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.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.Before;
45 import org.junit.Test;
46 import org.mockito.Mockito;
47 import org.mockito.stubbing.Answer;
48 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
49 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
50 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
51 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
52 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
53 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
54 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
55 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
56 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
57 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
58 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
59 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
60 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
61 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
62 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
63 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
64 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
65 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
66 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
67 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
68 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
69 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
70 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
71 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
72 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
73 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
74 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
75 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
76 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
77 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
78 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
79 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
80 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
81 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
82 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
84 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
85 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
86 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
89 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
90 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
91 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
92 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
93 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
94 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
95 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
96 import scala.concurrent.Await;
97 import scala.concurrent.Future;
98 import scala.concurrent.duration.FiniteDuration;
101 * End-to-end distributed data store tests that exercise remote shards and transactions.
103 * @author Thomas Pantelis
105 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
107 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
108 private static final String[] CARS = {"cars"};
110 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
111 "akka://cluster-test@127.0.0.1:2558");
112 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
113 "akka://cluster-test@127.0.0.1:2559");
115 private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
116 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
117 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
119 private ActorSystem leaderSystem;
120 private ActorSystem followerSystem;
121 private ActorSystem follower2System;
123 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
124 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
126 private final DatastoreContext.Builder followerDatastoreContextBuilder =
127 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
128 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
129 private final TransactionIdentifier tx1 = nextTransactionId();
130 private final TransactionIdentifier tx2 = nextTransactionId();
132 private AbstractDataStore followerDistributedDataStore;
133 private AbstractDataStore leaderDistributedDataStore;
134 private IntegrationTestKit followerTestKit;
135 private IntegrationTestKit leaderTestKit;
138 public void setUp() {
139 InMemoryJournal.clear();
140 InMemorySnapshotStore.clear();
142 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
143 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
145 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
146 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
148 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
149 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
153 public void tearDown() {
154 if (followerDistributedDataStore != null) {
155 leaderDistributedDataStore.close();
157 if (leaderDistributedDataStore != null) {
158 leaderDistributedDataStore.close();
161 JavaTestKit.shutdownActorSystem(leaderSystem);
162 JavaTestKit.shutdownActorSystem(followerSystem);
163 JavaTestKit.shutdownActorSystem(follower2System);
165 InMemoryJournal.clear();
166 InMemorySnapshotStore.clear();
169 private void initDatastoresWithCars(final String type) {
170 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
173 private void initDatastoresWithCarsAndPeople(final String type) {
174 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
177 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards) {
178 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
180 leaderDistributedDataStore = leaderTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, shards);
182 followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder);
183 followerDistributedDataStore = followerTestKit.setupDistributedDataStore(type, moduleShardsConfig, false,
186 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), shards);
189 private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
191 Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
192 assertEquals("isPresent", true, optional.isPresent());
194 CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(CarsModel.CAR_QNAME);
195 for (NormalizedNode<?, ?> entry: entries) {
196 listBuilder.withChild((MapEntryNode) entry);
199 assertEquals("Car list node", listBuilder.build(), optional.get());
202 private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
203 final NormalizedNode<?, ?> expNode) throws Exception {
204 Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
205 assertEquals("isPresent", true, optional.isPresent());
206 assertEquals("Data node", expNode, optional.get());
209 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
211 Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
212 assertEquals("exists", true, exists);
216 public void testWriteTransactionWithSingleShard() throws Exception {
217 String testName = "testWriteTransactionWithSingleShard";
218 initDatastoresWithCars(testName);
220 String followerCarShardName = "member-2-shard-cars-" + testName;
221 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 2, ApplyJournalEntries.class );
223 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
224 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
226 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
227 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
229 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
230 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
231 writeTx.merge(car1Path, car1);
233 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
234 YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
235 writeTx.merge(car2Path, car2);
237 followerTestKit.doCommit(writeTx.ready());
239 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
241 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
245 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
247 writeTx.delete(car1Path);
249 followerTestKit.doCommit(writeTx.ready());
251 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
253 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
255 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
257 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
259 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
261 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
262 JavaTestKit.shutdownActorSystem(followerSystem, null, true);
264 ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load().getConfig("Member2"));
266 try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder)
267 .setupDistributedDataStore(testName, "module-shards-member2", true, CARS_AND_PEOPLE)) {
268 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
271 JavaTestKit.shutdownActorSystem(newSystem);
275 public void testReadWriteTransactionWithSingleShard() throws Exception {
276 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
278 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
279 assertNotNull("newReadWriteTransaction returned null", rwTx);
281 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
282 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
284 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
285 rwTx.merge(CarsModel.newCarPath("optima"), car1);
287 verifyCars(rwTx, car1);
289 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
290 YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
291 rwTx.merge(car2Path, car2);
293 verifyExists(rwTx, car2Path);
295 followerTestKit.doCommit(rwTx.ready());
297 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
301 public void testWriteTransactionWithMultipleShards() throws Exception {
302 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
304 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
305 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
307 YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
308 NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
309 writeTx.write(carsPath, carsNode);
311 YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
312 NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
313 writeTx.write(peoplePath, peopleNode);
315 followerTestKit.doCommit(writeTx.ready());
317 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
319 verifyNode(readTx, carsPath, carsNode);
320 verifyNode(readTx, peoplePath, peopleNode);
324 public void testReadWriteTransactionWithMultipleShards() throws Exception {
325 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
327 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
328 assertNotNull("newReadWriteTransaction returned null", rwTx);
330 YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
331 NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
332 rwTx.write(carsPath, carsNode);
334 YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
335 NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
336 rwTx.write(peoplePath, peopleNode);
338 followerTestKit.doCommit(rwTx.ready());
340 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
342 verifyNode(readTx, carsPath, carsNode);
343 verifyNode(readTx, peoplePath, peopleNode);
347 public void testTransactionChainWithSingleShard() throws Exception {
348 initDatastoresWithCars("testTransactionChainWithSingleShard");
350 DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
352 // Add the top-level cars container with write-only.
354 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
355 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
357 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
361 // Verify the top-level cars container with read-only.
363 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
365 // Perform car operations with read-write.
367 DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
369 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
371 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
373 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
374 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
375 rwTx.write(car1Path, car1);
377 verifyExists(rwTx, car1Path);
379 verifyCars(rwTx, car1);
381 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
382 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
384 rwTx.delete(car1Path);
386 followerTestKit.doCommit(rwTx.ready());
390 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
394 public void testTransactionChainWithMultipleShards() throws Exception {
395 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
397 DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
399 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
400 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
402 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
403 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
405 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
406 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
408 followerTestKit.doCommit(writeTx.ready());
410 DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
412 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
413 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
414 readWriteTx.write(carPath, car);
416 MapEntryNode person = PeopleModel.newPersonEntry("jack");
417 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
418 readWriteTx.merge(personPath, person);
420 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
421 assertEquals("isPresent", true, optional.isPresent());
422 assertEquals("Data node", car, optional.get());
424 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
425 assertEquals("isPresent", true, optional.isPresent());
426 assertEquals("Data node", person, optional.get());
428 DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
430 writeTx = txChain.newWriteOnlyTransaction();
432 writeTx.delete(personPath);
434 DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
436 followerTestKit.doCommit(cohort2);
437 followerTestKit.doCommit(cohort3);
441 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
442 verifyCars(readTx, car);
444 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
445 assertEquals("isPresent", false, optional.isPresent());
449 public void testChainedTransactionFailureWithSingleShard() throws Exception {
450 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
452 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
453 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
454 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
455 MoreExecutors.directExecutor());
457 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
458 DOMTransactionChain txChain = broker.createTransactionChain(listener);
460 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
462 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
463 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
464 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
466 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
469 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
470 fail("Expected TransactionCommitFailedException");
471 } catch (TransactionCommitFailedException e) {
475 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
482 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
483 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
485 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
486 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
487 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
488 MoreExecutors.directExecutor());
490 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
491 DOMTransactionChain txChain = broker.createTransactionChain(listener);
493 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
495 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
497 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
498 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
499 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
501 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
502 // done for put for performance reasons.
503 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
506 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
507 fail("Expected TransactionCommitFailedException");
508 } catch (TransactionCommitFailedException e) {
512 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
519 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
520 String testName = "testSingleShardTransactionsWithLeaderChanges";
521 initDatastoresWithCars(testName);
523 String followerCarShardName = "member-2-shard-cars-" + testName;
524 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class );
526 // Write top-level car container from the follower so it uses a remote Tx.
528 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
530 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
531 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
533 followerTestKit.doCommit(writeTx.ready());
535 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
537 // Switch the leader to the follower
539 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
540 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
542 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
543 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
545 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorContext(), CARS);
547 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
548 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
550 DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
551 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
552 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder);
554 try (AbstractDataStore ds =
555 newMember1TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
557 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), CARS);
559 // Write a car entry to the new leader - should switch to local Tx
561 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
563 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
564 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
565 writeTx.merge(car1Path, car1);
567 followerTestKit.doCommit(writeTx.ready());
569 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
573 @SuppressWarnings("unchecked")
575 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
576 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
577 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
579 Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
580 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
582 TipProducingDataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
583 dataTree.setSchemaContext(SchemaContextHelper.full());
585 // Send a tx with immediate commit.
587 DataTreeModification modification = dataTree.takeSnapshot().newModification();
588 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
589 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
591 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
592 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
593 modification.ready();
595 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true);
597 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
598 Object resp = followerTestKit.expectMsgClass(Object.class);
599 if (resp instanceof akka.actor.Status.Failure) {
600 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
603 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
605 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
607 // Send another tx without immediate commit.
609 modification = dataTree.takeSnapshot().newModification();
610 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
611 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
612 modification.ready();
614 readyLocal = new ReadyLocalTransaction(tx2 , modification, false);
616 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
617 resp = followerTestKit.expectMsgClass(Object.class);
618 if (resp instanceof akka.actor.Status.Failure) {
619 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
622 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
624 ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
625 ((ReadyTransactionReply)resp).getCohortPath());
627 Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
628 Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
629 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
630 leaderDistributedDataStore.getActorContext(), Arrays.asList(
631 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), tx2);
632 cohort.canCommit().get(5, TimeUnit.SECONDS);
633 cohort.preCommit().get(5, TimeUnit.SECONDS);
634 cohort.commit().get(5, TimeUnit.SECONDS);
636 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
639 @SuppressWarnings("unchecked")
641 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
642 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
643 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
645 Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
646 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
648 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
649 DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
651 // Send a tx with immediate commit.
653 DataTreeModification modification = dataTree.takeSnapshot().newModification();
654 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
655 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
657 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
658 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
660 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1,
661 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
662 Mockito.mock(ShardDataTreeTransactionParent.class), tx1, modification), true);
664 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
665 Object resp = followerTestKit.expectMsgClass(Object.class);
666 if (resp instanceof akka.actor.Status.Failure) {
667 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
670 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
672 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
674 // Send another tx without immediate commit.
676 modification = dataTree.takeSnapshot().newModification();
677 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
678 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
680 forwardedReady = new ForwardedReadyTransaction(tx2,
681 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
682 Mockito.mock(ShardDataTreeTransactionParent.class), tx2, modification), false);
684 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
685 resp = followerTestKit.expectMsgClass(Object.class);
686 if (resp instanceof akka.actor.Status.Failure) {
687 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
690 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
692 ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
693 ((ReadyTransactionReply)resp).getCohortPath());
695 Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
696 Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
697 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
698 leaderDistributedDataStore.getActorContext(), Arrays.asList(
699 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), tx2);
700 cohort.canCommit().get(5, TimeUnit.SECONDS);
701 cohort.preCommit().get(5, TimeUnit.SECONDS);
702 cohort.commit().get(5, TimeUnit.SECONDS);
704 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
708 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
709 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
710 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
711 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
713 // Do an initial write to get the primary shard info cached.
715 DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
716 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
717 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
718 followerTestKit.doCommit(initialWriteTx.ready());
720 // Wait for the commit to be replicated to the follower.
722 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
723 raftState -> assertEquals("getLastApplied", 0, raftState.getLastApplied()));
725 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
726 raftState -> assertEquals("getLastApplied", 0, raftState.getLastApplied()));
728 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
731 DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
732 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
733 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
734 DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
735 ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
736 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
738 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
739 // in the leader shard.
741 DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
742 LinkedList<MapEntryNode> cars = new LinkedList<>();
744 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
745 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
747 NormalizedNode<?, ?> people = PeopleModel.newPersonMapNode();
748 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
749 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
751 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
752 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
753 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
756 DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
757 for (int i = 1; i <= 5; i++, carIndex++) {
758 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
759 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
762 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
765 DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
766 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
767 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
770 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
771 // leader shard on ready.
773 DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
774 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
775 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
777 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
778 stats -> assertEquals("getReadWriteTransactionCount", 1, stats.getReadWriteTransactionCount()));
780 // Disable elections on the leader so it switches to follower.
782 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
783 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
784 .shardElectionTimeoutFactor(10));
786 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
787 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorContext(), "cars");
789 // Submit all tx's - the messages should get queued for retry.
791 ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
792 final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
793 final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
794 final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
796 // Enable elections on the other follower so it becomes the leader, at which point the
797 // tx's should get forwarded from the previous leader to the new leader to complete the commits.
799 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
800 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
802 followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
803 followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
804 followerTestKit.doCommit(writeTx3Cohort);
805 followerTestKit.doCommit(writeTx4Cohort);
806 followerTestKit.doCommit(rwTxCohort);
808 DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
809 verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
810 verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
814 public void testLeadershipTransferOnShutdown() throws Exception {
815 leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
816 followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
817 String testName = "testLeadershipTransferOnShutdown";
818 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
820 IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
821 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(100));
822 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupDistributedDataStore(testName,
823 MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
825 // Create and submit a couple tx's so they're pending.
827 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
828 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
829 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
830 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
831 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
833 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
834 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
836 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
837 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
838 writeTx.write(CarsModel.newCarPath("optima"), car);
839 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
841 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
842 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
844 // Gracefully stop the leader via a Shutdown message.
846 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
847 .shardElectionTimeoutFactor(100));
849 FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
850 Future<ActorRef> future = leaderDistributedDataStore.getActorContext().findLocalShardAsync("cars");
851 ActorRef leaderActor = Await.result(future, duration);
853 Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
855 // Commit the 2 transactions. They should finish and succeed.
857 followerTestKit.doCommit(cohort1);
858 followerTestKit.doCommit(cohort2);
860 // Wait for the leader actor stopped.
862 Boolean stopped = Await.result(stopFuture, duration);
863 assertEquals("Stopped", Boolean.TRUE, stopped);
865 // Verify leadership was transferred by reading the committed data from the other nodes.
867 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
868 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
873 public void testTransactionWithIsolatedLeader() throws Exception {
874 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
875 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
876 String testName = "testTransactionWithIsolatedLeader";
877 initDatastoresWithCars(testName);
879 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
880 DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
881 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
883 // Tx that is submitted after the leader transitions to IsolatedLeader.
884 DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
885 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
887 // Tx that is submitted after the follower is reinstated.
888 DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
889 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
892 followerTestKit.watch(followerDistributedDataStore.getActorContext().getShardManager());
893 followerDistributedDataStore.close();
894 followerTestKit.expectTerminated(followerDistributedDataStore.getActorContext().getShardManager());
896 // Submit the preIsolatedLeaderWriteTx so it's pending
897 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
899 // Change the isolated leader check interval low so it changes to IsolatedLeader.
900 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
901 .shardIsolatedLeaderCheckIntervalInMillis(200));
903 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
904 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
907 leaderTestKit.doCommit(noShardLeaderWriteTx.ready());
908 fail("Expected NoShardLeaderException");
909 } catch (ExecutionException e) {
910 assertEquals("getCause", NoShardLeaderException.class, e.getCause().getClass());
913 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
914 .shardElectionTimeoutFactor(100));
916 DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
918 followerDistributedDataStore = followerTestKit.setupDistributedDataStore(testName,
919 MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
921 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
922 leaderTestKit.doCommit(successTxCohort);
925 @Test(expected = AskTimeoutException.class)
926 public void testTransactionWithShardLeaderNotResponding() throws Exception {
927 followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
928 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
930 // Do an initial read to get the primary shard info cached.
932 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
933 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
935 // Shutdown the leader and try to create a new tx.
937 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
939 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
940 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
942 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
944 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
947 followerTestKit.doCommit(rwTx.ready());
948 } catch (ExecutionException e) {
949 assertTrue("Expected ShardLeaderNotRespondingException cause. Actual: " + e.getCause(),
950 e.getCause() instanceof ShardLeaderNotRespondingException);
951 assertNotNull("Expected a nested cause", e.getCause().getCause());
952 Throwables.propagateIfInstanceOf(e.getCause().getCause(), Exception.class);
953 Throwables.propagate(e.getCause().getCause());
957 @Test(expected = NoShardLeaderException.class)
958 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
959 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
961 // Do an initial read to get the primary shard info cached.
963 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
964 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
966 // Shutdown the leader and try to create a new tx.
968 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
970 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
972 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
974 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
975 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
977 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
979 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
982 followerTestKit.doCommit(rwTx.ready());
983 } catch (ExecutionException e) {
984 Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
985 Throwables.propagate(e.getCause());
990 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
991 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
992 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS);
994 DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
995 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
996 IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System, follower2DatastoreContextBuilder);
998 try (AbstractDataStore ds =
999 follower2TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false, CARS)) {
1001 followerTestKit.waitForMembersUp("member-1", "member-3");
1002 follower2TestKit.waitForMembersUp("member-1", "member-2");
1004 // Do an initial read to get the primary shard info cached.
1006 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1007 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1009 // Shutdown the leader and try to create a new tx.
1011 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
1013 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1015 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1016 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1018 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1020 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1022 followerTestKit.doCommit(rwTx.ready());
1027 public void testInstallSnapshot() throws Exception {
1028 final String testName = "testInstallSnapshot";
1029 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1030 final String followerCarShardName = "member-2-shard-cars-" + testName;
1032 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1033 // install a snapshot to sync the follower.
1035 TipProducingDataTree tree = InMemoryDataTreeFactory.getInstance().create(TreeType.CONFIGURATION);
1036 tree.setSchemaContext(SchemaContextHelper.full());
1038 ContainerNode carsNode = CarsModel.newCarsNode(
1039 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", BigInteger.valueOf(20000))));
1040 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1042 NormalizedNode<?, ?> snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.EMPTY);
1043 Snapshot initialSnapshot = Snapshot.create(
1044 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1045 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1046 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1048 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1049 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1051 initDatastoresWithCars(testName);
1053 Optional<NormalizedNode<?, ?>> readOptional = leaderDistributedDataStore.newReadOnlyTransaction().read(
1054 CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
1055 assertEquals("isPresent", true, readOptional.isPresent());
1056 assertEquals("Node", carsNode, readOptional.get());
1058 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1059 initialSnapshot, snapshotRoot);
1061 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1062 initialSnapshot, snapshotRoot);
1065 private static void verifySnapshot(Snapshot actual, Snapshot expected, NormalizedNode<?, ?> expRoot) {
1066 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1067 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1068 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1069 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1070 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1071 MetadataShardDataTreeSnapshot shardSnapshot =
1072 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1073 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1076 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1077 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1078 DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
1079 Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1080 Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1081 Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
1082 dataStore.onDatastoreContextUpdated(mockContextFactory);