2 * Copyright (c) 2015 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.JavaTestKit;
28 import com.google.common.base.Optional;
29 import com.google.common.base.Supplier;
30 import com.google.common.base.Throwables;
31 import com.google.common.collect.ImmutableMap;
32 import com.google.common.util.concurrent.ListenableFuture;
33 import com.google.common.util.concurrent.MoreExecutors;
34 import com.google.common.util.concurrent.Uninterruptibles;
35 import com.typesafe.config.ConfigFactory;
36 import java.math.BigInteger;
37 import java.util.Arrays;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.LinkedList;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.TimeUnit;
43 import org.junit.After;
44 import org.junit.Assume;
45 import org.junit.Before;
46 import org.junit.Test;
47 import org.junit.runner.RunWith;
48 import org.junit.runners.Parameterized;
49 import org.junit.runners.Parameterized.Parameter;
50 import org.junit.runners.Parameterized.Parameters;
51 import org.mockito.Mockito;
52 import org.mockito.stubbing.Answer;
53 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
54 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
55 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
56 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
57 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
58 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
59 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
60 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
61 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
62 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
64 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
65 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
66 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
67 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
68 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
69 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
70 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
71 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
72 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
73 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
74 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
75 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
76 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
77 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
78 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
79 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
80 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
81 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
82 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
83 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
84 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
85 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
86 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
87 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
88 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
89 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
90 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
95 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
96 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
97 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
98 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
99 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
102 import scala.concurrent.Await;
103 import scala.concurrent.Future;
104 import scala.concurrent.duration.FiniteDuration;
107 * End-to-end distributed data store tests that exercise remote shards and transactions.
109 * @author Thomas Pantelis
111 @RunWith(Parameterized.class)
112 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
114 @Parameters(name = "{0}")
115 public static Collection<Object[]> data() {
116 return Arrays.asList(new Object[][] {
117 { DistributedDataStore.class, 7}, { ClientBackedDataStore.class, 60 }
122 public Class<? extends AbstractDataStore> testParameter;
124 public int commitTimeout;
126 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
127 private static final String[] CARS = {"cars"};
129 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
130 "akka://cluster-test@127.0.0.1:2558");
131 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
132 "akka://cluster-test@127.0.0.1:2559");
134 private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
135 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
136 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
138 private ActorSystem leaderSystem;
139 private ActorSystem followerSystem;
140 private ActorSystem follower2System;
142 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
143 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
145 private final DatastoreContext.Builder followerDatastoreContextBuilder =
146 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
147 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
148 private final TransactionIdentifier tx1 = nextTransactionId();
149 private final TransactionIdentifier tx2 = nextTransactionId();
151 private AbstractDataStore followerDistributedDataStore;
152 private AbstractDataStore leaderDistributedDataStore;
153 private IntegrationTestKit followerTestKit;
154 private IntegrationTestKit leaderTestKit;
157 public void setUp() {
158 InMemoryJournal.clear();
159 InMemorySnapshotStore.clear();
161 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
162 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
164 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
165 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
167 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
168 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
172 public void tearDown() {
173 if (followerDistributedDataStore != null) {
174 leaderDistributedDataStore.close();
176 if (leaderDistributedDataStore != null) {
177 leaderDistributedDataStore.close();
180 JavaTestKit.shutdownActorSystem(leaderSystem);
181 JavaTestKit.shutdownActorSystem(followerSystem);
182 JavaTestKit.shutdownActorSystem(follower2System);
184 InMemoryJournal.clear();
185 InMemorySnapshotStore.clear();
188 private void initDatastoresWithCars(final String type) throws Exception {
189 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
192 private void initDatastoresWithCarsAndPeople(final String type) throws Exception {
193 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
196 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards)
198 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder, commitTimeout);
200 leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
201 testParameter, type, moduleShardsConfig, false, shards);
203 followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder, commitTimeout);
204 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
205 testParameter, type, moduleShardsConfig, false, shards);
207 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), shards);
210 private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
212 final Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
213 assertEquals("isPresent", true, optional.isPresent());
215 final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
216 CarsModel.CAR_QNAME);
217 for (final NormalizedNode<?, ?> entry: entries) {
218 listBuilder.withChild((MapEntryNode) entry);
221 assertEquals("Car list node", listBuilder.build(), optional.get());
224 private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
225 final NormalizedNode<?, ?> expNode) throws Exception {
226 final Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
227 assertEquals("isPresent", true, optional.isPresent());
228 assertEquals("Data node", expNode, optional.get());
231 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
233 final Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
234 assertEquals("exists", true, exists);
238 public void testWriteTransactionWithSingleShard() throws Exception {
239 final String testName = "testWriteTransactionWithSingleShard";
240 initDatastoresWithCars(testName);
242 final String followerCarShardName = "member-2-shard-cars-" + testName;
243 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 2, ApplyJournalEntries.class);
245 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
246 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
248 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
249 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
251 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
252 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
253 writeTx.merge(car1Path, car1);
255 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
256 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
257 writeTx.merge(car2Path, car2);
259 followerTestKit.doCommit(writeTx.ready());
261 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
263 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
267 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
269 writeTx.delete(car1Path);
271 followerTestKit.doCommit(writeTx.ready());
273 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
275 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
277 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
279 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
281 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
283 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
284 JavaTestKit.shutdownActorSystem(followerSystem, null, true);
286 final ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load()
287 .getConfig("Member2"));
289 try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder,
291 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS_AND_PEOPLE)) {
292 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
295 JavaTestKit.shutdownActorSystem(newSystem);
299 public void testReadWriteTransactionWithSingleShard() throws Exception {
300 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
302 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
303 assertNotNull("newReadWriteTransaction returned null", rwTx);
305 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
306 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
308 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
309 rwTx.merge(CarsModel.newCarPath("optima"), car1);
311 verifyCars(rwTx, car1);
313 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
314 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
315 rwTx.merge(car2Path, car2);
317 verifyExists(rwTx, car2Path);
319 followerTestKit.doCommit(rwTx.ready());
321 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
325 public void testWriteTransactionWithMultipleShards() throws Exception {
326 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
328 final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
329 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
331 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
332 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
333 writeTx.write(carsPath, carsNode);
335 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
336 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
337 writeTx.write(peoplePath, peopleNode);
339 followerTestKit.doCommit(writeTx.ready());
341 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
343 verifyNode(readTx, carsPath, carsNode);
344 verifyNode(readTx, peoplePath, peopleNode);
348 public void testReadWriteTransactionWithMultipleShards() throws Exception {
349 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
351 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
352 assertNotNull("newReadWriteTransaction returned null", rwTx);
354 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
355 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
356 rwTx.write(carsPath, carsNode);
358 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
359 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
360 rwTx.write(peoplePath, peopleNode);
362 followerTestKit.doCommit(rwTx.ready());
364 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
366 verifyNode(readTx, carsPath, carsNode);
367 verifyNode(readTx, peoplePath, peopleNode);
371 public void testTransactionChainWithSingleShard() throws Exception {
372 initDatastoresWithCars("testTransactionChainWithSingleShard");
374 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
376 // Add the top-level cars container with write-only.
378 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
379 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
381 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
383 final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
385 // Verify the top-level cars container with read-only.
387 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
389 // Perform car operations with read-write.
391 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
393 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
395 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
397 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
398 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
399 rwTx.write(car1Path, car1);
401 verifyExists(rwTx, car1Path);
403 verifyCars(rwTx, car1);
405 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
406 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
408 rwTx.delete(car1Path);
410 followerTestKit.doCommit(writeTxReady);
412 followerTestKit.doCommit(rwTx.ready());
416 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
420 public void testTransactionChainWithMultipleShards() throws Exception {
421 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
423 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
425 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
426 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
428 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
429 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
431 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
432 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
434 followerTestKit.doCommit(writeTx.ready());
436 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
438 final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
439 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
440 readWriteTx.write(carPath, car);
442 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
443 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
444 readWriteTx.merge(personPath, person);
446 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
447 assertEquals("isPresent", true, optional.isPresent());
448 assertEquals("Data node", car, optional.get());
450 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
451 assertEquals("isPresent", true, optional.isPresent());
452 assertEquals("Data node", person, optional.get());
454 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
456 writeTx = txChain.newWriteOnlyTransaction();
458 writeTx.delete(personPath);
460 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
462 followerTestKit.doCommit(cohort2);
463 followerTestKit.doCommit(cohort3);
467 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
468 verifyCars(readTx, car);
470 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
471 assertEquals("isPresent", false, optional.isPresent());
475 public void testChainedTransactionFailureWithSingleShard() throws Exception {
476 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
478 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
479 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
480 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
481 MoreExecutors.directExecutor());
483 final TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
484 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
486 final DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
488 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
489 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
490 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
492 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
495 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
496 fail("Expected TransactionCommitFailedException");
497 } catch (final TransactionCommitFailedException e) {
501 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
508 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
509 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
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 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
521 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
523 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
524 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
525 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
527 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
528 // done for put for performance reasons.
529 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
532 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
533 fail("Expected TransactionCommitFailedException");
534 } catch (final TransactionCommitFailedException e) {
538 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
545 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
546 final String testName = "testSingleShardTransactionsWithLeaderChanges";
547 initDatastoresWithCars(testName);
549 final String followerCarShardName = "member-2-shard-cars-" + testName;
550 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class);
552 // Write top-level car container from the follower so it uses a remote Tx.
554 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
556 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
557 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
559 followerTestKit.doCommit(writeTx.ready());
561 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
563 // Switch the leader to the follower
565 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
566 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
568 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
569 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
571 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorContext(), CARS);
573 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
574 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
576 final DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
577 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
578 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
580 try (final AbstractDataStore ds =
581 newMember1TestKit.setupAbstractDataStore(
582 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
584 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), CARS);
586 // Write a car entry to the new leader - should switch to local Tx
588 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
590 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
591 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
592 writeTx.merge(car1Path, car1);
594 followerTestKit.doCommit(writeTx.ready());
596 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
600 @SuppressWarnings("unchecked")
602 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
603 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
604 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
606 final Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext()
607 .findLocalShard("cars");
608 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
610 final TipProducingDataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
611 dataTree.setSchemaContext(SchemaContextHelper.full());
613 // Send a tx with immediate commit.
615 DataTreeModification modification = dataTree.takeSnapshot().newModification();
616 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
617 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
619 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
620 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
621 modification.ready();
623 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true);
625 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
626 Object resp = followerTestKit.expectMsgClass(Object.class);
627 if (resp instanceof akka.actor.Status.Failure) {
628 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
631 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
633 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
635 // Send another tx without immediate commit.
637 modification = dataTree.takeSnapshot().newModification();
638 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
639 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
640 modification.ready();
642 readyLocal = new ReadyLocalTransaction(tx2 , modification, false);
644 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
645 resp = followerTestKit.expectMsgClass(Object.class);
646 if (resp instanceof akka.actor.Status.Failure) {
647 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
650 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
652 final ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
653 ((ReadyTransactionReply)resp).getCohortPath());
655 final Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
656 Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
657 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
658 leaderDistributedDataStore.getActorContext(), Arrays.asList(
659 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), tx2);
660 cohort.canCommit().get(5, TimeUnit.SECONDS);
661 cohort.preCommit().get(5, TimeUnit.SECONDS);
662 cohort.commit().get(5, TimeUnit.SECONDS);
664 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
667 @SuppressWarnings("unchecked")
669 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
670 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
671 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
673 final Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext()
674 .findLocalShard("cars");
675 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
677 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
678 final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
680 // Send a tx with immediate commit.
682 DataTreeModification modification = dataTree.takeSnapshot().newModification();
683 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
684 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
686 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
687 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
689 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1,
690 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
691 Mockito.mock(ShardDataTreeTransactionParent.class), tx1, modification), true);
693 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
694 Object resp = followerTestKit.expectMsgClass(Object.class);
695 if (resp instanceof akka.actor.Status.Failure) {
696 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
699 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
701 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
703 // Send another tx without immediate commit.
705 modification = dataTree.takeSnapshot().newModification();
706 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
707 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
709 forwardedReady = new ForwardedReadyTransaction(tx2,
710 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
711 Mockito.mock(ShardDataTreeTransactionParent.class), tx2, modification), false);
713 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
714 resp = followerTestKit.expectMsgClass(Object.class);
715 if (resp instanceof akka.actor.Status.Failure) {
716 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
719 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
721 ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
722 ((ReadyTransactionReply)resp).getCohortPath());
724 final Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
725 Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
726 final ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
727 leaderDistributedDataStore.getActorContext(), Arrays.asList(
728 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), tx2);
729 cohort.canCommit().get(5, TimeUnit.SECONDS);
730 cohort.preCommit().get(5, TimeUnit.SECONDS);
731 cohort.commit().get(5, TimeUnit.SECONDS);
733 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
737 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
738 //TODO remove when test passes also for ClientBackedDataStore
739 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
740 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
741 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
742 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
744 // Do an initial write to get the primary shard info cached.
746 final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
747 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
748 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
749 followerTestKit.doCommit(initialWriteTx.ready());
751 // Wait for the commit to be replicated to the follower.
753 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
754 raftState -> assertEquals("getLastApplied", 0, raftState.getLastApplied()));
756 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
757 raftState -> assertEquals("getLastApplied", 0, raftState.getLastApplied()));
759 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
762 final DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
763 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
764 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
765 final DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
766 final ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
767 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
769 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
770 // in the leader shard.
772 final DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
773 final LinkedList<MapEntryNode> cars = new LinkedList<>();
775 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
776 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
778 NormalizedNode<?, ?> people = PeopleModel.newPersonMapNode();
779 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
780 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
782 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
783 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
784 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
787 final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
788 for (int i = 1; i <= 5; i++, carIndex++) {
789 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
790 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
793 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
796 final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
797 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
798 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
801 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
802 // leader shard on ready.
804 final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
805 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
806 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
808 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
809 stats -> assertEquals("getReadWriteTransactionCount", 1, stats.getReadWriteTransactionCount()));
811 // Disable elections on the leader so it switches to follower.
813 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
814 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
815 .shardElectionTimeoutFactor(10));
817 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
818 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorContext(), "cars");
820 // Submit all tx's - the messages should get queued for retry.
822 final ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
823 final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
824 final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
825 final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
827 // Enable elections on the other follower so it becomes the leader, at which point the
828 // tx's should get forwarded from the previous leader to the new leader to complete the commits.
830 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
831 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
833 followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
834 followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
835 followerTestKit.doCommit(writeTx3Cohort);
836 followerTestKit.doCommit(writeTx4Cohort);
837 followerTestKit.doCommit(rwTxCohort);
839 DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
840 verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
841 verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
845 public void testLeadershipTransferOnShutdown() throws Exception {
846 //TODO remove when test passes also for ClientBackedDataStore
847 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
848 leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
849 followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
850 final String testName = "testLeadershipTransferOnShutdown";
851 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
853 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
854 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(100),
856 try (final AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
857 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
859 // Create and submit a couple tx's so they're pending.
861 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
862 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
863 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
864 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
865 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
867 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
868 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
870 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
871 final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
872 writeTx.write(CarsModel.newCarPath("optima"), car);
873 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
875 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
876 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
878 // Gracefully stop the leader via a Shutdown message.
880 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
881 .shardElectionTimeoutFactor(100));
883 final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
884 final Future<ActorRef> future = leaderDistributedDataStore.getActorContext().findLocalShardAsync("cars");
885 final ActorRef leaderActor = Await.result(future, duration);
887 final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
889 // Commit the 2 transactions. They should finish and succeed.
891 followerTestKit.doCommit(cohort1);
892 followerTestKit.doCommit(cohort2);
894 // Wait for the leader actor stopped.
896 final Boolean stopped = Await.result(stopFuture, duration);
897 assertEquals("Stopped", Boolean.TRUE, stopped);
899 // Verify leadership was transferred by reading the committed data from the other nodes.
901 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
902 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
907 public void testTransactionWithIsolatedLeader() throws Exception {
908 //TODO remove when test passes also for ClientBackedDataStore
909 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
910 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
911 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
912 final String testName = "testTransactionWithIsolatedLeader";
913 initDatastoresWithCars(testName);
915 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
916 final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
917 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
919 // Tx that is submitted after the leader transitions to IsolatedLeader.
920 final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
921 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
923 // Tx that is submitted after the follower is reinstated.
924 final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
925 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
928 followerTestKit.watch(followerDistributedDataStore.getActorContext().getShardManager());
929 followerDistributedDataStore.close();
930 followerTestKit.expectTerminated(followerDistributedDataStore.getActorContext().getShardManager());
932 // Submit the preIsolatedLeaderWriteTx so it's pending
933 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
935 // Change the isolated leader check interval low so it changes to IsolatedLeader.
936 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
937 .shardIsolatedLeaderCheckIntervalInMillis(200));
939 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
940 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
943 leaderTestKit.doCommit(noShardLeaderWriteTx.ready());
944 fail("Expected NoShardLeaderException");
945 } catch (final ExecutionException e) {
946 assertEquals("getCause", NoShardLeaderException.class, Throwables.getRootCause(e).getClass());
949 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
950 .shardElectionTimeoutFactor(100));
952 final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
954 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
955 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
957 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
958 leaderTestKit.doCommit(successTxCohort);
962 public void testTransactionWithShardLeaderNotResponding() throws Exception {
963 followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
964 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
966 // Do an initial read to get the primary shard info cached.
968 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
969 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
971 // Shutdown the leader and try to create a new tx.
973 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
975 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
976 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
978 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
980 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
983 followerTestKit.doCommit(rwTx.ready());
984 fail("Exception expected");
985 } catch (final ExecutionException e) {
986 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(e.getCause());
987 assertTrue(msg, Throwables.getRootCause(e) instanceof NoShardLeaderException
988 || e.getCause() instanceof ShardLeaderNotRespondingException);
993 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
994 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
996 // Do an initial read to get the primary shard info cached.
998 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
999 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1001 // Shutdown the leader and try to create a new tx.
1003 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
1005 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1007 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1009 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1010 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1012 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1014 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1017 followerTestKit.doCommit(rwTx.ready());
1018 fail("Exception expected");
1019 } catch (final ExecutionException e) {
1020 final String msg = "Expected instance of NoShardLeaderException, actual: \n"
1021 + Throwables.getStackTraceAsString(e.getCause());
1022 assertTrue(msg, Throwables.getRootCause(e) instanceof NoShardLeaderException);
1027 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1028 //TODO remove when test passes also for ClientBackedDataStore
1029 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
1030 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1031 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS);
1033 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1034 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
1035 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1036 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1038 try (final AbstractDataStore ds =
1039 follower2TestKit.setupAbstractDataStore(
1040 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false, CARS)) {
1042 followerTestKit.waitForMembersUp("member-1", "member-3");
1043 follower2TestKit.waitForMembersUp("member-1", "member-2");
1045 // Do an initial read to get the primary shard info cached.
1047 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1048 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1050 // Shutdown the leader and try to create a new tx.
1052 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
1054 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1056 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1057 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1059 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1061 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1063 followerTestKit.doCommit(rwTx.ready());
1068 public void testInstallSnapshot() throws Exception {
1069 final String testName = "testInstallSnapshot";
1070 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1071 final String followerCarShardName = "member-2-shard-cars-" + testName;
1073 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1074 // install a snapshot to sync the follower.
1076 TipProducingDataTree tree = InMemoryDataTreeFactory.getInstance().create(TreeType.CONFIGURATION);
1077 tree.setSchemaContext(SchemaContextHelper.full());
1079 final ContainerNode carsNode = CarsModel.newCarsNode(
1080 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", BigInteger.valueOf(20000))));
1081 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1083 final NormalizedNode<?, ?> snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.EMPTY);
1084 final Snapshot initialSnapshot = Snapshot.create(
1085 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1086 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1087 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1089 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1090 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1092 initDatastoresWithCars(testName);
1094 final Optional<NormalizedNode<?, ?>> readOptional = leaderDistributedDataStore.newReadOnlyTransaction().read(
1095 CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1096 assertEquals("isPresent", true, readOptional.isPresent());
1097 assertEquals("Node", carsNode, readOptional.get());
1099 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1100 initialSnapshot, snapshotRoot);
1102 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1103 initialSnapshot, snapshotRoot);
1106 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1107 final NormalizedNode<?, ?> expRoot) {
1108 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1109 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1110 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1111 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1112 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1113 MetadataShardDataTreeSnapshot shardSnapshot =
1114 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1115 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1118 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1119 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1120 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
1121 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1122 Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1123 Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
1124 dataStore.onDatastoreContextUpdated(mockContextFactory);