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.ActorSelection;
20 import akka.actor.ActorSystem;
21 import akka.actor.Address;
22 import akka.actor.AddressFromURIString;
23 import akka.cluster.Cluster;
24 import akka.dispatch.Futures;
25 import akka.pattern.AskTimeoutException;
26 import akka.testkit.JavaTestKit;
27 import com.google.common.base.Optional;
28 import com.google.common.collect.ImmutableMap;
29 import com.google.common.util.concurrent.MoreExecutors;
30 import com.google.common.util.concurrent.Uninterruptibles;
31 import com.typesafe.config.ConfigFactory;
32 import java.math.BigInteger;
33 import java.util.Arrays;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.TimeUnit;
36 import org.junit.After;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.mockito.Mockito;
40 import org.mockito.invocation.InvocationOnMock;
41 import org.mockito.stubbing.Answer;
42 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
43 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
44 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
45 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
46 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
47 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
48 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
50 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
51 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
52 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
53 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
54 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
55 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
56 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
57 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
58 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
59 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
60 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
61 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
62 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
63 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
64 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
65 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
66 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
67 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
68 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
78 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
79 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
84 * End-to-end distributed data store tests that exercise remote shards and transactions.
86 * @author Thomas Pantelis
88 public class DistributedDataStoreRemotingIntegrationTest {
90 private static final String[] SHARD_NAMES = {"cars", "people"};
92 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558");
93 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2559");
95 private static final String MODULE_SHARDS_CONFIG_2 = "module-shards-member1-and-2.conf";
96 private static final String MODULE_SHARDS_CONFIG_3 = "module-shards-member1-and-2-and-3.conf";
98 private ActorSystem leaderSystem;
99 private ActorSystem followerSystem;
100 private ActorSystem follower2System;
102 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
103 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1);
105 private final DatastoreContext.Builder followerDatastoreContextBuilder =
106 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
108 private DistributedDataStore followerDistributedDataStore;
109 private DistributedDataStore leaderDistributedDataStore;
110 private IntegrationTestKit followerTestKit;
111 private IntegrationTestKit leaderTestKit;
114 public void setUp() {
115 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
116 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
118 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
119 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
121 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
122 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
126 public void tearDown() {
127 JavaTestKit.shutdownActorSystem(leaderSystem);
128 JavaTestKit.shutdownActorSystem(followerSystem);
129 JavaTestKit.shutdownActorSystem(follower2System);
132 private void initDatastores(String type) {
133 initDatastores(type, MODULE_SHARDS_CONFIG_2);
136 private void initDatastores(String type, String moduleShardsConfig) {
137 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
139 leaderDistributedDataStore = leaderTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, SHARD_NAMES);
141 followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder);
142 followerDistributedDataStore = followerTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, SHARD_NAMES);
144 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), SHARD_NAMES);
147 private static void verifyCars(DOMStoreReadTransaction readTx, MapEntryNode... entries) throws Exception {
148 Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
149 assertEquals("isPresent", true, optional.isPresent());
151 CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(CarsModel.CAR_QNAME);
152 for(NormalizedNode<?, ?> entry: entries) {
153 listBuilder.withChild((MapEntryNode) entry);
156 assertEquals("Car list node", listBuilder.build(), optional.get());
159 private static void verifyNode(DOMStoreReadTransaction readTx, YangInstanceIdentifier path, NormalizedNode<?, ?> expNode)
161 Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
162 assertEquals("isPresent", true, optional.isPresent());
163 assertEquals("Data node", expNode, optional.get());
166 private static void verifyExists(DOMStoreReadTransaction readTx, YangInstanceIdentifier path) throws Exception {
167 Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
168 assertEquals("exists", true, exists);
172 public void testWriteTransactionWithSingleShard() throws Exception {
173 String testName = "testWriteTransactionWithSingleShard";
174 initDatastores(testName);
176 String followerCarShardName = "member-2-shard-cars-" + testName;
177 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 2, ApplyJournalEntries.class );
179 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
180 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
182 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
183 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
185 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
186 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
187 writeTx.merge(car1Path, car1);
189 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
190 YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
191 writeTx.merge(car2Path, car2);
193 followerTestKit.doCommit(writeTx.ready());
195 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
197 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
201 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
203 writeTx.delete(car1Path);
205 followerTestKit.doCommit(writeTx.ready());
207 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
209 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
211 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
213 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
215 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
217 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
218 JavaTestKit.shutdownActorSystem(followerSystem, null, true);
220 ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load().getConfig("Member2"));
222 DistributedDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder).
223 setupDistributedDataStore(testName, "module-shards-member2", true, SHARD_NAMES);
225 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
227 JavaTestKit.shutdownActorSystem(newSystem);
231 public void testReadWriteTransactionWithSingleShard() throws Exception {
232 initDatastores("testReadWriteTransactionWithSingleShard");
234 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
235 assertNotNull("newReadWriteTransaction returned null", rwTx);
237 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
238 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
240 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
241 rwTx.merge(CarsModel.newCarPath("optima"), car1);
243 verifyCars(rwTx, car1);
245 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
246 YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
247 rwTx.merge(car2Path, car2);
249 verifyExists(rwTx, car2Path);
251 followerTestKit.doCommit(rwTx.ready());
253 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
257 public void testWriteTransactionWithMultipleShards() throws Exception {
258 initDatastores("testWriteTransactionWithMultipleShards");
260 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
261 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
263 YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
264 NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
265 writeTx.write(carsPath, carsNode);
267 YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
268 NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
269 writeTx.write(peoplePath, peopleNode);
271 followerTestKit.doCommit(writeTx.ready());
273 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
275 verifyNode(readTx, carsPath, carsNode);
276 verifyNode(readTx, peoplePath, peopleNode);
280 public void testReadWriteTransactionWithMultipleShards() throws Exception {
281 initDatastores("testReadWriteTransactionWithMultipleShards");
283 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
284 assertNotNull("newReadWriteTransaction returned null", rwTx);
286 YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
287 NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
288 rwTx.write(carsPath, carsNode);
290 YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
291 NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
292 rwTx.write(peoplePath, peopleNode);
294 followerTestKit.doCommit(rwTx.ready());
296 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
298 verifyNode(readTx, carsPath, carsNode);
299 verifyNode(readTx, peoplePath, peopleNode);
303 public void testTransactionChainWithSingleShard() throws Exception {
304 initDatastores("testTransactionChainWithSingleShard");
306 DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
308 // Add the top-level cars container with write-only.
310 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
311 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
313 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
317 // Verify the top-level cars container with read-only.
319 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
321 // Perform car operations with read-write.
323 DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
325 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
327 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
329 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
330 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
331 rwTx.write(car1Path, car1);
333 verifyExists(rwTx, car1Path);
335 verifyCars(rwTx, car1);
337 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
338 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
340 rwTx.delete(car1Path);
342 followerTestKit.doCommit(rwTx.ready());
346 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
350 public void testTransactionChainWithMultipleShards() throws Exception{
351 initDatastores("testTransactionChainWithMultipleShards");
353 DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
355 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
356 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
358 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
359 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
361 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
362 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
364 followerTestKit.doCommit(writeTx.ready());
366 DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
368 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
369 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
370 readWriteTx.write(carPath, car);
372 MapEntryNode person = PeopleModel.newPersonEntry("jack");
373 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
374 readWriteTx.merge(personPath, person);
376 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
377 assertEquals("isPresent", true, optional.isPresent());
378 assertEquals("Data node", car, optional.get());
380 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
381 assertEquals("isPresent", true, optional.isPresent());
382 assertEquals("Data node", person, optional.get());
384 DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
386 writeTx = txChain.newWriteOnlyTransaction();
388 writeTx.delete(personPath);
390 DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
392 followerTestKit.doCommit(cohort2);
393 followerTestKit.doCommit(cohort3);
397 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
398 verifyCars(readTx, car);
400 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
401 assertEquals("isPresent", false, optional.isPresent());
405 public void testChainedTransactionFailureWithSingleShard() throws Exception {
406 initDatastores("testChainedTransactionFailureWithSingleShard");
408 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
409 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
410 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
411 MoreExecutors.directExecutor());
413 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
414 DOMTransactionChain txChain = broker.createTransactionChain(listener);
416 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
418 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
419 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
420 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
422 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
425 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
426 fail("Expected TransactionCommitFailedException");
427 } catch (TransactionCommitFailedException e) {
431 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
438 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
439 initDatastores("testChainedTransactionFailureWithMultipleShards");
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 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
453 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
454 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
455 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
457 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
458 // done for put for performance reasons.
459 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
462 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
463 fail("Expected TransactionCommitFailedException");
464 } catch (TransactionCommitFailedException e) {
468 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
475 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
476 String testName = "testSingleShardTransactionsWithLeaderChanges";
477 initDatastores(testName);
479 String followerCarShardName = "member-2-shard-cars-" + testName;
480 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class );
482 // Write top-level car container from the follower so it uses a remote Tx.
484 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
486 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
487 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
489 followerTestKit.doCommit(writeTx.ready());
491 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
493 // Switch the leader to the follower
495 followerDatastoreContextBuilder.shardElectionTimeoutFactor(1);
496 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
498 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
500 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorContext(), SHARD_NAMES);
502 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
503 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
505 DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder().
506 shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
507 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder);
508 newMember1TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CONFIG_2, false, SHARD_NAMES);
510 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), SHARD_NAMES);
512 // Write a car entry to the new leader - should switch to local Tx
514 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
516 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
517 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
518 writeTx.merge(car1Path, car1);
520 followerTestKit.doCommit(writeTx.ready());
522 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
526 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
527 initDatastores("testReadyLocalTransactionForwardedToLeader");
528 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
530 Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
531 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
533 TipProducingDataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
534 dataTree.setSchemaContext(SchemaContextHelper.full());
536 // Send a tx with immediate commit.
538 DataTreeModification modification = dataTree.takeSnapshot().newModification();
539 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
540 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
542 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
543 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
544 modification.ready();
546 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction("tx-1" , modification, true);
548 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
549 Object resp = followerTestKit.expectMsgClass(Object.class);
550 if(resp instanceof akka.actor.Status.Failure) {
551 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
554 assertEquals("Response type", CommitTransactionReply.SERIALIZABLE_CLASS, resp.getClass());
556 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
558 // Send another tx without immediate commit.
560 modification = dataTree.takeSnapshot().newModification();
561 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
562 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
563 modification.ready();
565 readyLocal = new ReadyLocalTransaction("tx-2" , modification, false);
567 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
568 resp = followerTestKit.expectMsgClass(Object.class);
569 if(resp instanceof akka.actor.Status.Failure) {
570 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
573 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
575 ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
576 ((ReadyTransactionReply)resp).getCohortPath());
578 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
579 leaderDistributedDataStore.getActorContext(), Arrays.asList(Futures.successful(txActor)), "tx-2");
580 cohort.canCommit().get(5, TimeUnit.SECONDS);
581 cohort.preCommit().get(5, TimeUnit.SECONDS);
582 cohort.commit().get(5, TimeUnit.SECONDS);
584 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
588 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
589 initDatastores("testForwardedReadyTransactionForwardedToLeader");
590 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
592 Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
593 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
595 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
596 DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
598 // Send a tx with immediate commit.
600 DataTreeModification modification = dataTree.takeSnapshot().newModification();
601 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
602 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
604 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
605 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
607 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction("tx-1",
608 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
609 Mockito.mock(ShardDataTreeTransactionParent.class), "tx-1", modification), true, true);
611 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
612 Object resp = followerTestKit.expectMsgClass(Object.class);
613 if(resp instanceof akka.actor.Status.Failure) {
614 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
617 assertEquals("Response type", CommitTransactionReply.SERIALIZABLE_CLASS, resp.getClass());
619 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
621 // Send another tx without immediate commit.
623 modification = dataTree.takeSnapshot().newModification();
624 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
625 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
627 forwardedReady = new ForwardedReadyTransaction("tx-2",
628 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
629 Mockito.mock(ShardDataTreeTransactionParent.class), "tx-2", modification), true, false);
631 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
632 resp = followerTestKit.expectMsgClass(Object.class);
633 if(resp instanceof akka.actor.Status.Failure) {
634 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
637 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
639 ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
640 ((ReadyTransactionReply)resp).getCohortPath());
642 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
643 leaderDistributedDataStore.getActorContext(), Arrays.asList(Futures.successful(txActor)), "tx-2");
644 cohort.canCommit().get(5, TimeUnit.SECONDS);
645 cohort.preCommit().get(5, TimeUnit.SECONDS);
646 cohort.commit().get(5, TimeUnit.SECONDS);
648 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
651 @Test(expected=NoShardLeaderException.class)
652 public void testTransactionWithIsolatedLeader() throws Throwable {
653 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(300);
654 String testName = "testTransactionWithIsolatedLeader";
655 initDatastores(testName);
657 JavaTestKit.shutdownActorSystem(followerSystem, null, true);
659 Uninterruptibles.sleepUninterruptibly(leaderDistributedDataStore.getActorContext().getDatastoreContext()
660 .getShardRaftConfig().getElectionTimeOutInterval().toMillis() * 3, TimeUnit.MILLISECONDS);
662 DOMStoreWriteTransaction writeTx = leaderDistributedDataStore.newWriteOnlyTransaction();
663 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
666 followerTestKit.doCommit(writeTx.ready());
667 } catch (ExecutionException e) {
672 @Test(expected=AskTimeoutException.class)
673 public void testTransactionWithShardLeaderNotResponding() throws Throwable {
674 followerDatastoreContextBuilder.shardElectionTimeoutFactor(30);
675 initDatastores("testTransactionWithShardLeaderNotResponding");
677 // Do an initial read to get the primary shard info cached.
679 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
680 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
682 // Shutdown the leader and try to create a new tx.
684 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
686 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
687 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
689 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
691 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
694 followerTestKit.doCommit(rwTx.ready());
695 } catch (ExecutionException e) {
696 assertTrue("Expected ShardLeaderNotRespondingException cause. Actual: " + e.getCause(),
697 e.getCause() instanceof ShardLeaderNotRespondingException);
698 assertNotNull("Expected a nested cause", e.getCause().getCause());
699 throw e.getCause().getCause();
703 @Test(expected=NoShardLeaderException.class)
704 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Throwable {
705 initDatastores("testTransactionWithCreateTxFailureDueToNoLeader");
707 // Do an initial read to get the primary shard info cached.
709 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
710 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
712 // Shutdown the leader and try to create a new tx.
714 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
716 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
718 followerDatastoreContextBuilder.operationTimeoutInMillis(10).shardElectionTimeoutFactor(1);
719 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
721 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
723 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
726 followerTestKit.doCommit(rwTx.ready());
727 } catch (ExecutionException e) {
733 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
734 followerDatastoreContextBuilder.shardElectionTimeoutFactor(30);
735 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
736 initDatastores(testName, MODULE_SHARDS_CONFIG_3);
738 DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder().
739 shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
740 IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System, follower2DatastoreContextBuilder);
741 follower2TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CONFIG_3, false, SHARD_NAMES);
743 // Do an initial read to get the primary shard info cached.
745 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
746 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
748 // Shutdown the leader and try to create a new tx.
750 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
752 followerDatastoreContextBuilder.operationTimeoutInMillis(500);
753 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
755 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
757 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
759 followerTestKit.doCommit(rwTx.ready());
762 private static void sendDatastoreContextUpdate(DistributedDataStore dataStore, final Builder builder) {
763 DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
764 Answer<DatastoreContext> answer = new Answer<DatastoreContext>() {
766 public DatastoreContext answer(InvocationOnMock invocation) {
767 return builder.build();
770 Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
771 Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
772 dataStore.onDatastoreContextUpdated(mockContextFactory);