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.LinkedList;
40 import java.util.concurrent.ExecutionException;
41 import java.util.concurrent.TimeUnit;
42 import org.junit.After;
43 import org.junit.Before;
44 import org.junit.Test;
45 import org.mockito.Mockito;
46 import org.mockito.stubbing.Answer;
47 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
48 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
49 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
50 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
51 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
52 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
53 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
54 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
55 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
56 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
57 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
58 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
59 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
60 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
61 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
62 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
63 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
64 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
65 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
66 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
67 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
68 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
69 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
70 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
71 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
72 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
73 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
74 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
75 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
76 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
77 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
78 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
79 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
81 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
83 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
84 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
85 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
86 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
87 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
88 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
89 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
90 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
91 import scala.concurrent.Await;
92 import scala.concurrent.Future;
93 import scala.concurrent.duration.FiniteDuration;
96 * End-to-end distributed data store tests that exercise remote shards and transactions.
98 * @author Thomas Pantelis
100 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
102 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
103 private static final String[] CARS = {"cars"};
105 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
106 "akka.tcp://cluster-test@127.0.0.1:2558");
107 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
108 "akka.tcp://cluster-test@127.0.0.1:2559");
110 private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
111 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
112 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
114 private ActorSystem leaderSystem;
115 private ActorSystem followerSystem;
116 private ActorSystem follower2System;
118 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
119 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
121 private final DatastoreContext.Builder followerDatastoreContextBuilder =
122 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
123 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
124 private final TransactionIdentifier tx1 = nextTransactionId();
125 private final TransactionIdentifier tx2 = nextTransactionId();
127 private AbstractDataStore followerDistributedDataStore;
128 private AbstractDataStore leaderDistributedDataStore;
129 private IntegrationTestKit followerTestKit;
130 private IntegrationTestKit leaderTestKit;
133 public void setUp() {
134 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
135 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
137 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
138 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
140 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
141 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
145 public void tearDown() {
146 if (followerDistributedDataStore != null) {
147 leaderDistributedDataStore.close();
149 if (leaderDistributedDataStore != null) {
150 leaderDistributedDataStore.close();
153 JavaTestKit.shutdownActorSystem(leaderSystem);
154 JavaTestKit.shutdownActorSystem(followerSystem);
155 JavaTestKit.shutdownActorSystem(follower2System);
158 private void initDatastoresWithCars(final String type) {
159 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
162 private void initDatastoresWithCarsAndPeople(final String type) {
163 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
166 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards) {
167 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
169 leaderDistributedDataStore = leaderTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, shards);
171 followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder);
172 followerDistributedDataStore = followerTestKit.setupDistributedDataStore(type, moduleShardsConfig, false,
175 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), shards);
178 private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
180 Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
181 assertEquals("isPresent", true, optional.isPresent());
183 CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(CarsModel.CAR_QNAME);
184 for (NormalizedNode<?, ?> entry: entries) {
185 listBuilder.withChild((MapEntryNode) entry);
188 assertEquals("Car list node", listBuilder.build(), optional.get());
191 private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
192 final NormalizedNode<?, ?> expNode) throws Exception {
193 Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
194 assertEquals("isPresent", true, optional.isPresent());
195 assertEquals("Data node", expNode, optional.get());
198 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
200 Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
201 assertEquals("exists", true, exists);
205 public void testWriteTransactionWithSingleShard() throws Exception {
206 String testName = "testWriteTransactionWithSingleShard";
207 initDatastoresWithCars(testName);
209 String followerCarShardName = "member-2-shard-cars-" + testName;
210 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 2, ApplyJournalEntries.class );
212 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
213 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
215 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
216 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
218 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
219 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
220 writeTx.merge(car1Path, car1);
222 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
223 YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
224 writeTx.merge(car2Path, car2);
226 followerTestKit.doCommit(writeTx.ready());
228 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
230 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
234 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
236 writeTx.delete(car1Path);
238 followerTestKit.doCommit(writeTx.ready());
240 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
242 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
244 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
246 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
248 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
250 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
251 JavaTestKit.shutdownActorSystem(followerSystem, null, true);
253 ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load().getConfig("Member2"));
255 try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder)
256 .setupDistributedDataStore(testName, "module-shards-member2", true, CARS_AND_PEOPLE)) {
257 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
260 JavaTestKit.shutdownActorSystem(newSystem);
264 public void testReadWriteTransactionWithSingleShard() throws Exception {
265 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
267 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
268 assertNotNull("newReadWriteTransaction returned null", rwTx);
270 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
271 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
273 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
274 rwTx.merge(CarsModel.newCarPath("optima"), car1);
276 verifyCars(rwTx, car1);
278 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
279 YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
280 rwTx.merge(car2Path, car2);
282 verifyExists(rwTx, car2Path);
284 followerTestKit.doCommit(rwTx.ready());
286 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
290 public void testWriteTransactionWithMultipleShards() throws Exception {
291 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
293 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
294 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
296 YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
297 NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
298 writeTx.write(carsPath, carsNode);
300 YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
301 NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
302 writeTx.write(peoplePath, peopleNode);
304 followerTestKit.doCommit(writeTx.ready());
306 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
308 verifyNode(readTx, carsPath, carsNode);
309 verifyNode(readTx, peoplePath, peopleNode);
313 public void testReadWriteTransactionWithMultipleShards() throws Exception {
314 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
316 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
317 assertNotNull("newReadWriteTransaction returned null", rwTx);
319 YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
320 NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
321 rwTx.write(carsPath, carsNode);
323 YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
324 NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
325 rwTx.write(peoplePath, peopleNode);
327 followerTestKit.doCommit(rwTx.ready());
329 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
331 verifyNode(readTx, carsPath, carsNode);
332 verifyNode(readTx, peoplePath, peopleNode);
336 public void testTransactionChainWithSingleShard() throws Exception {
337 initDatastoresWithCars("testTransactionChainWithSingleShard");
339 DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
341 // Add the top-level cars container with write-only.
343 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
344 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
346 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
350 // Verify the top-level cars container with read-only.
352 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
354 // Perform car operations with read-write.
356 DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
358 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
360 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
362 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
363 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
364 rwTx.write(car1Path, car1);
366 verifyExists(rwTx, car1Path);
368 verifyCars(rwTx, car1);
370 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
371 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
373 rwTx.delete(car1Path);
375 followerTestKit.doCommit(rwTx.ready());
379 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
383 public void testTransactionChainWithMultipleShards() throws Exception {
384 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
386 DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
388 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
389 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
391 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
392 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
394 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
395 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
397 followerTestKit.doCommit(writeTx.ready());
399 DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
401 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
402 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
403 readWriteTx.write(carPath, car);
405 MapEntryNode person = PeopleModel.newPersonEntry("jack");
406 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
407 readWriteTx.merge(personPath, person);
409 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
410 assertEquals("isPresent", true, optional.isPresent());
411 assertEquals("Data node", car, optional.get());
413 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
414 assertEquals("isPresent", true, optional.isPresent());
415 assertEquals("Data node", person, optional.get());
417 DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
419 writeTx = txChain.newWriteOnlyTransaction();
421 writeTx.delete(personPath);
423 DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
425 followerTestKit.doCommit(cohort2);
426 followerTestKit.doCommit(cohort3);
430 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
431 verifyCars(readTx, car);
433 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
434 assertEquals("isPresent", false, optional.isPresent());
438 public void testChainedTransactionFailureWithSingleShard() throws Exception {
439 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
441 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
442 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
443 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
444 MoreExecutors.directExecutor());
446 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
447 DOMTransactionChain txChain = broker.createTransactionChain(listener);
449 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
451 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
452 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
453 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
455 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
458 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
459 fail("Expected TransactionCommitFailedException");
460 } catch (TransactionCommitFailedException e) {
464 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
471 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
472 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
474 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
475 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
476 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
477 MoreExecutors.directExecutor());
479 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
480 DOMTransactionChain txChain = broker.createTransactionChain(listener);
482 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
484 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
486 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
487 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
488 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
490 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
491 // done for put for performance reasons.
492 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
495 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
496 fail("Expected TransactionCommitFailedException");
497 } catch (TransactionCommitFailedException e) {
501 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
508 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
509 String testName = "testSingleShardTransactionsWithLeaderChanges";
510 initDatastoresWithCars(testName);
512 String followerCarShardName = "member-2-shard-cars-" + testName;
513 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class );
515 // Write top-level car container from the follower so it uses a remote Tx.
517 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
519 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
520 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
522 followerTestKit.doCommit(writeTx.ready());
524 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
526 // Switch the leader to the follower
528 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
529 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
531 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
532 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
534 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorContext(), CARS);
536 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
537 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
539 DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
540 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
541 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder);
543 try (AbstractDataStore ds =
544 newMember1TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
546 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), CARS);
548 // Write a car entry to the new leader - should switch to local Tx
550 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
552 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
553 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
554 writeTx.merge(car1Path, car1);
556 followerTestKit.doCommit(writeTx.ready());
558 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
562 @SuppressWarnings("unchecked")
564 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
565 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
566 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
568 Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
569 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
571 TipProducingDataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
572 dataTree.setSchemaContext(SchemaContextHelper.full());
574 // Send a tx with immediate commit.
576 DataTreeModification modification = dataTree.takeSnapshot().newModification();
577 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
578 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
580 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
581 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
582 modification.ready();
584 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true);
586 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
587 Object resp = followerTestKit.expectMsgClass(Object.class);
588 if (resp instanceof akka.actor.Status.Failure) {
589 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
592 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
594 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
596 // Send another tx without immediate commit.
598 modification = dataTree.takeSnapshot().newModification();
599 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
600 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
601 modification.ready();
603 readyLocal = new ReadyLocalTransaction(tx2 , modification, false);
605 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
606 resp = followerTestKit.expectMsgClass(Object.class);
607 if (resp instanceof akka.actor.Status.Failure) {
608 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
611 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
613 ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
614 ((ReadyTransactionReply)resp).getCohortPath());
616 Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
617 Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
618 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
619 leaderDistributedDataStore.getActorContext(), Arrays.asList(
620 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), tx2);
621 cohort.canCommit().get(5, TimeUnit.SECONDS);
622 cohort.preCommit().get(5, TimeUnit.SECONDS);
623 cohort.commit().get(5, TimeUnit.SECONDS);
625 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
628 @SuppressWarnings("unchecked")
630 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
631 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
632 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
634 Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
635 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
637 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
638 DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
640 // Send a tx with immediate commit.
642 DataTreeModification modification = dataTree.takeSnapshot().newModification();
643 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
644 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
646 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
647 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
649 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1,
650 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
651 Mockito.mock(ShardDataTreeTransactionParent.class), tx1, modification), true);
653 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
654 Object resp = followerTestKit.expectMsgClass(Object.class);
655 if (resp instanceof akka.actor.Status.Failure) {
656 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
659 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
661 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
663 // Send another tx without immediate commit.
665 modification = dataTree.takeSnapshot().newModification();
666 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
667 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
669 forwardedReady = new ForwardedReadyTransaction(tx2,
670 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
671 Mockito.mock(ShardDataTreeTransactionParent.class), tx2, modification), false);
673 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
674 resp = followerTestKit.expectMsgClass(Object.class);
675 if (resp instanceof akka.actor.Status.Failure) {
676 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
679 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
681 ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
682 ((ReadyTransactionReply)resp).getCohortPath());
684 Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
685 Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
686 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
687 leaderDistributedDataStore.getActorContext(), Arrays.asList(
688 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), tx2);
689 cohort.canCommit().get(5, TimeUnit.SECONDS);
690 cohort.preCommit().get(5, TimeUnit.SECONDS);
691 cohort.commit().get(5, TimeUnit.SECONDS);
693 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
697 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
698 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
699 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
700 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
702 // Do an initial write to get the primary shard info cached.
704 DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
705 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
706 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
707 followerTestKit.doCommit(initialWriteTx.ready());
709 // Wait for the commit to be replicated to the follower.
711 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
712 raftState -> assertEquals("getLastApplied", 0, raftState.getLastApplied()));
714 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
715 raftState -> assertEquals("getLastApplied", 0, raftState.getLastApplied()));
717 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
720 DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
721 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
722 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
723 DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
724 ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
725 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
727 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
728 // in the leader shard.
730 DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
731 LinkedList<MapEntryNode> cars = new LinkedList<>();
733 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
734 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
736 NormalizedNode<?, ?> people = PeopleModel.newPersonMapNode();
737 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
738 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
740 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
741 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
742 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
745 DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
746 for (int i = 1; i <= 5; i++, carIndex++) {
747 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
748 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
751 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
754 DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
755 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
756 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
759 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
760 // leader shard on ready.
762 DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
763 cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
764 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
766 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
767 stats -> assertEquals("getReadWriteTransactionCount", 1, stats.getReadWriteTransactionCount()));
769 // Disable elections on the leader so it switches to follower.
771 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
772 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
773 .shardElectionTimeoutFactor(10));
775 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
776 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorContext(), "cars");
778 // Submit all tx's - the messages should get queued for retry.
780 ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
781 final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
782 final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
783 final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
785 // Enable elections on the other follower so it becomes the leader, at which point the
786 // tx's should get forwarded from the previous leader to the new leader to complete the commits.
788 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
789 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
791 followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
792 followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
793 followerTestKit.doCommit(writeTx3Cohort);
794 followerTestKit.doCommit(writeTx4Cohort);
795 followerTestKit.doCommit(rwTxCohort);
797 DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
798 verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
799 verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
803 public void testLeadershipTransferOnShutdown() throws Exception {
804 leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
805 followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
806 String testName = "testLeadershipTransferOnShutdown";
807 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
809 IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System, followerDatastoreContextBuilder);
810 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupDistributedDataStore(testName,
811 MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
813 // Create and submit a couple tx's so they're pending.
815 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
816 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
817 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
818 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
819 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
821 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
822 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
824 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
825 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
826 writeTx.write(CarsModel.newCarPath("optima"), car);
827 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
829 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
830 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
832 // Gracefully stop the leader via a Shutdown message.
834 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
835 .shardElectionTimeoutFactor(100));
837 FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
838 Future<ActorRef> future = leaderDistributedDataStore.getActorContext().findLocalShardAsync("cars");
839 ActorRef leaderActor = Await.result(future, duration);
841 Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
843 // Commit the 2 transactions. They should finish and succeed.
845 followerTestKit.doCommit(cohort1);
846 followerTestKit.doCommit(cohort2);
848 // Wait for the leader actor stopped.
850 Boolean stopped = Await.result(stopFuture, duration);
851 assertEquals("Stopped", Boolean.TRUE, stopped);
853 // Verify leadership was transferred by reading the committed data from the other nodes.
855 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
856 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
861 public void testTransactionWithIsolatedLeader() throws Exception {
862 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
863 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
864 String testName = "testTransactionWithIsolatedLeader";
865 initDatastoresWithCars(testName);
867 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
868 DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
869 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
871 // Tx that is submitted after the leader transitions to IsolatedLeader.
872 DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
873 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
875 // Tx that is submitted after the follower is reinstated.
876 DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
877 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
880 followerTestKit.watch(followerDistributedDataStore.getActorContext().getShardManager());
881 followerDistributedDataStore.close();
882 followerTestKit.expectTerminated(followerDistributedDataStore.getActorContext().getShardManager());
884 // Submit the preIsolatedLeaderWriteTx so it's pending
885 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
887 // Change the isolated leader check interval low so it changes to IsolatedLeader.
888 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
889 .shardIsolatedLeaderCheckIntervalInMillis(200));
891 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
892 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
895 leaderTestKit.doCommit(noShardLeaderWriteTx.ready());
896 fail("Expected NoShardLeaderException");
897 } catch (ExecutionException e) {
898 assertEquals("getCause", NoShardLeaderException.class, e.getCause().getClass());
901 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
902 .shardElectionTimeoutFactor(100));
904 DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
906 followerDistributedDataStore = followerTestKit.setupDistributedDataStore(testName,
907 MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
909 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
910 leaderTestKit.doCommit(successTxCohort);
913 @Test(expected = AskTimeoutException.class)
914 public void testTransactionWithShardLeaderNotResponding() throws Exception {
915 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
917 // Do an initial read to get the primary shard info cached.
919 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
920 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
922 // Shutdown the leader and try to create a new tx.
924 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
926 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
927 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
929 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
931 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
934 followerTestKit.doCommit(rwTx.ready());
935 } catch (ExecutionException e) {
936 assertTrue("Expected ShardLeaderNotRespondingException cause. Actual: " + e.getCause(),
937 e.getCause() instanceof ShardLeaderNotRespondingException);
938 assertNotNull("Expected a nested cause", e.getCause().getCause());
939 Throwables.propagateIfInstanceOf(e.getCause().getCause(), Exception.class);
940 Throwables.propagate(e.getCause().getCause());
944 @Test(expected = NoShardLeaderException.class)
945 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
946 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
948 // Do an initial read to get the primary shard info cached.
950 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
951 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
953 // Shutdown the leader and try to create a new tx.
955 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
957 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
959 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
961 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
962 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
964 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
966 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
969 followerTestKit.doCommit(rwTx.ready());
970 } catch (ExecutionException e) {
971 Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
972 Throwables.propagate(e.getCause());
977 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
978 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
979 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS);
981 DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
982 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
983 IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System, follower2DatastoreContextBuilder);
985 try (AbstractDataStore ds =
986 follower2TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false, CARS)) {
988 followerTestKit.waitForMembersUp("member-1", "member-3");
989 follower2TestKit.waitForMembersUp("member-1", "member-2");
991 // Do an initial read to get the primary shard info cached.
993 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
994 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
996 // Shutdown the leader and try to create a new tx.
998 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
1000 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1002 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1003 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1005 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1007 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1009 followerTestKit.doCommit(rwTx.ready());
1013 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1014 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1015 DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
1016 Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1017 Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1018 Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
1019 dataStore.onDatastoreContextUpdated(mockContextFactory);