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.AskTimeoutException;
27 import akka.pattern.Patterns;
28 import akka.testkit.JavaTestKit;
29 import com.google.common.base.Optional;
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.concurrent.ExecutionException;
43 import java.util.concurrent.TimeUnit;
44 import org.junit.After;
45 import org.junit.Assume;
46 import org.junit.Before;
47 import org.junit.Test;
48 import org.junit.runner.RunWith;
49 import org.junit.runners.Parameterized;
50 import org.junit.runners.Parameterized.Parameter;
51 import org.junit.runners.Parameterized.Parameters;
52 import org.mockito.Mockito;
53 import org.mockito.stubbing.Answer;
54 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
55 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
56 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
57 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
58 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
59 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
60 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
61 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
62 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
63 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
65 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
66 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
67 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
68 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
69 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
70 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
71 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
72 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
73 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
74 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
75 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
76 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
77 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
78 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
79 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
80 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
81 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
82 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
83 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
84 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
85 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
86 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
87 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
88 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
89 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
90 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
91 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
93 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
95 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
96 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
97 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
98 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
99 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
100 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
101 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
102 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
103 import scala.concurrent.Await;
104 import scala.concurrent.Future;
105 import scala.concurrent.duration.FiniteDuration;
108 * End-to-end distributed data store tests that exercise remote shards and transactions.
110 * @author Thomas Pantelis
112 @RunWith(Parameterized.class)
113 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
115 @Parameters(name = "{0}")
116 public static Collection<Object[]> data() {
117 return Arrays.asList(new Object[][] {
118 { DistributedDataStore.class }, { ClientBackedDataStore.class }
123 public Class<? extends AbstractDataStore> testParameter;
125 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
126 private static final String[] CARS = {"cars"};
128 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
129 "akka://cluster-test@127.0.0.1:2558");
130 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
131 "akka://cluster-test@127.0.0.1:2559");
133 private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
134 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
135 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
137 private ActorSystem leaderSystem;
138 private ActorSystem followerSystem;
139 private ActorSystem follower2System;
141 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
142 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
144 private final DatastoreContext.Builder followerDatastoreContextBuilder =
145 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
146 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
147 private final TransactionIdentifier tx1 = nextTransactionId();
148 private final TransactionIdentifier tx2 = nextTransactionId();
150 private AbstractDataStore followerDistributedDataStore;
151 private AbstractDataStore leaderDistributedDataStore;
152 private IntegrationTestKit followerTestKit;
153 private IntegrationTestKit leaderTestKit;
156 public void setUp() {
157 InMemoryJournal.clear();
158 InMemorySnapshotStore.clear();
160 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
161 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
163 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
164 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
166 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
167 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
171 public void tearDown() {
172 if (followerDistributedDataStore != null) {
173 leaderDistributedDataStore.close();
175 if (leaderDistributedDataStore != null) {
176 leaderDistributedDataStore.close();
179 JavaTestKit.shutdownActorSystem(leaderSystem);
180 JavaTestKit.shutdownActorSystem(followerSystem);
181 JavaTestKit.shutdownActorSystem(follower2System);
183 InMemoryJournal.clear();
184 InMemorySnapshotStore.clear();
187 private void initDatastoresWithCars(final String type) throws Exception {
188 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
191 private void initDatastoresWithCarsAndPeople(final String type) throws Exception {
192 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
195 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards)
197 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
199 leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
200 testParameter, type, moduleShardsConfig, false, shards);
202 followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder);
203 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
204 testParameter, type, moduleShardsConfig, false, shards);
206 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), shards);
209 private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
211 final Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
212 assertEquals("isPresent", true, optional.isPresent());
214 final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
215 CarsModel.CAR_QNAME);
216 for (final NormalizedNode<?, ?> entry: entries) {
217 listBuilder.withChild((MapEntryNode) entry);
220 assertEquals("Car list node", listBuilder.build(), optional.get());
223 private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
224 final NormalizedNode<?, ?> expNode) throws Exception {
225 final Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
226 assertEquals("isPresent", true, optional.isPresent());
227 assertEquals("Data node", expNode, optional.get());
230 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
232 final Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
233 assertEquals("exists", true, exists);
237 public void testWriteTransactionWithSingleShard() throws Exception {
238 final String testName = "testWriteTransactionWithSingleShard";
239 initDatastoresWithCars(testName);
241 final String followerCarShardName = "member-2-shard-cars-" + testName;
242 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 2, ApplyJournalEntries.class);
244 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
245 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
247 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
248 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
250 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
251 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
252 writeTx.merge(car1Path, car1);
254 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
255 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
256 writeTx.merge(car2Path, car2);
258 followerTestKit.doCommit(writeTx.ready());
260 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
262 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
266 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
268 writeTx.delete(car1Path);
270 followerTestKit.doCommit(writeTx.ready());
272 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
274 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
276 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
278 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
280 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
282 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
283 JavaTestKit.shutdownActorSystem(followerSystem, null, true);
285 final ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load()
286 .getConfig("Member2"));
288 try (final AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder)
289 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS_AND_PEOPLE)) {
290 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
293 JavaTestKit.shutdownActorSystem(newSystem);
297 public void testReadWriteTransactionWithSingleShard() throws Exception {
298 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
300 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
301 assertNotNull("newReadWriteTransaction returned null", rwTx);
303 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
304 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
306 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
307 rwTx.merge(CarsModel.newCarPath("optima"), car1);
309 verifyCars(rwTx, car1);
311 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
312 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
313 rwTx.merge(car2Path, car2);
315 verifyExists(rwTx, car2Path);
317 followerTestKit.doCommit(rwTx.ready());
319 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
323 public void testWriteTransactionWithMultipleShards() throws Exception {
324 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
326 final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
327 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
329 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
330 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
331 writeTx.write(carsPath, carsNode);
333 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
334 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
335 writeTx.write(peoplePath, peopleNode);
337 followerTestKit.doCommit(writeTx.ready());
339 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
341 verifyNode(readTx, carsPath, carsNode);
342 verifyNode(readTx, peoplePath, peopleNode);
346 public void testReadWriteTransactionWithMultipleShards() throws Exception {
347 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
349 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
350 assertNotNull("newReadWriteTransaction returned null", rwTx);
352 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
353 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
354 rwTx.write(carsPath, carsNode);
356 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
357 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
358 rwTx.write(peoplePath, peopleNode);
360 followerTestKit.doCommit(rwTx.ready());
362 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
364 verifyNode(readTx, carsPath, carsNode);
365 verifyNode(readTx, peoplePath, peopleNode);
369 public void testTransactionChainWithSingleShard() throws Exception {
370 initDatastoresWithCars("testTransactionChainWithSingleShard");
372 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
374 // Add the top-level cars container with write-only.
376 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
377 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
379 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
381 final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
383 // Verify the top-level cars container with read-only.
385 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
387 // Perform car operations with read-write.
389 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
391 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
393 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
395 final MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
396 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
397 rwTx.write(car1Path, car1);
399 verifyExists(rwTx, car1Path);
401 verifyCars(rwTx, car1);
403 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
404 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
406 rwTx.delete(car1Path);
408 followerTestKit.doCommit(writeTxReady);
410 followerTestKit.doCommit(rwTx.ready());
414 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
418 public void testTransactionChainWithMultipleShards() throws Exception {
419 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
421 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
423 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
424 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
426 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
427 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
429 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
430 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
432 followerTestKit.doCommit(writeTx.ready());
434 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
436 final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
437 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
438 readWriteTx.write(carPath, car);
440 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
441 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
442 readWriteTx.merge(personPath, person);
444 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
445 assertEquals("isPresent", true, optional.isPresent());
446 assertEquals("Data node", car, optional.get());
448 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
449 assertEquals("isPresent", true, optional.isPresent());
450 assertEquals("Data node", person, optional.get());
452 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
454 writeTx = txChain.newWriteOnlyTransaction();
456 writeTx.delete(personPath);
458 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
460 followerTestKit.doCommit(cohort2);
461 followerTestKit.doCommit(cohort3);
465 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
466 verifyCars(readTx, car);
468 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
469 assertEquals("isPresent", false, optional.isPresent());
473 public void testChainedTransactionFailureWithSingleShard() throws Exception {
474 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
476 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
477 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
478 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
479 MoreExecutors.directExecutor());
481 final TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
482 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
484 final DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
486 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
487 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
488 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
490 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
493 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
494 fail("Expected TransactionCommitFailedException");
495 } catch (final TransactionCommitFailedException e) {
499 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
506 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
507 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
509 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
510 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
511 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
512 MoreExecutors.directExecutor());
514 final TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
515 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
517 final DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
519 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
521 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
522 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
523 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
525 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
526 // done for put for performance reasons.
527 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
530 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
531 fail("Expected TransactionCommitFailedException");
532 } catch (final TransactionCommitFailedException e) {
536 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
543 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
544 //TODO remove when test passes also for ClientBackedDataStore
545 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
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);
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));
855 try (final AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
856 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
858 // Create and submit a couple tx's so they're pending.
860 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
861 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
862 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
863 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
864 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
866 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
867 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
869 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
870 final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
871 writeTx.write(CarsModel.newCarPath("optima"), car);
872 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
874 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
875 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
877 // Gracefully stop the leader via a Shutdown message.
879 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
880 .shardElectionTimeoutFactor(100));
882 final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
883 final Future<ActorRef> future = leaderDistributedDataStore.getActorContext().findLocalShardAsync("cars");
884 final ActorRef leaderActor = Await.result(future, duration);
886 final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
888 // Commit the 2 transactions. They should finish and succeed.
890 followerTestKit.doCommit(cohort1);
891 followerTestKit.doCommit(cohort2);
893 // Wait for the leader actor stopped.
895 final Boolean stopped = Await.result(stopFuture, duration);
896 assertEquals("Stopped", Boolean.TRUE, stopped);
898 // Verify leadership was transferred by reading the committed data from the other nodes.
900 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
901 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
906 public void testTransactionWithIsolatedLeader() throws Exception {
907 //TODO remove when test passes also for ClientBackedDataStore
908 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
909 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
910 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
911 final String testName = "testTransactionWithIsolatedLeader";
912 initDatastoresWithCars(testName);
914 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
915 final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
916 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
918 // Tx that is submitted after the leader transitions to IsolatedLeader.
919 final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
920 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
922 // Tx that is submitted after the follower is reinstated.
923 final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
924 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
927 followerTestKit.watch(followerDistributedDataStore.getActorContext().getShardManager());
928 followerDistributedDataStore.close();
929 followerTestKit.expectTerminated(followerDistributedDataStore.getActorContext().getShardManager());
931 // Submit the preIsolatedLeaderWriteTx so it's pending
932 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
934 // Change the isolated leader check interval low so it changes to IsolatedLeader.
935 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
936 .shardIsolatedLeaderCheckIntervalInMillis(200));
938 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
939 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
942 leaderTestKit.doCommit(noShardLeaderWriteTx.ready());
943 fail("Expected NoShardLeaderException");
944 } catch (final ExecutionException e) {
945 assertEquals("getCause", NoShardLeaderException.class, Throwables.getRootCause(e).getClass());
948 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
949 .shardElectionTimeoutFactor(100));
951 final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
953 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
954 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
956 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
957 leaderTestKit.doCommit(successTxCohort);
960 @Test(expected = AskTimeoutException.class)
961 public void testTransactionWithShardLeaderNotResponding() throws Exception {
962 //TODO remove when test passes also for ClientBackedDataStore
963 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
964 followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
965 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
967 // Do an initial read to get the primary shard info cached.
969 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
970 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
972 // Shutdown the leader and try to create a new tx.
974 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
976 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
977 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
979 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
981 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
984 followerTestKit.doCommit(rwTx.ready());
985 } catch (final ExecutionException e) {
986 assertTrue("Expected ShardLeaderNotRespondingException cause. Actual: " + e.getCause(),
987 e.getCause() instanceof ShardLeaderNotRespondingException);
988 assertNotNull("Expected a nested cause", e.getCause().getCause());
989 Throwables.propagateIfInstanceOf(e.getCause().getCause(), Exception.class);
990 Throwables.propagate(e.getCause().getCause());
994 @Test(expected = NoShardLeaderException.class)
995 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
996 //TODO remove when test passes also for ClientBackedDataStore
997 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
998 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
1000 // Do an initial read to get the primary shard info cached.
1002 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1003 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1005 // Shutdown the leader and try to create a new tx.
1007 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
1009 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1011 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1013 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1014 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1016 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1018 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1021 followerTestKit.doCommit(rwTx.ready());
1022 } catch (final ExecutionException e) {
1023 Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
1024 Throwables.propagate(e.getCause());
1029 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1030 //TODO remove when test passes also for ClientBackedDataStore
1031 Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
1032 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1033 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS);
1035 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1036 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
1037 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1038 follower2System, follower2DatastoreContextBuilder);
1040 try (final AbstractDataStore ds =
1041 follower2TestKit.setupAbstractDataStore(
1042 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false, CARS)) {
1044 followerTestKit.waitForMembersUp("member-1", "member-3");
1045 follower2TestKit.waitForMembersUp("member-1", "member-2");
1047 // Do an initial read to get the primary shard info cached.
1049 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1050 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1052 // Shutdown the leader and try to create a new tx.
1054 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
1056 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1058 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1059 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1061 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1063 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1065 followerTestKit.doCommit(rwTx.ready());
1070 public void testInstallSnapshot() throws Exception {
1071 final String testName = "testInstallSnapshot";
1072 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1073 final String followerCarShardName = "member-2-shard-cars-" + testName;
1075 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1076 // install a snapshot to sync the follower.
1078 TipProducingDataTree tree = InMemoryDataTreeFactory.getInstance().create(TreeType.CONFIGURATION);
1079 tree.setSchemaContext(SchemaContextHelper.full());
1081 final ContainerNode carsNode = CarsModel.newCarsNode(
1082 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", BigInteger.valueOf(20000))));
1083 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1085 final NormalizedNode<?, ?> snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.EMPTY);
1086 final Snapshot initialSnapshot = Snapshot.create(
1087 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1088 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1089 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1091 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1092 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1094 initDatastoresWithCars(testName);
1096 final Optional<NormalizedNode<?, ?>> readOptional = leaderDistributedDataStore.newReadOnlyTransaction().read(
1097 CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1098 assertEquals("isPresent", true, readOptional.isPresent());
1099 assertEquals("Node", carsNode, readOptional.get());
1101 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1102 initialSnapshot, snapshotRoot);
1104 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1105 initialSnapshot, snapshotRoot);
1108 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1109 final NormalizedNode<?, ?> expRoot) {
1110 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1111 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1112 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1113 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1114 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1115 MetadataShardDataTreeSnapshot shardSnapshot =
1116 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1117 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1120 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1121 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1122 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
1123 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1124 Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1125 Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
1126 dataStore.onDatastoreContextUpdated(mockContextFactory);