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;
18 import akka.actor.ActorRef;
19 import akka.actor.ActorSystem;
20 import akka.actor.Address;
21 import akka.actor.AddressFromURIString;
22 import akka.cluster.Cluster;
23 import akka.pattern.AskTimeoutException;
24 import akka.testkit.JavaTestKit;
25 import com.google.common.base.Optional;
26 import com.google.common.collect.ImmutableMap;
27 import com.google.common.util.concurrent.MoreExecutors;
28 import com.google.common.util.concurrent.Uninterruptibles;
29 import com.typesafe.config.ConfigFactory;
30 import java.math.BigInteger;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.TimeUnit;
33 import org.junit.After;
34 import org.junit.Before;
35 import org.junit.Test;
36 import org.mockito.Mockito;
37 import org.mockito.invocation.InvocationOnMock;
38 import org.mockito.stubbing.Answer;
39 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
40 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
41 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
42 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
43 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
44 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
45 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
46 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
47 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
48 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
49 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
50 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
51 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
52 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
53 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
54 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
55 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
56 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
57 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
58 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
59 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
60 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
61 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
62 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
70 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
71 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
72 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
73 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
76 * End-to-end distributed data store tests that exercise remote shards and transactions.
78 * @author Thomas Pantelis
80 public class DistributedDataStoreRemotingIntegrationTest {
82 private static final String[] SHARD_NAMES = {"cars", "people"};
84 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558");
85 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2559");
87 private static final String MODULE_SHARDS_CONFIG_2 = "module-shards-member1-and-2.conf";
88 private static final String MODULE_SHARDS_CONFIG_3 = "module-shards-member1-and-2-and-3.conf";
90 private ActorSystem leaderSystem;
91 private ActorSystem followerSystem;
92 private ActorSystem follower2System;
94 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
95 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1);
97 private final DatastoreContext.Builder followerDatastoreContextBuilder =
98 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
100 private DistributedDataStore followerDistributedDataStore;
101 private DistributedDataStore leaderDistributedDataStore;
102 private IntegrationTestKit followerTestKit;
103 private IntegrationTestKit leaderTestKit;
106 public void setUp() {
107 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
108 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
110 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
111 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
113 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
114 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
118 public void tearDown() {
119 JavaTestKit.shutdownActorSystem(leaderSystem);
120 JavaTestKit.shutdownActorSystem(followerSystem);
121 JavaTestKit.shutdownActorSystem(follower2System);
124 private void initDatastores(String type) {
125 initDatastores(type, MODULE_SHARDS_CONFIG_2);
128 private void initDatastores(String type, String moduleShardsConfig) {
129 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
131 leaderDistributedDataStore = leaderTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, SHARD_NAMES);
133 followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder);
134 followerDistributedDataStore = followerTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, SHARD_NAMES);
136 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), SHARD_NAMES);
139 private static void verifyCars(DOMStoreReadTransaction readTx, MapEntryNode... entries) throws Exception {
140 Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
141 assertEquals("isPresent", true, optional.isPresent());
143 CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(CarsModel.CAR_QNAME);
144 for(NormalizedNode<?, ?> entry: entries) {
145 listBuilder.withChild((MapEntryNode) entry);
148 assertEquals("Car list node", listBuilder.build(), optional.get());
151 private static void verifyNode(DOMStoreReadTransaction readTx, YangInstanceIdentifier path, NormalizedNode<?, ?> expNode)
153 Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
154 assertEquals("isPresent", true, optional.isPresent());
155 assertEquals("Data node", expNode, optional.get());
158 private static void verifyExists(DOMStoreReadTransaction readTx, YangInstanceIdentifier path) throws Exception {
159 Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
160 assertEquals("exists", true, exists);
164 public void testWriteTransactionWithSingleShard() throws Exception {
165 String testName = "testWriteTransactionWithSingleShard";
166 initDatastores(testName);
168 String followerCarShardName = "member-2-shard-cars-" + testName;
169 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 2, ApplyJournalEntries.class );
171 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
172 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
174 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
175 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
177 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
178 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
179 writeTx.merge(car1Path, car1);
181 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
182 YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
183 writeTx.merge(car2Path, car2);
185 followerTestKit.doCommit(writeTx.ready());
187 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
189 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
193 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
195 writeTx.delete(car1Path);
197 followerTestKit.doCommit(writeTx.ready());
199 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
201 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
203 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
205 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
207 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
209 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
210 JavaTestKit.shutdownActorSystem(followerSystem, null, true);
212 ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load().getConfig("Member2"));
214 DistributedDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder).
215 setupDistributedDataStore(testName, "module-shards-member2", true, SHARD_NAMES);
217 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
219 JavaTestKit.shutdownActorSystem(newSystem);
223 public void testReadWriteTransactionWithSingleShard() throws Exception {
224 initDatastores("testReadWriteTransactionWithSingleShard");
226 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
227 assertNotNull("newReadWriteTransaction returned null", rwTx);
229 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
230 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
232 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
233 rwTx.merge(CarsModel.newCarPath("optima"), car1);
235 verifyCars(rwTx, car1);
237 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
238 YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
239 rwTx.merge(car2Path, car2);
241 verifyExists(rwTx, car2Path);
243 followerTestKit.doCommit(rwTx.ready());
245 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
249 public void testWriteTransactionWithMultipleShards() throws Exception {
250 initDatastores("testWriteTransactionWithMultipleShards");
252 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
253 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
255 YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
256 NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
257 writeTx.write(carsPath, carsNode);
259 YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
260 NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
261 writeTx.write(peoplePath, peopleNode);
263 followerTestKit.doCommit(writeTx.ready());
265 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
267 verifyNode(readTx, carsPath, carsNode);
268 verifyNode(readTx, peoplePath, peopleNode);
272 public void testReadWriteTransactionWithMultipleShards() throws Exception {
273 initDatastores("testReadWriteTransactionWithMultipleShards");
275 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
276 assertNotNull("newReadWriteTransaction returned null", rwTx);
278 YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
279 NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
280 rwTx.write(carsPath, carsNode);
282 YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
283 NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
284 rwTx.write(peoplePath, peopleNode);
286 followerTestKit.doCommit(rwTx.ready());
288 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
290 verifyNode(readTx, carsPath, carsNode);
291 verifyNode(readTx, peoplePath, peopleNode);
295 public void testTransactionChainWithSingleShard() throws Exception {
296 initDatastores("testTransactionChainWithSingleShard");
298 DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
300 // Add the top-level cars container with write-only.
302 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
303 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
305 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
309 // Verify the top-level cars container with read-only.
311 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
313 // Perform car operations with read-write.
315 DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
317 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
319 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
321 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
322 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
323 rwTx.write(car1Path, car1);
325 verifyExists(rwTx, car1Path);
327 verifyCars(rwTx, car1);
329 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
330 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
332 rwTx.delete(car1Path);
334 followerTestKit.doCommit(rwTx.ready());
338 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
342 public void testTransactionChainWithMultipleShards() throws Exception{
343 initDatastores("testTransactionChainWithMultipleShards");
345 DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
347 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
348 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
350 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
351 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
353 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
354 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
356 followerTestKit.doCommit(writeTx.ready());
358 DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
360 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
361 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
362 readWriteTx.write(carPath, car);
364 MapEntryNode person = PeopleModel.newPersonEntry("jack");
365 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
366 readWriteTx.merge(personPath, person);
368 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
369 assertEquals("isPresent", true, optional.isPresent());
370 assertEquals("Data node", car, optional.get());
372 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
373 assertEquals("isPresent", true, optional.isPresent());
374 assertEquals("Data node", person, optional.get());
376 DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
378 writeTx = txChain.newWriteOnlyTransaction();
380 writeTx.delete(personPath);
382 DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
384 followerTestKit.doCommit(cohort2);
385 followerTestKit.doCommit(cohort3);
389 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
390 verifyCars(readTx, car);
392 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
393 assertEquals("isPresent", false, optional.isPresent());
397 public void testChainedTransactionFailureWithSingleShard() throws Exception {
398 initDatastores("testChainedTransactionFailureWithSingleShard");
400 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
401 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
402 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
403 MoreExecutors.directExecutor());
405 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
406 DOMTransactionChain txChain = broker.createTransactionChain(listener);
408 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
410 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
411 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
412 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
414 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
417 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
418 fail("Expected TransactionCommitFailedException");
419 } catch (TransactionCommitFailedException e) {
423 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
430 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
431 initDatastores("testChainedTransactionFailureWithMultipleShards");
433 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
434 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
435 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
436 MoreExecutors.directExecutor());
438 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
439 DOMTransactionChain txChain = broker.createTransactionChain(listener);
441 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
443 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
445 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
446 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
447 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
449 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
450 // done for put for performance reasons.
451 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
454 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
455 fail("Expected TransactionCommitFailedException");
456 } catch (TransactionCommitFailedException e) {
460 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
467 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
468 String testName = "testSingleShardTransactionsWithLeaderChanges";
469 initDatastores(testName);
471 String followerCarShardName = "member-2-shard-cars-" + testName;
472 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class );
474 // Write top-level car container from the follower so it uses a remote Tx.
476 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
478 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
479 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
481 followerTestKit.doCommit(writeTx.ready());
483 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
485 // Switch the leader to the follower
487 followerDatastoreContextBuilder.shardElectionTimeoutFactor(1);
488 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
490 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
492 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorContext(), SHARD_NAMES);
494 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
495 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
497 DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder().
498 shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
499 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder);
500 newMember1TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CONFIG_2, false, SHARD_NAMES);
502 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), SHARD_NAMES);
504 // Write a car entry to the new leader - should switch to local Tx
506 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
508 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
509 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
510 writeTx.merge(car1Path, car1);
512 followerTestKit.doCommit(writeTx.ready());
514 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
518 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
519 initDatastores("testReadyLocalTransactionForwardedToLeader");
520 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
522 Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
523 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
525 TipProducingDataTree dataTree = InMemoryDataTreeFactory.getInstance().create();
526 dataTree.setSchemaContext(SchemaContextHelper.full());
527 DataTreeModification modification = dataTree.takeSnapshot().newModification();
529 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
530 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
532 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
533 new WriteModification(CarsModel.newCarPath("optima"), car).apply(modification);
535 String transactionID = "tx-1";
536 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(transactionID , modification, true);
538 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
539 Object resp = followerTestKit.expectMsgClass(Object.class);
540 if(resp instanceof akka.actor.Status.Failure) {
541 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
544 assertTrue("Expected response of type " + CommitTransactionReply.SERIALIZABLE_CLASS,
545 CommitTransactionReply.SERIALIZABLE_CLASS.equals(resp.getClass()));
547 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car);
550 @Test(expected=NoShardLeaderException.class)
551 public void testTransactionWithIsolatedLeader() throws Throwable {
552 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(300);
553 String testName = "testTransactionWithIsolatedLeader";
554 initDatastores(testName);
556 JavaTestKit.shutdownActorSystem(followerSystem, null, true);
558 Uninterruptibles.sleepUninterruptibly(leaderDistributedDataStore.getActorContext().getDatastoreContext()
559 .getShardRaftConfig().getElectionTimeOutInterval().toMillis() * 3, TimeUnit.MILLISECONDS);
561 DOMStoreWriteTransaction writeTx = leaderDistributedDataStore.newWriteOnlyTransaction();
562 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
565 followerTestKit.doCommit(writeTx.ready());
566 } catch (ExecutionException e) {
571 @Test(expected=AskTimeoutException.class)
572 public void testTransactionWithShardLeaderNotResponding() throws Throwable {
573 followerDatastoreContextBuilder.shardElectionTimeoutFactor(30);
574 initDatastores("testTransactionWithShardLeaderNotResponding");
576 // Do an initial read to get the primary shard info cached.
578 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
579 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
581 // Shutdown the leader and try to create a new tx.
583 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
585 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
586 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
588 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
590 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
593 followerTestKit.doCommit(rwTx.ready());
594 } catch (ExecutionException e) {
595 assertTrue("Expected ShardLeaderNotRespondingException cause. Actual: " + e.getCause(),
596 e.getCause() instanceof ShardLeaderNotRespondingException);
597 assertNotNull("Expected a nested cause", e.getCause().getCause());
598 throw e.getCause().getCause();
602 @Test(expected=NoShardLeaderException.class)
603 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Throwable {
604 initDatastores("testTransactionWithCreateTxFailureDueToNoLeader");
606 // Do an initial read to get the primary shard info cached.
608 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
609 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
611 // Shutdown the leader and try to create a new tx.
613 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
615 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
617 followerDatastoreContextBuilder.operationTimeoutInMillis(10).shardElectionTimeoutFactor(1);
618 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
620 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
622 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
625 followerTestKit.doCommit(rwTx.ready());
626 } catch (ExecutionException e) {
632 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
633 followerDatastoreContextBuilder.shardElectionTimeoutFactor(30);
634 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
635 initDatastores(testName, MODULE_SHARDS_CONFIG_3);
637 DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder().
638 shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
639 IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System, follower2DatastoreContextBuilder);
640 follower2TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CONFIG_3, false, SHARD_NAMES);
642 // Do an initial read to get the primary shard info cached.
644 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
645 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
647 // Shutdown the leader and try to create a new tx.
649 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
651 followerDatastoreContextBuilder.operationTimeoutInMillis(500);
652 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
654 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
656 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
658 followerTestKit.doCommit(rwTx.ready());
661 private static void sendDatastoreContextUpdate(DistributedDataStore dataStore, final Builder builder) {
662 DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
663 Answer<DatastoreContext> answer = new Answer<DatastoreContext>() {
665 public DatastoreContext answer(InvocationOnMock invocation) {
666 return builder.build();
669 Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
670 Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
671 dataStore.onDatastoreContextUpdated(mockContextFactory);