2 * Copyright (c) 2015, 2017 Brocade Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore;
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertTrue;
13 import static org.junit.Assert.fail;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.eq;
16 import static org.mockito.Mockito.timeout;
17 import static org.mockito.Mockito.verify;
19 import akka.actor.ActorRef;
20 import akka.actor.ActorSelection;
21 import akka.actor.ActorSystem;
22 import akka.actor.Address;
23 import akka.actor.AddressFromURIString;
24 import akka.cluster.Cluster;
25 import akka.dispatch.Futures;
26 import akka.pattern.Patterns;
27 import akka.testkit.javadsl.TestKit;
28 import com.google.common.base.Optional;
29 import com.google.common.base.Stopwatch;
30 import com.google.common.base.Supplier;
31 import com.google.common.base.Throwables;
32 import com.google.common.collect.ImmutableMap;
33 import com.google.common.util.concurrent.ListenableFuture;
34 import com.google.common.util.concurrent.MoreExecutors;
35 import com.google.common.util.concurrent.Uninterruptibles;
36 import com.typesafe.config.ConfigFactory;
37 import java.math.BigInteger;
38 import java.util.Arrays;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.LinkedList;
42 import java.util.List;
43 import java.util.concurrent.ExecutionException;
44 import java.util.concurrent.TimeUnit;
45 import java.util.concurrent.atomic.AtomicLong;
46 import org.junit.After;
47 import org.junit.Assume;
48 import org.junit.Before;
49 import org.junit.Test;
50 import org.junit.runner.RunWith;
51 import org.junit.runners.Parameterized;
52 import org.junit.runners.Parameterized.Parameter;
53 import org.junit.runners.Parameterized.Parameters;
54 import org.mockito.Mockito;
55 import org.mockito.stubbing.Answer;
56 import org.opendaylight.controller.cluster.access.client.RequestTimeoutException;
57 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
58 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
59 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
60 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
61 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
62 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
63 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
64 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
65 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
66 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
68 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
69 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
70 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
71 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
72 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
73 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
74 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
75 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
76 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
77 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
78 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
79 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
80 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
81 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
82 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
83 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
84 import org.opendaylight.mdsal.common.api.TransactionChainListener;
85 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
86 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
87 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
88 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
89 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
90 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
91 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
92 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
93 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
94 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
95 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
96 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
97 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
98 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
99 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
100 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
101 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
102 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
103 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
104 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
105 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
106 import scala.concurrent.Await;
107 import scala.concurrent.Future;
108 import scala.concurrent.duration.FiniteDuration;
111 * End-to-end distributed data store tests that exercise remote shards and transactions.
113 * @author Thomas Pantelis
115 @RunWith(Parameterized.class)
116 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
118 @Parameters(name = "{0}")
119 public static Collection<Object[]> data() {
120 return Arrays.asList(new Object[][] {
121 { DistributedDataStore.class, 7}, { ClientBackedDataStore.class, 12 }
126 public Class<? extends AbstractDataStore> testParameter;
128 public int commitTimeout;
130 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
131 private static final String[] CARS = {"cars"};
133 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
134 "akka://cluster-test@127.0.0.1:2558");
135 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
136 "akka://cluster-test@127.0.0.1:2559");
138 private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
139 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
140 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
141 private static final String MODULE_SHARDS_CARS_1_2_3 = "module-shards-cars-member-1-and-2-and-3.conf";
143 private ActorSystem leaderSystem;
144 private ActorSystem followerSystem;
145 private ActorSystem follower2System;
147 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
148 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
150 private final DatastoreContext.Builder followerDatastoreContextBuilder =
151 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
152 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
153 private final TransactionIdentifier tx1 = nextTransactionId();
154 private final TransactionIdentifier tx2 = nextTransactionId();
156 private AbstractDataStore followerDistributedDataStore;
157 private AbstractDataStore leaderDistributedDataStore;
158 private IntegrationTestKit followerTestKit;
159 private IntegrationTestKit leaderTestKit;
162 public void setUp() {
163 InMemoryJournal.clear();
164 InMemorySnapshotStore.clear();
166 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
167 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
169 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
170 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
172 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
173 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
177 public void tearDown() {
178 if (followerDistributedDataStore != null) {
179 leaderDistributedDataStore.close();
181 if (leaderDistributedDataStore != null) {
182 leaderDistributedDataStore.close();
185 TestKit.shutdownActorSystem(leaderSystem);
186 TestKit.shutdownActorSystem(followerSystem);
187 TestKit.shutdownActorSystem(follower2System);
189 InMemoryJournal.clear();
190 InMemorySnapshotStore.clear();
193 private void initDatastoresWithCars(final String type) throws Exception {
194 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
197 private void initDatastoresWithCarsAndPeople(final String type) throws Exception {
198 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
201 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards)
203 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder, commitTimeout);
205 leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
206 testParameter, type, moduleShardsConfig, false, shards);
208 followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder, commitTimeout);
209 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
210 testParameter, type, moduleShardsConfig, false, shards);
212 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), shards);
214 leaderTestKit.waitForMembersUp("member-2");
215 followerTestKit.waitForMembersUp("member-1");
218 private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
220 final Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
221 assertEquals("isPresent", true, optional.isPresent());
223 final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
224 CarsModel.CAR_QNAME);
225 for (final NormalizedNode<?, ?> entry: entries) {
226 listBuilder.withChild((MapEntryNode) entry);
229 assertEquals("Car list node", listBuilder.build(), optional.get());
232 private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
233 final NormalizedNode<?, ?> expNode) throws Exception {
234 final Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
235 assertEquals("isPresent", true, optional.isPresent());
236 assertEquals("Data node", expNode, optional.get());
239 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
241 final Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
242 assertEquals("exists", true, exists);
246 public void testWriteTransactionWithSingleShard() throws Exception {
247 final String testName = "testWriteTransactionWithSingleShard";
248 initDatastoresWithCars(testName);
250 final String followerCarShardName = "member-2-shard-cars-" + testName;
252 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
253 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
255 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
256 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
258 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
259 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
260 writeTx.merge(car1Path, car1);
262 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
263 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
264 writeTx.merge(car2Path, car2);
266 followerTestKit.doCommit(writeTx.ready());
268 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
270 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
274 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
276 writeTx.delete(car1Path);
278 followerTestKit.doCommit(writeTx.ready());
280 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
282 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
284 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
286 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
288 // The following is a bit tricky. Before we reinstate the follower we need to ensure it has persisted and
289 // applied and all the log entries from the leader. Since we've verified the car data above we know that
290 // all the transactions have been applied on the leader so we first read and capture its lastAppliedIndex.
291 final AtomicLong leaderLastAppliedIndex = new AtomicLong();
292 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, CARS[0],
293 state -> leaderLastAppliedIndex.set(state.getLastApplied()));
295 // Now we need to make sure the follower has persisted the leader's lastAppliedIndex via ApplyJournalEntries.
296 // However we don't know exactly how many ApplyJournalEntries messages there will be as it can differ between
297 // the tell-based and ask-based front-ends. For ask-based there will be exactly 2 ApplyJournalEntries but
298 // tell-based persists additional payloads which could be replicated and applied in a batch resulting in
299 // either 2 or 3 ApplyJournalEntries. To handle this we read the follower's persisted ApplyJournalEntries
300 // until we find the one that encompasses the leader's lastAppliedIndex.
301 Stopwatch sw = Stopwatch.createStarted();
302 boolean done = false;
304 final List<ApplyJournalEntries> entries = InMemoryJournal.get(followerCarShardName,
305 ApplyJournalEntries.class);
306 for (ApplyJournalEntries aje: entries) {
307 if (aje.getToIndex() >= leaderLastAppliedIndex.get()) {
313 assertTrue("Follower did not persist ApplyJournalEntries containing leader's lastAppliedIndex "
314 + leaderLastAppliedIndex + ". Entries persisted: " + entries, sw.elapsed(TimeUnit.SECONDS) <= 5);
316 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
319 TestKit.shutdownActorSystem(leaderSystem, Boolean.TRUE);
320 TestKit.shutdownActorSystem(followerSystem, Boolean.TRUE);
322 final ActorSystem newSystem = newActorSystem("reinstated-member2", "Member2");
324 try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder,
326 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS)) {
327 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
332 public void testReadWriteTransactionWithSingleShard() throws Exception {
333 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
335 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
336 assertNotNull("newReadWriteTransaction returned null", rwTx);
338 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
339 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
341 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
342 rwTx.merge(CarsModel.newCarPath("optima"), car1);
344 verifyCars(rwTx, car1);
346 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
347 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
348 rwTx.merge(car2Path, car2);
350 verifyExists(rwTx, car2Path);
352 followerTestKit.doCommit(rwTx.ready());
354 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
358 public void testWriteTransactionWithMultipleShards() throws Exception {
359 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
361 final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
362 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
364 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
365 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
366 writeTx.write(carsPath, carsNode);
368 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
369 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
370 writeTx.write(peoplePath, peopleNode);
372 followerTestKit.doCommit(writeTx.ready());
374 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
376 verifyNode(readTx, carsPath, carsNode);
377 verifyNode(readTx, peoplePath, peopleNode);
381 public void testReadWriteTransactionWithMultipleShards() throws Exception {
382 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
384 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
385 assertNotNull("newReadWriteTransaction returned null", rwTx);
387 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
388 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
389 rwTx.write(carsPath, carsNode);
391 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
392 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
393 rwTx.write(peoplePath, peopleNode);
395 followerTestKit.doCommit(rwTx.ready());
397 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
399 verifyNode(readTx, carsPath, carsNode);
400 verifyNode(readTx, peoplePath, peopleNode);
404 public void testTransactionChainWithSingleShard() throws Exception {
405 initDatastoresWithCars("testTransactionChainWithSingleShard");
407 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
409 // Add the top-level cars container with write-only.
411 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
412 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
414 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
416 final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
418 // Verify the top-level cars container with read-only.
420 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
422 // Perform car operations with read-write.
424 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
426 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
428 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
430 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
431 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
432 rwTx.write(car1Path, car1);
434 verifyExists(rwTx, car1Path);
436 verifyCars(rwTx, car1);
438 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
439 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
441 rwTx.delete(car1Path);
443 followerTestKit.doCommit(writeTxReady);
445 followerTestKit.doCommit(rwTx.ready());
449 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
453 public void testTransactionChainWithMultipleShards() throws Exception {
454 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
456 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
458 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
459 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
461 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
462 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
464 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
465 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
467 followerTestKit.doCommit(writeTx.ready());
469 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
471 final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
472 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
473 readWriteTx.write(carPath, car);
475 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
476 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
477 readWriteTx.merge(personPath, person);
479 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
480 assertEquals("isPresent", true, optional.isPresent());
481 assertEquals("Data node", car, optional.get());
483 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
484 assertEquals("isPresent", true, optional.isPresent());
485 assertEquals("Data node", person, optional.get());
487 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
489 writeTx = txChain.newWriteOnlyTransaction();
491 writeTx.delete(personPath);
493 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
495 followerTestKit.doCommit(cohort2);
496 followerTestKit.doCommit(cohort3);
500 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
501 verifyCars(readTx, car);
503 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
504 assertEquals("isPresent", false, optional.isPresent());
508 public void testChainedTransactionFailureWithSingleShard() throws Exception {
509 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
511 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
512 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
513 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
514 MoreExecutors.directExecutor());
516 final TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
517 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
519 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
521 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
522 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
523 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
525 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
528 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
529 fail("Expected TransactionCommitFailedException");
530 } catch (final TransactionCommitFailedException e) {
534 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
541 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
542 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
544 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
545 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
546 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
547 MoreExecutors.directExecutor());
549 final TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
550 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
552 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
554 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
556 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
557 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
558 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
560 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
561 // done for put for performance reasons.
562 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
565 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
566 fail("Expected TransactionCommitFailedException");
567 } catch (final TransactionCommitFailedException e) {
571 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
578 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
579 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
580 final String testName = "testSingleShardTransactionsWithLeaderChanges";
581 initDatastoresWithCars(testName);
583 final String followerCarShardName = "member-2-shard-cars-" + testName;
584 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class);
586 // Write top-level car container from the follower so it uses a remote Tx.
588 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
590 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
591 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
593 followerTestKit.doCommit(writeTx.ready());
595 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
597 // Switch the leader to the follower
599 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
600 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
602 TestKit.shutdownActorSystem(leaderSystem, true);
603 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
605 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorContext(), CARS);
607 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
608 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
610 final DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
611 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
612 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
614 try (AbstractDataStore ds =
615 newMember1TestKit.setupAbstractDataStore(
616 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
618 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), CARS);
620 // Write a car entry to the new leader - should switch to local Tx
622 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
624 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
625 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
626 writeTx.merge(car1Path, car1);
628 followerTestKit.doCommit(writeTx.ready());
630 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
634 @SuppressWarnings("unchecked")
636 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
637 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
638 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
640 final Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext()
641 .findLocalShard("cars");
642 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
644 final DataTree dataTree = new InMemoryDataTreeFactory().create(
645 DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
647 // Send a tx with immediate commit.
649 DataTreeModification modification = dataTree.takeSnapshot().newModification();
650 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
651 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
653 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
654 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
655 modification.ready();
657 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true);
659 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
660 Object resp = followerTestKit.expectMsgClass(Object.class);
661 if (resp instanceof akka.actor.Status.Failure) {
662 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
665 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
667 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
669 // Send another tx without immediate commit.
671 modification = dataTree.takeSnapshot().newModification();
672 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
673 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
674 modification.ready();
676 readyLocal = new ReadyLocalTransaction(tx2 , modification, false);
678 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
679 resp = followerTestKit.expectMsgClass(Object.class);
680 if (resp instanceof akka.actor.Status.Failure) {
681 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
684 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
686 final ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
687 ((ReadyTransactionReply)resp).getCohortPath());
689 final Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
690 Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
691 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
692 leaderDistributedDataStore.getActorContext(), Arrays.asList(
693 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), tx2);
694 cohort.canCommit().get(5, TimeUnit.SECONDS);
695 cohort.preCommit().get(5, TimeUnit.SECONDS);
696 cohort.commit().get(5, TimeUnit.SECONDS);
698 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
701 @SuppressWarnings("unchecked")
703 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
704 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
705 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
707 final Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext()
708 .findLocalShard("cars");
709 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
711 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
712 final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
714 // Send a tx with immediate commit.
716 DataTreeModification modification = dataTree.takeSnapshot().newModification();
717 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
718 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
720 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
721 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
723 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1,
724 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
725 Mockito.mock(ShardDataTreeTransactionParent.class), tx1, modification), true);
727 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
728 Object resp = followerTestKit.expectMsgClass(Object.class);
729 if (resp instanceof akka.actor.Status.Failure) {
730 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
733 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
735 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
737 // Send another tx without immediate commit.
739 modification = dataTree.takeSnapshot().newModification();
740 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
741 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
743 forwardedReady = new ForwardedReadyTransaction(tx2,
744 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
745 Mockito.mock(ShardDataTreeTransactionParent.class), tx2, modification), false);
747 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
748 resp = followerTestKit.expectMsgClass(Object.class);
749 if (resp instanceof akka.actor.Status.Failure) {
750 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
753 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
755 ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
756 ((ReadyTransactionReply)resp).getCohortPath());
758 final Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
759 Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
760 final ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
761 leaderDistributedDataStore.getActorContext(), Arrays.asList(
762 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), tx2);
763 cohort.canCommit().get(5, TimeUnit.SECONDS);
764 cohort.preCommit().get(5, TimeUnit.SECONDS);
765 cohort.commit().get(5, TimeUnit.SECONDS);
767 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
771 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
772 //TODO remove when test passes also for ClientBackedDataStore
773 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
774 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
775 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
776 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
778 // Do an initial write to get the primary shard info cached.
780 final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
781 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
782 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
783 followerTestKit.doCommit(initialWriteTx.ready());
785 // Wait for the commit to be replicated to the follower.
787 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
788 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
790 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
791 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
793 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
796 final DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
797 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
798 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
799 final DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
800 final ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
801 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
803 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
804 // in the leader shard.
806 final DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
807 final LinkedList<MapEntryNode> cars = new LinkedList<>();
809 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
810 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
812 NormalizedNode<?, ?> people = PeopleModel.newPersonMapNode();
813 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
814 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
816 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
817 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
818 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
821 final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
822 for (int i = 1; i <= 5; i++, carIndex++) {
823 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
824 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
827 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
830 final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
831 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
832 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
835 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
836 // leader shard on ready.
838 final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
839 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
840 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
842 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
843 stats -> assertEquals("getReadWriteTransactionCount", 1, stats.getReadWriteTransactionCount()));
845 // Disable elections on the leader so it switches to follower.
847 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
848 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
849 .shardElectionTimeoutFactor(10));
851 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorContext(), "cars");
853 // Submit all tx's - the messages should get queued for retry.
855 final ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
856 final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
857 final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
858 final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
860 // Enable elections on the other follower so it becomes the leader, at which point the
861 // tx's should get forwarded from the previous leader to the new leader to complete the commits.
863 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
864 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
865 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorContext(), "cars")
866 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
867 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorContext(), "people")
868 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
870 followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
871 followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
872 followerTestKit.doCommit(writeTx3Cohort);
873 followerTestKit.doCommit(writeTx4Cohort);
874 followerTestKit.doCommit(rwTxCohort);
876 DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
877 verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
878 verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
882 public void testLeadershipTransferOnShutdown() throws Exception {
883 //TODO remove when test passes also for ClientBackedDataStore
884 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
885 leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
886 followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
887 final String testName = "testLeadershipTransferOnShutdown";
888 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
890 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
891 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(100),
893 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
894 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
896 followerTestKit.waitForMembersUp("member-3");
897 follower2TestKit.waitForMembersUp("member-1", "member-2");
899 // Create and submit a couple tx's so they're pending.
901 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
902 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
903 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
904 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
905 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
907 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
908 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
910 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
911 final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
912 writeTx.write(CarsModel.newCarPath("optima"), car);
913 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
915 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
916 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
918 // Gracefully stop the leader via a Shutdown message.
920 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
921 .shardElectionTimeoutFactor(100));
923 final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
924 final Future<ActorRef> future = leaderDistributedDataStore.getActorContext().findLocalShardAsync("cars");
925 final ActorRef leaderActor = Await.result(future, duration);
927 final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
929 // Commit the 2 transactions. They should finish and succeed.
931 followerTestKit.doCommit(cohort1);
932 followerTestKit.doCommit(cohort2);
934 // Wait for the leader actor stopped.
936 final Boolean stopped = Await.result(stopFuture, duration);
937 assertEquals("Stopped", Boolean.TRUE, stopped);
939 // Verify leadership was transferred by reading the committed data from the other nodes.
941 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
942 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
947 public void testTransactionWithIsolatedLeader() throws Exception {
948 //TODO remove when test passes also for ClientBackedDataStore
949 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
950 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
951 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
952 final String testName = "testTransactionWithIsolatedLeader";
953 initDatastoresWithCars(testName);
955 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
956 final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
957 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
959 // Tx that is submitted after the leader transitions to IsolatedLeader.
960 final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
961 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
963 // Tx that is submitted after the follower is reinstated.
964 final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
965 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
968 followerTestKit.watch(followerDistributedDataStore.getActorContext().getShardManager());
969 followerDistributedDataStore.close();
970 followerTestKit.expectTerminated(followerDistributedDataStore.getActorContext().getShardManager());
972 // Submit the preIsolatedLeaderWriteTx so it's pending
973 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
975 // Change the isolated leader check interval low so it changes to IsolatedLeader.
976 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
977 .shardIsolatedLeaderCheckIntervalInMillis(200));
979 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
980 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
983 leaderTestKit.doCommit(noShardLeaderWriteTx.ready());
984 fail("Expected NoShardLeaderException");
985 } catch (final ExecutionException e) {
986 assertEquals("getCause", NoShardLeaderException.class, Throwables.getRootCause(e).getClass());
989 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
990 .shardElectionTimeoutFactor(100));
992 final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
994 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
995 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
997 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
998 leaderTestKit.doCommit(successTxCohort);
1002 public void testTransactionWithShardLeaderNotResponding() throws Exception {
1003 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1004 followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
1005 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
1007 // Do an initial read to get the primary shard info cached.
1009 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1010 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1012 // Shutdown the leader and try to create a new tx.
1014 TestKit.shutdownActorSystem(leaderSystem, true);
1016 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
1017 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
1019 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1021 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1024 followerTestKit.doCommit(rwTx.ready());
1025 fail("Exception expected");
1026 } catch (final ExecutionException e) {
1027 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(e.getCause());
1028 if (DistributedDataStore.class.equals(testParameter)) {
1029 assertTrue(msg, Throwables.getRootCause(e) instanceof NoShardLeaderException
1030 || e.getCause() instanceof ShardLeaderNotRespondingException);
1032 assertTrue(msg, Throwables.getRootCause(e) instanceof RequestTimeoutException);
1038 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
1039 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1040 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
1042 // Do an initial read to get the primary shard info cached.
1044 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1045 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1047 // Shutdown the leader and try to create a new tx.
1049 TestKit.shutdownActorSystem(leaderSystem, true);
1051 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1053 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1055 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1056 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1058 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1060 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1063 followerTestKit.doCommit(rwTx.ready());
1064 fail("Exception expected");
1065 } catch (final ExecutionException e) {
1066 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(e.getCause());
1067 if (DistributedDataStore.class.equals(testParameter)) {
1068 assertTrue(msg, Throwables.getRootCause(e) instanceof NoShardLeaderException);
1070 assertTrue(msg, Throwables.getRootCause(e) instanceof RequestTimeoutException);
1076 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1077 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
1078 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1079 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1081 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1082 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1083 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1084 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1086 try (AbstractDataStore ds =
1087 follower2TestKit.setupAbstractDataStore(
1088 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS)) {
1090 followerTestKit.waitForMembersUp("member-1", "member-3");
1091 follower2TestKit.waitForMembersUp("member-1", "member-2");
1093 // Do an initial read to get the primary shard info cached.
1095 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1096 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1098 // Shutdown the leader and try to create a new tx.
1100 TestKit.shutdownActorSystem(leaderSystem, true);
1102 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1104 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1105 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(5).customRaftPolicyImplementation(null));
1107 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1109 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1111 followerTestKit.doCommit(rwTx.ready());
1116 public void testInstallSnapshot() throws Exception {
1117 final String testName = "testInstallSnapshot";
1118 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1119 final String followerCarShardName = "member-2-shard-cars-" + testName;
1121 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1122 // install a snapshot to sync the follower.
1124 DataTree tree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION,
1125 SchemaContextHelper.full());
1127 final ContainerNode carsNode = CarsModel.newCarsNode(
1128 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", BigInteger.valueOf(20000))));
1129 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1131 final NormalizedNode<?, ?> snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.EMPTY);
1132 final Snapshot initialSnapshot = Snapshot.create(
1133 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1134 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1135 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1137 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1138 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1140 initDatastoresWithCars(testName);
1142 final Optional<NormalizedNode<?, ?>> readOptional = leaderDistributedDataStore.newReadOnlyTransaction().read(
1143 CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1144 assertEquals("isPresent", true, readOptional.isPresent());
1145 assertEquals("Node", carsNode, readOptional.get());
1147 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1148 initialSnapshot, snapshotRoot);
1150 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1151 initialSnapshot, snapshotRoot);
1155 public void testReadWriteMessageSlicing() throws Exception {
1156 // The slicing is only implemented for tell-based protocol
1157 Assume.assumeTrue(testParameter.equals(ClientBackedDataStore.class));
1159 leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
1160 followerDatastoreContextBuilder.maximumMessageSliceSize(100);
1161 initDatastoresWithCars("testLargeReadReplySlicing");
1163 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1165 final NormalizedNode<?, ?> carsNode = CarsModel.create();
1166 rwTx.write(CarsModel.BASE_PATH, carsNode);
1168 verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
1171 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1172 final NormalizedNode<?, ?> expRoot) {
1173 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1174 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1175 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1176 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1177 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1178 MetadataShardDataTreeSnapshot shardSnapshot =
1179 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1180 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1183 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1184 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1185 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
1186 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1187 Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1188 Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
1189 dataStore.onDatastoreContextUpdated(mockContextFactory);