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.IntegrationTestKit.ShardStatsVerifier;
44 import org.opendaylight.controller.cluster.datastore.MemberNode.RaftStateVerifier;
45 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
46 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
47 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
48 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
49 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
50 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
51 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
52 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
53 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
54 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
55 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
56 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
57 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
58 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
59 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
60 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
61 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
62 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
63 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
64 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
65 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
66 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
67 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
68 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
69 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
70 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
71 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
72 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
73 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
74 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
75 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
82 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
83 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
84 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
85 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
86 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
89 * End-to-end distributed data store tests that exercise remote shards and transactions.
91 * @author Thomas Pantelis
93 public class DistributedDataStoreRemotingIntegrationTest {
95 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
96 private static final String[] CARS = {"cars"};
98 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558");
99 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2559");
101 private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
102 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
103 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
105 private ActorSystem leaderSystem;
106 private ActorSystem followerSystem;
107 private ActorSystem follower2System;
109 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
110 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
112 private final DatastoreContext.Builder followerDatastoreContextBuilder =
113 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5).
114 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
116 private DistributedDataStore followerDistributedDataStore;
117 private DistributedDataStore leaderDistributedDataStore;
118 private IntegrationTestKit followerTestKit;
119 private IntegrationTestKit leaderTestKit;
122 public void setUp() {
123 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
124 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
126 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
127 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
129 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
130 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
134 public void tearDown() {
135 JavaTestKit.shutdownActorSystem(leaderSystem);
136 JavaTestKit.shutdownActorSystem(followerSystem);
137 JavaTestKit.shutdownActorSystem(follower2System);
140 private void initDatastoresWithCars(String type) {
141 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
144 private void initDatastoresWithCarsAndPeople(String type) {
145 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
148 private void initDatastores(String type, String moduleShardsConfig, String[] shards) {
149 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
151 leaderDistributedDataStore = leaderTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, shards);
153 followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder);
154 followerDistributedDataStore = followerTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, shards);
156 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), shards);
159 private static void verifyCars(DOMStoreReadTransaction readTx, MapEntryNode... entries) throws Exception {
160 Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
161 assertEquals("isPresent", true, optional.isPresent());
163 CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(CarsModel.CAR_QNAME);
164 for(NormalizedNode<?, ?> entry: entries) {
165 listBuilder.withChild((MapEntryNode) entry);
168 assertEquals("Car list node", listBuilder.build(), optional.get());
171 private static void verifyNode(DOMStoreReadTransaction readTx, YangInstanceIdentifier path, NormalizedNode<?, ?> expNode)
173 Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
174 assertEquals("isPresent", true, optional.isPresent());
175 assertEquals("Data node", expNode, optional.get());
178 private static void verifyExists(DOMStoreReadTransaction readTx, YangInstanceIdentifier path) throws Exception {
179 Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
180 assertEquals("exists", true, exists);
184 public void testWriteTransactionWithSingleShard() throws Exception {
185 String testName = "testWriteTransactionWithSingleShard";
186 initDatastoresWithCars(testName);
188 String followerCarShardName = "member-2-shard-cars-" + testName;
189 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 2, ApplyJournalEntries.class );
191 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
192 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
194 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
195 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
197 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
198 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
199 writeTx.merge(car1Path, car1);
201 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
202 YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
203 writeTx.merge(car2Path, car2);
205 followerTestKit.doCommit(writeTx.ready());
207 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
209 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
213 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
215 writeTx.delete(car1Path);
217 followerTestKit.doCommit(writeTx.ready());
219 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
221 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
223 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
225 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
227 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
229 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
230 JavaTestKit.shutdownActorSystem(followerSystem, null, true);
232 ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load().getConfig("Member2"));
234 DistributedDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder).
235 setupDistributedDataStore(testName, "module-shards-member2", true, CARS_AND_PEOPLE);
237 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
239 JavaTestKit.shutdownActorSystem(newSystem);
243 public void testReadWriteTransactionWithSingleShard() throws Exception {
244 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
246 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
247 assertNotNull("newReadWriteTransaction returned null", rwTx);
249 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
250 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
252 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
253 rwTx.merge(CarsModel.newCarPath("optima"), car1);
255 verifyCars(rwTx, car1);
257 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
258 YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
259 rwTx.merge(car2Path, car2);
261 verifyExists(rwTx, car2Path);
263 followerTestKit.doCommit(rwTx.ready());
265 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
269 public void testWriteTransactionWithMultipleShards() throws Exception {
270 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
272 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
273 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
275 YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
276 NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
277 writeTx.write(carsPath, carsNode);
279 YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
280 NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
281 writeTx.write(peoplePath, peopleNode);
283 followerTestKit.doCommit(writeTx.ready());
285 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
287 verifyNode(readTx, carsPath, carsNode);
288 verifyNode(readTx, peoplePath, peopleNode);
292 public void testReadWriteTransactionWithMultipleShards() throws Exception {
293 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
295 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
296 assertNotNull("newReadWriteTransaction returned null", rwTx);
298 YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
299 NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
300 rwTx.write(carsPath, carsNode);
302 YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
303 NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
304 rwTx.write(peoplePath, peopleNode);
306 followerTestKit.doCommit(rwTx.ready());
308 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
310 verifyNode(readTx, carsPath, carsNode);
311 verifyNode(readTx, peoplePath, peopleNode);
315 public void testTransactionChainWithSingleShard() throws Exception {
316 initDatastoresWithCars("testTransactionChainWithSingleShard");
318 DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
320 // Add the top-level cars container with write-only.
322 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
323 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
325 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
329 // Verify the top-level cars container with read-only.
331 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
333 // Perform car operations with read-write.
335 DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
337 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
339 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
341 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
342 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
343 rwTx.write(car1Path, car1);
345 verifyExists(rwTx, car1Path);
347 verifyCars(rwTx, car1);
349 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(25000));
350 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
352 rwTx.delete(car1Path);
354 followerTestKit.doCommit(rwTx.ready());
358 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
362 public void testTransactionChainWithMultipleShards() throws Exception{
363 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
365 DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
367 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
368 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
370 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
371 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
373 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
374 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
376 followerTestKit.doCommit(writeTx.ready());
378 DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
380 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
381 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
382 readWriteTx.write(carPath, car);
384 MapEntryNode person = PeopleModel.newPersonEntry("jack");
385 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
386 readWriteTx.merge(personPath, person);
388 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
389 assertEquals("isPresent", true, optional.isPresent());
390 assertEquals("Data node", car, optional.get());
392 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
393 assertEquals("isPresent", true, optional.isPresent());
394 assertEquals("Data node", person, optional.get());
396 DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
398 writeTx = txChain.newWriteOnlyTransaction();
400 writeTx.delete(personPath);
402 DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
404 followerTestKit.doCommit(cohort2);
405 followerTestKit.doCommit(cohort3);
409 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
410 verifyCars(readTx, car);
412 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
413 assertEquals("isPresent", false, optional.isPresent());
417 public void testChainedTransactionFailureWithSingleShard() throws Exception {
418 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
420 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
421 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
422 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
423 MoreExecutors.directExecutor());
425 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
426 DOMTransactionChain txChain = broker.createTransactionChain(listener);
428 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
430 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
431 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
432 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
434 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
437 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
438 fail("Expected TransactionCommitFailedException");
439 } catch (TransactionCommitFailedException e) {
443 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
450 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
451 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
453 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
454 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
455 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
456 MoreExecutors.directExecutor());
458 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
459 DOMTransactionChain txChain = broker.createTransactionChain(listener);
461 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
463 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
465 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
466 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
467 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
469 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
470 // done for put for performance reasons.
471 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
474 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
475 fail("Expected TransactionCommitFailedException");
476 } catch (TransactionCommitFailedException e) {
480 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
487 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
488 String testName = "testSingleShardTransactionsWithLeaderChanges";
489 initDatastoresWithCars(testName);
491 String followerCarShardName = "member-2-shard-cars-" + testName;
492 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class );
494 // Write top-level car container from the follower so it uses a remote Tx.
496 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
498 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
499 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
501 followerTestKit.doCommit(writeTx.ready());
503 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
505 // Switch the leader to the follower
507 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
508 shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
510 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
512 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorContext(), CARS);
514 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
515 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
517 DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder().
518 shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
519 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder);
520 newMember1TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
522 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), CARS);
524 // Write a car entry to the new leader - should switch to local Tx
526 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
528 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
529 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
530 writeTx.merge(car1Path, car1);
532 followerTestKit.doCommit(writeTx.ready());
534 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
538 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
539 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
540 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
542 Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
543 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
545 TipProducingDataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
546 dataTree.setSchemaContext(SchemaContextHelper.full());
548 // Send a tx with immediate commit.
550 DataTreeModification modification = dataTree.takeSnapshot().newModification();
551 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
552 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
554 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
555 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
556 modification.ready();
558 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction("tx-1" , modification, true);
560 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
561 Object resp = followerTestKit.expectMsgClass(Object.class);
562 if(resp instanceof akka.actor.Status.Failure) {
563 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
566 assertEquals("Response type", CommitTransactionReply.SERIALIZABLE_CLASS, resp.getClass());
568 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
570 // Send another tx without immediate commit.
572 modification = dataTree.takeSnapshot().newModification();
573 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
574 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
575 modification.ready();
577 readyLocal = new ReadyLocalTransaction("tx-2" , modification, false);
579 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
580 resp = followerTestKit.expectMsgClass(Object.class);
581 if(resp instanceof akka.actor.Status.Failure) {
582 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
585 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
587 ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
588 ((ReadyTransactionReply)resp).getCohortPath());
590 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
591 leaderDistributedDataStore.getActorContext(), Arrays.asList(Futures.successful(txActor)), "tx-2");
592 cohort.canCommit().get(5, TimeUnit.SECONDS);
593 cohort.preCommit().get(5, TimeUnit.SECONDS);
594 cohort.commit().get(5, TimeUnit.SECONDS);
596 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
600 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
601 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
602 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorContext(), "cars");
604 Optional<ActorRef> carsFollowerShard = followerDistributedDataStore.getActorContext().findLocalShard("cars");
605 assertEquals("Cars follower shard found", true, carsFollowerShard.isPresent());
607 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
608 DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
610 // Send a tx with immediate commit.
612 DataTreeModification modification = dataTree.takeSnapshot().newModification();
613 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
614 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
616 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
617 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
619 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction("tx-1",
620 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
621 Mockito.mock(ShardDataTreeTransactionParent.class), "tx-1", modification), true, true);
623 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
624 Object resp = followerTestKit.expectMsgClass(Object.class);
625 if(resp instanceof akka.actor.Status.Failure) {
626 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
629 assertEquals("Response type", CommitTransactionReply.SERIALIZABLE_CLASS, resp.getClass());
631 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
633 // Send another tx without immediate commit.
635 modification = dataTree.takeSnapshot().newModification();
636 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
637 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
639 forwardedReady = new ForwardedReadyTransaction("tx-2",
640 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
641 Mockito.mock(ShardDataTreeTransactionParent.class), "tx-2", modification), true, false);
643 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
644 resp = followerTestKit.expectMsgClass(Object.class);
645 if(resp instanceof akka.actor.Status.Failure) {
646 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
649 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
651 ActorSelection txActor = leaderDistributedDataStore.getActorContext().actorSelection(
652 ((ReadyTransactionReply)resp).getCohortPath());
654 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
655 leaderDistributedDataStore.getActorContext(), Arrays.asList(Futures.successful(txActor)), "tx-2");
656 cohort.canCommit().get(5, TimeUnit.SECONDS);
657 cohort.preCommit().get(5, TimeUnit.SECONDS);
658 cohort.commit().get(5, TimeUnit.SECONDS);
660 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
664 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
665 initDatastoresWithCars("testTransactionForwardedToLeaderAfterRetry");
667 // Do an initial write to get the primary shard info cached.
669 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
670 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
671 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
672 followerTestKit.doCommit(writeTx.ready());
674 // Wait for the commit to be replicated to the follower.
676 MemberNode.verifyRaftState(followerDistributedDataStore, "cars", new RaftStateVerifier() {
678 public void verify(OnDemandRaftState raftState) {
679 assertEquals("getLastApplied", 0, raftState.getLastApplied());
683 // Create and prepare wo and rw tx's.
685 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
686 MapEntryNode car1 = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
687 writeTx.write(CarsModel.newCarPath("optima"), car1);
689 DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
690 MapEntryNode car2 = CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000));
691 readWriteTx.write(CarsModel.newCarPath("sportage"), car2);
693 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars", new ShardStatsVerifier() {
695 public void verify(ShardStats stats) {
696 assertEquals("getReadWriteTransactionCount", 1, stats.getReadWriteTransactionCount());
700 // Disable elections on the leader so it switches to follower.
702 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder.
703 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
704 shardElectionTimeoutFactor(10));
706 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorContext(), "cars");
708 // Submit tx's and enable elections on the follower so it becomes the leader, at which point the
709 // readied tx's should get forwarded from the previous leader.
711 DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
712 DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
714 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
715 customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
717 followerTestKit.doCommit(cohort1);
718 followerTestKit.doCommit(cohort2);
720 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
724 public void testTransactionWithIsolatedLeader() throws Throwable {
725 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(200);
726 String testName = "testTransactionWithIsolatedLeader";
727 initDatastoresWithCars(testName);
729 DOMStoreWriteTransaction failWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
730 failWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
732 DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
733 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
735 followerTestKit.watch(followerDistributedDataStore.getActorContext().getShardManager());
736 followerDistributedDataStore.close();
737 followerTestKit.expectTerminated(followerDistributedDataStore.getActorContext().getShardManager());
739 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars", new RaftStateVerifier() {
741 public void verify(OnDemandRaftState raftState) {
742 assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState());
747 leaderTestKit.doCommit(failWriteTx.ready());
748 fail("Expected NoShardLeaderException");
749 } catch (ExecutionException e) {
750 assertEquals("getCause", NoShardLeaderException.class, e.getCause().getClass());
753 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder.
754 shardElectionTimeoutFactor(100));
756 DOMStoreThreePhaseCommitCohort writeTxCohort = successWriteTx.ready();
758 followerDistributedDataStore = followerTestKit.setupDistributedDataStore(testName,
759 MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
761 leaderTestKit.doCommit(writeTxCohort);
764 @Test(expected=AskTimeoutException.class)
765 public void testTransactionWithShardLeaderNotResponding() throws Throwable {
766 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
768 // Do an initial read to get the primary shard info cached.
770 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
771 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
773 // Shutdown the leader and try to create a new tx.
775 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
777 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
778 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
780 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
782 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
785 followerTestKit.doCommit(rwTx.ready());
786 } catch (ExecutionException e) {
787 assertTrue("Expected ShardLeaderNotRespondingException cause. Actual: " + e.getCause(),
788 e.getCause() instanceof ShardLeaderNotRespondingException);
789 assertNotNull("Expected a nested cause", e.getCause().getCause());
790 throw e.getCause().getCause();
794 @Test(expected=NoShardLeaderException.class)
795 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Throwable {
796 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
798 // Do an initial read to get the primary shard info cached.
800 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
801 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
803 // Shutdown the leader and try to create a new tx.
805 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
807 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
809 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
810 operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
812 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
814 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
817 followerTestKit.doCommit(rwTx.ready());
818 } catch (ExecutionException e) {
824 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
825 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
826 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS);
828 DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder().
829 shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
830 IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System, follower2DatastoreContextBuilder);
831 follower2TestKit.setupDistributedDataStore(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false, CARS);
833 // Do an initial read to get the primary shard info cached.
835 DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
836 readTx.read(CarsModel.BASE_PATH).checkedGet(5, TimeUnit.SECONDS);
838 // Shutdown the leader and try to create a new tx.
840 JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
842 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
843 operationTimeoutInMillis(500).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
845 DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
847 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
849 followerTestKit.doCommit(rwTx.ready());
852 private static void sendDatastoreContextUpdate(DistributedDataStore dataStore, final Builder builder) {
853 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
854 DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
855 Answer<DatastoreContext> answer = new Answer<DatastoreContext>() {
857 public DatastoreContext answer(InvocationOnMock invocation) {
858 return newBuilder.build();
861 Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
862 Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
863 dataStore.onDatastoreContextUpdated(mockContextFactory);