2 * Copyright (c) 2014, 2015 Cisco 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
9 package org.opendaylight.controller.cluster.datastore;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertSame;
15 import static org.junit.Assert.assertTrue;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.Mockito.inOrder;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.reset;
20 import static org.mockito.Mockito.verify;
21 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
22 import akka.actor.ActorRef;
23 import akka.actor.ActorSelection;
24 import akka.actor.Props;
25 import akka.actor.Status.Failure;
26 import akka.dispatch.Dispatchers;
27 import akka.dispatch.OnComplete;
28 import akka.japi.Creator;
29 import akka.pattern.Patterns;
30 import akka.persistence.SaveSnapshotSuccess;
31 import akka.testkit.TestActorRef;
32 import akka.util.Timeout;
33 import com.google.common.base.Function;
34 import com.google.common.util.concurrent.Futures;
35 import com.google.common.util.concurrent.ListenableFuture;
36 import com.google.common.util.concurrent.Uninterruptibles;
37 import java.util.Collections;
38 import java.util.HashSet;
40 import java.util.concurrent.CountDownLatch;
41 import java.util.concurrent.TimeUnit;
42 import java.util.concurrent.atomic.AtomicBoolean;
43 import java.util.concurrent.atomic.AtomicReference;
44 import org.junit.Test;
45 import org.mockito.InOrder;
46 import org.opendaylight.controller.cluster.DataPersistenceProvider;
47 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
48 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
49 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
50 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
51 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
52 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
53 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
54 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
55 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
56 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
57 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
58 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
59 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
61 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
62 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
63 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
64 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
65 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
66 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
67 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
68 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
69 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListenerReply;
70 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
71 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
72 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
73 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
74 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
75 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
76 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
77 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
78 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
79 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
80 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
81 import org.opendaylight.controller.cluster.raft.RaftActorContext;
82 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
83 import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry;
84 import org.opendaylight.controller.cluster.raft.Snapshot;
85 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
86 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
87 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
88 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
89 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
90 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
91 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
92 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
93 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
94 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
95 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
96 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
97 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
98 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
99 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
100 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
101 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
102 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
103 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
104 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
105 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
106 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
107 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
108 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
109 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
110 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
111 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
112 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
113 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
114 import scala.concurrent.Await;
115 import scala.concurrent.Future;
116 import scala.concurrent.duration.FiniteDuration;
118 public class ShardTest extends AbstractShardTest {
119 private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in InMemorySnapshotStore and journal recovery seq number will start from 1";
122 public void testRegisterChangeListener() throws Exception {
123 new ShardTestKit(getSystem()) {{
124 final TestActorRef<Shard> shard = actorFactory.createTestActor(
125 newShardProps(), "testRegisterChangeListener");
127 waitUntilLeader(shard);
129 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
131 final MockDataChangeListener listener = new MockDataChangeListener(1);
132 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
133 "testRegisterChangeListener-DataChangeListener");
135 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
136 dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
138 final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
139 RegisterChangeListenerReply.class);
140 final String replyPath = reply.getListenerRegistrationPath().toString();
141 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
142 "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
144 final YangInstanceIdentifier path = TestModel.TEST_PATH;
145 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
147 listener.waitForChangeEvents(path);
151 @SuppressWarnings("serial")
153 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
154 // This test tests the timing window in which a change listener is registered before the
155 // shard becomes the leader. We verify that the listener is registered and notified of the
156 // existing data when the shard becomes the leader.
157 new ShardTestKit(getSystem()) {{
158 // For this test, we want to send the RegisterChangeListener message after the shard
159 // has recovered from persistence and before it becomes the leader. So we subclass
160 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
161 // we know that the shard has been initialized to a follower and has started the
162 // election process. The following 2 CountDownLatches are used to coordinate the
163 // ElectionTimeout with the sending of the RegisterChangeListener message.
164 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
165 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
166 final Creator<Shard> creator = new Creator<Shard>() {
167 boolean firstElectionTimeout = true;
170 public Shard create() throws Exception {
171 // Use a non persistent provider because this test actually invokes persist on the journal
172 // this will cause all other messages to not be queued properly after that.
173 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
174 // it does do a persist)
175 return new Shard(newShardBuilder()) {
177 public void onReceiveCommand(final Object message) throws Exception {
178 if(message instanceof ElectionTimeout && firstElectionTimeout) {
179 // Got the first ElectionTimeout. We don't forward it to the
180 // base Shard yet until we've sent the RegisterChangeListener
181 // message. So we signal the onFirstElectionTimeout latch to tell
182 // the main thread to send the RegisterChangeListener message and
183 // start a thread to wait on the onChangeListenerRegistered latch,
184 // which the main thread signals after it has sent the message.
185 // After the onChangeListenerRegistered is triggered, we send the
186 // original ElectionTimeout message to proceed with the election.
187 firstElectionTimeout = false;
188 final ActorRef self = getSelf();
192 Uninterruptibles.awaitUninterruptibly(
193 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
194 self.tell(message, self);
198 onFirstElectionTimeout.countDown();
200 super.onReceiveCommand(message);
207 setupInMemorySnapshotStore();
209 final MockDataChangeListener listener = new MockDataChangeListener(1);
210 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
211 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
213 final TestActorRef<Shard> shard = actorFactory.createTestActor(
214 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
215 "testRegisterChangeListenerWhenNotLeaderInitially");
217 final YangInstanceIdentifier path = TestModel.TEST_PATH;
219 // Wait until the shard receives the first ElectionTimeout message.
220 assertEquals("Got first ElectionTimeout", true,
221 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
223 // Now send the RegisterChangeListener and wait for the reply.
224 shard.tell(new RegisterChangeListener(path, dclActor,
225 AsyncDataBroker.DataChangeScope.SUBTREE, false), getRef());
227 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
228 RegisterChangeListenerReply.class);
229 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
231 // Sanity check - verify the shard is not the leader yet.
232 shard.tell(FindLeader.INSTANCE, getRef());
233 final FindLeaderReply findLeadeReply =
234 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
235 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
237 // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
238 // with the election process.
239 onChangeListenerRegistered.countDown();
241 // Wait for the shard to become the leader and notify our listener with the existing
242 // data in the store.
243 listener.waitForChangeEvents(path);
248 public void testRegisterDataTreeChangeListener() throws Exception {
249 new ShardTestKit(getSystem()) {{
250 final TestActorRef<Shard> shard = actorFactory.createTestActor(
251 newShardProps(), "testRegisterDataTreeChangeListener");
253 waitUntilLeader(shard);
255 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
257 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
258 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
259 "testRegisterDataTreeChangeListener-DataTreeChangeListener");
261 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
263 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
264 RegisterDataTreeChangeListenerReply.class);
265 final String replyPath = reply.getListenerRegistrationPath().toString();
266 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
267 "akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
269 final YangInstanceIdentifier path = TestModel.TEST_PATH;
270 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
272 listener.waitForChangeEvents();
276 @SuppressWarnings("serial")
278 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
279 new ShardTestKit(getSystem()) {{
280 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
281 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
282 final Creator<Shard> creator = new Creator<Shard>() {
283 boolean firstElectionTimeout = true;
286 public Shard create() throws Exception {
287 return new Shard(newShardBuilder()) {
289 public void onReceiveCommand(final Object message) throws Exception {
290 if(message instanceof ElectionTimeout && firstElectionTimeout) {
291 firstElectionTimeout = false;
292 final ActorRef self = getSelf();
296 Uninterruptibles.awaitUninterruptibly(
297 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
298 self.tell(message, self);
302 onFirstElectionTimeout.countDown();
304 super.onReceiveCommand(message);
311 setupInMemorySnapshotStore();
313 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
314 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
315 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
317 final TestActorRef<Shard> shard = actorFactory.createTestActor(
318 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
319 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
321 final YangInstanceIdentifier path = TestModel.TEST_PATH;
323 assertEquals("Got first ElectionTimeout", true,
324 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
326 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
327 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
328 RegisterDataTreeChangeListenerReply.class);
329 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
331 shard.tell(FindLeader.INSTANCE, getRef());
332 final FindLeaderReply findLeadeReply =
333 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
334 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
337 onChangeListenerRegistered.countDown();
339 // TODO: investigate why we do not receive data chage events
340 listener.waitForChangeEvents();
345 public void testCreateTransaction(){
346 new ShardTestKit(getSystem()) {{
347 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
349 waitUntilLeader(shard);
351 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
353 shard.tell(new CreateTransaction("txn-1", TransactionType.READ_ONLY.ordinal(), null,
354 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
356 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
357 CreateTransactionReply.class);
359 final String path = reply.getTransactionPath().toString();
360 assertTrue("Unexpected transaction path " + path,
361 path.contains("akka://test/user/testCreateTransaction/shard-txn-1"));
366 public void testCreateTransactionOnChain(){
367 new ShardTestKit(getSystem()) {{
368 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
370 waitUntilLeader(shard);
372 shard.tell(new CreateTransaction("txn-1",TransactionType.READ_ONLY.ordinal(), "foobar",
373 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
375 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
376 CreateTransactionReply.class);
378 final String path = reply.getTransactionPath().toString();
379 assertTrue("Unexpected transaction path " + path,
380 path.contains("akka://test/user/testCreateTransactionOnChain/shard-txn-1"));
384 @SuppressWarnings("serial")
386 public void testPeerAddressResolved() throws Exception {
387 new ShardTestKit(getSystem()) {{
388 final CountDownLatch recoveryComplete = new CountDownLatch(1);
389 class TestShard extends Shard {
391 super(Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).
392 peerAddresses(Collections.<String, String>singletonMap(shardID.toString(), null)).
393 schemaContext(SCHEMA_CONTEXT));
396 String getPeerAddress(String id) {
397 return getRaftActorContext().getPeerAddress(id);
401 protected void onRecoveryComplete() {
403 super.onRecoveryComplete();
405 recoveryComplete.countDown();
410 final TestActorRef<Shard> shard = actorFactory.createTestActor(
411 Props.create(new DelegatingShardCreator(new Creator<Shard>() {
413 public TestShard create() throws Exception {
414 return new TestShard();
416 })), "testPeerAddressResolved");
418 assertEquals("Recovery complete", true,
419 Uninterruptibles.awaitUninterruptibly(recoveryComplete, 5, TimeUnit.SECONDS));
421 final String address = "akka://foobar";
422 shard.underlyingActor().onReceiveCommand(new PeerAddressResolved(shardID.toString(), address));
424 assertEquals("getPeerAddress", address,
425 ((TestShard) shard.underlyingActor()).getPeerAddress(shardID.toString()));
430 public void testApplySnapshot() throws Exception {
432 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testApplySnapshot");
434 ShardTestKit.waitUntilLeader(shard);
436 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
437 store.setSchemaContext(SCHEMA_CONTEXT);
439 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
440 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
441 withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
442 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
444 writeToStore(store, TestModel.TEST_PATH, container);
446 final YangInstanceIdentifier root = YangInstanceIdentifier.builder().build();
447 final NormalizedNode<?,?> expected = readStore(store, root);
449 final Snapshot snapshot = Snapshot.create(SerializationUtils.serializeNormalizedNode(expected),
450 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
452 shard.underlyingActor().getRaftActorSnapshotCohort().applySnapshot(snapshot.getState());
454 final NormalizedNode<?,?> actual = readStore(shard, root);
456 assertEquals("Root node", expected, actual);
460 public void testApplyState() throws Exception {
461 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testApplyState");
463 ShardTestKit.waitUntilLeader(shard);
465 final DataTree source = setupInMemorySnapshotStore();
466 final DataTreeModification writeMod = source.takeSnapshot().newModification();
467 ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
468 writeMod.write(TestModel.TEST_PATH, node);
471 final ApplyState applyState = new ApplyState(null, "test", new ReplicatedLogImplEntry(1, 2,
472 payloadForModification(source, writeMod)));
474 shard.underlyingActor().onReceiveCommand(applyState);
476 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
477 assertEquals("Applied state", node, actual);
481 public void testDataTreeCandidateRecovery() throws Exception {
482 // Set up the InMemorySnapshotStore.
483 final DataTree source = setupInMemorySnapshotStore();
485 final DataTreeModification writeMod = source.takeSnapshot().newModification();
486 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
488 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
490 // Set up the InMemoryJournal.
491 InMemoryJournal.addEntry(shardID.toString(), 1, new ReplicatedLogImplEntry(0, 1, payloadForModification(source, writeMod)));
493 final int nListEntries = 16;
494 final Set<Integer> listEntryKeys = new HashSet<>();
496 // Add some ModificationPayload entries
497 for (int i = 1; i <= nListEntries; i++) {
498 listEntryKeys.add(Integer.valueOf(i));
500 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
501 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
503 final DataTreeModification mod = source.takeSnapshot().newModification();
504 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
506 InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
507 payloadForModification(source, mod)));
510 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
511 new ApplyJournalEntries(nListEntries));
513 testRecovery(listEntryKeys);
517 public void testConcurrentThreePhaseCommits() throws Throwable {
518 new ShardTestKit(getSystem()) {{
519 final TestActorRef<Shard> shard = actorFactory.createTestActor(
520 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
521 "testConcurrentThreePhaseCommits");
523 waitUntilLeader(shard);
525 // Setup 3 simulated transactions with mock cohorts backed by real cohorts.
527 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
529 final String transactionID1 = "tx1";
530 final MutableCompositeModification modification1 = new MutableCompositeModification();
531 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
532 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
534 final String transactionID2 = "tx2";
535 final MutableCompositeModification modification2 = new MutableCompositeModification();
536 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
537 TestModel.OUTER_LIST_PATH,
538 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
541 final String transactionID3 = "tx3";
542 final MutableCompositeModification modification3 = new MutableCompositeModification();
543 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
544 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
545 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
546 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
549 final long timeoutSec = 5;
550 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
551 final Timeout timeout = new Timeout(duration);
553 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
554 final ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
555 expectMsgClass(duration, ReadyTransactionReply.class));
556 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
558 // Send the CanCommitTransaction message for the first Tx.
560 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
561 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
562 expectMsgClass(duration, CanCommitTransactionReply.class));
563 assertEquals("Can commit", true, canCommitReply.getCanCommit());
565 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
566 expectMsgClass(duration, ReadyTransactionReply.class);
568 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
569 expectMsgClass(duration, ReadyTransactionReply.class);
571 // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
572 // processed after the first Tx completes.
574 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
575 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
577 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
578 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
580 // Send the CommitTransaction message for the first Tx. After it completes, it should
581 // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
583 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
584 expectMsgClass(duration, CommitTransactionReply.class);
586 // Wait for the next 2 Tx's to complete.
588 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
589 final CountDownLatch commitLatch = new CountDownLatch(2);
591 class OnFutureComplete extends OnComplete<Object> {
592 private final Class<?> expRespType;
594 OnFutureComplete(final Class<?> expRespType) {
595 this.expRespType = expRespType;
599 public void onComplete(final Throwable error, final Object resp) {
601 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
604 assertEquals("Commit response type", expRespType, resp.getClass());
606 } catch (final Exception e) {
612 void onSuccess(final Object resp) throws Exception {
616 class OnCommitFutureComplete extends OnFutureComplete {
617 OnCommitFutureComplete() {
618 super(CommitTransactionReply.class);
622 public void onComplete(final Throwable error, final Object resp) {
623 super.onComplete(error, resp);
624 commitLatch.countDown();
628 class OnCanCommitFutureComplete extends OnFutureComplete {
629 private final String transactionID;
631 OnCanCommitFutureComplete(final String transactionID) {
632 super(CanCommitTransactionReply.class);
633 this.transactionID = transactionID;
637 void onSuccess(final Object resp) throws Exception {
638 final CanCommitTransactionReply canCommitReply =
639 CanCommitTransactionReply.fromSerializable(resp);
640 assertEquals("Can commit", true, canCommitReply.getCanCommit());
642 final Future<Object> commitFuture = Patterns.ask(shard,
643 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
644 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
648 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
649 getSystem().dispatcher());
651 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
652 getSystem().dispatcher());
654 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
656 if(caughtEx.get() != null) {
657 throw caughtEx.get();
660 assertEquals("Commits complete", true, done);
662 final InOrder inOrder = inOrder(cohort1, cohort2, cohort3);
663 inOrder.verify(cohort1).canCommit();
664 inOrder.verify(cohort1).preCommit();
665 inOrder.verify(cohort1).commit();
666 inOrder.verify(cohort2).canCommit();
667 inOrder.verify(cohort2).preCommit();
668 inOrder.verify(cohort2).commit();
669 inOrder.verify(cohort3).canCommit();
670 inOrder.verify(cohort3).preCommit();
671 inOrder.verify(cohort3).commit();
673 // Verify data in the data store.
675 verifyOuterListEntry(shard, 1);
677 verifyLastApplied(shard, 2);
682 public void testBatchedModificationsWithNoCommitOnReady() throws Throwable {
683 new ShardTestKit(getSystem()) {{
684 final TestActorRef<Shard> shard = actorFactory.createTestActor(
685 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
686 "testBatchedModificationsWithNoCommitOnReady");
688 waitUntilLeader(shard);
690 final String transactionID = "tx";
691 final FiniteDuration duration = duration("5 seconds");
693 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
694 final ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
696 public ShardDataTreeCohort decorate(final String txID, final ShardDataTreeCohort actual) {
697 if(mockCohort.get() == null) {
698 mockCohort.set(createDelegatingMockCohort("cohort", actual));
701 return mockCohort.get();
705 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
707 // Send a BatchedModifications to start a transaction.
709 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
710 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
711 expectMsgClass(duration, BatchedModificationsReply.class);
713 // Send a couple more BatchedModifications.
715 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
716 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
717 expectMsgClass(duration, BatchedModificationsReply.class);
719 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
720 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
721 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3), getRef());
722 expectMsgClass(duration, ReadyTransactionReply.class);
724 // Send the CanCommitTransaction message.
726 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
727 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
728 expectMsgClass(duration, CanCommitTransactionReply.class));
729 assertEquals("Can commit", true, canCommitReply.getCanCommit());
731 // Send the CanCommitTransaction message.
733 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
734 expectMsgClass(duration, CommitTransactionReply.class);
736 final InOrder inOrder = inOrder(mockCohort.get());
737 inOrder.verify(mockCohort.get()).canCommit();
738 inOrder.verify(mockCohort.get()).preCommit();
739 inOrder.verify(mockCohort.get()).commit();
741 // Verify data in the data store.
743 verifyOuterListEntry(shard, 1);
748 public void testBatchedModificationsWithCommitOnReady() throws Throwable {
749 new ShardTestKit(getSystem()) {{
750 final TestActorRef<Shard> shard = actorFactory.createTestActor(
751 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
752 "testBatchedModificationsWithCommitOnReady");
754 waitUntilLeader(shard);
756 final String transactionID = "tx";
757 final FiniteDuration duration = duration("5 seconds");
759 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
760 final ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
762 public ShardDataTreeCohort decorate(final String txID, final ShardDataTreeCohort actual) {
763 if(mockCohort.get() == null) {
764 mockCohort.set(createDelegatingMockCohort("cohort", actual));
767 return mockCohort.get();
771 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
773 // Send a BatchedModifications to start a transaction.
775 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
776 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
777 expectMsgClass(duration, BatchedModificationsReply.class);
779 // Send a couple more BatchedModifications.
781 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
782 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
783 expectMsgClass(duration, BatchedModificationsReply.class);
785 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
786 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
787 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3), getRef());
789 expectMsgClass(duration, CommitTransactionReply.class);
791 final InOrder inOrder = inOrder(mockCohort.get());
792 inOrder.verify(mockCohort.get()).canCommit();
793 inOrder.verify(mockCohort.get()).preCommit();
794 inOrder.verify(mockCohort.get()).commit();
796 // Verify data in the data store.
798 verifyOuterListEntry(shard, 1);
802 @Test(expected=IllegalStateException.class)
803 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Throwable {
804 new ShardTestKit(getSystem()) {{
805 final TestActorRef<Shard> shard = actorFactory.createTestActor(
806 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
807 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
809 waitUntilLeader(shard);
811 final String transactionID = "tx1";
812 final BatchedModifications batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION, null);
813 batched.setReady(true);
814 batched.setTotalMessagesSent(2);
816 shard.tell(batched, getRef());
818 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
820 if(failure != null) {
821 throw failure.cause();
827 public void testBatchedModificationsWithOperationFailure() throws Throwable {
828 new ShardTestKit(getSystem()) {{
829 final TestActorRef<Shard> shard = actorFactory.createTestActor(
830 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
831 "testBatchedModificationsWithOperationFailure");
833 waitUntilLeader(shard);
835 // Test merge with invalid data. An exception should occur when the merge is applied. Note that
836 // write will not validate the children for performance reasons.
838 String transactionID = "tx1";
840 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
841 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
842 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
844 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, null);
845 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
846 shard.tell(batched, getRef());
847 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
849 Throwable cause = failure.cause();
851 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION, null);
852 batched.setReady(true);
853 batched.setTotalMessagesSent(2);
855 shard.tell(batched, getRef());
857 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
858 assertEquals("Failure cause", cause, failure.cause());
863 public void testBatchedModificationsOnTransactionChain() throws Throwable {
864 new ShardTestKit(getSystem()) {{
865 final TestActorRef<Shard> shard = actorFactory.createTestActor(
866 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
867 "testBatchedModificationsOnTransactionChain");
869 waitUntilLeader(shard);
871 final String transactionChainID = "txChain";
872 final String transactionID1 = "tx1";
873 final String transactionID2 = "tx2";
875 final FiniteDuration duration = duration("5 seconds");
877 // Send a BatchedModifications to start a chained write transaction and ready it.
879 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
880 final YangInstanceIdentifier path = TestModel.TEST_PATH;
881 shard.tell(newBatchedModifications(transactionID1, transactionChainID, path,
882 containerNode, true, false, 1), getRef());
883 expectMsgClass(duration, ReadyTransactionReply.class);
885 // Create a read Tx on the same chain.
887 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
888 transactionChainID, DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
890 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
892 getSystem().actorSelection(createReply.getTransactionPath()).tell(
893 new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
894 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
895 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
897 // Commit the write transaction.
899 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
900 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
901 expectMsgClass(duration, CanCommitTransactionReply.class));
902 assertEquals("Can commit", true, canCommitReply.getCanCommit());
904 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
905 expectMsgClass(duration, CommitTransactionReply.class);
907 // Verify data in the data store.
909 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
910 assertEquals("Stored node", containerNode, actualNode);
915 public void testOnBatchedModificationsWhenNotLeader() {
916 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
917 new ShardTestKit(getSystem()) {{
918 final Creator<Shard> creator = new Creator<Shard>() {
919 private static final long serialVersionUID = 1L;
922 public Shard create() throws Exception {
923 return new Shard(newShardBuilder()) {
925 protected boolean isLeader() {
926 return overrideLeaderCalls.get() ? false : super.isLeader();
930 protected ActorSelection getLeader() {
931 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
938 final TestActorRef<Shard> shard = actorFactory.createTestActor(
939 Props.create(new DelegatingShardCreator(creator)), "testOnBatchedModificationsWhenNotLeader");
941 waitUntilLeader(shard);
943 overrideLeaderCalls.set(true);
945 final BatchedModifications batched = new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, "");
947 shard.tell(batched, ActorRef.noSender());
949 expectMsgEquals(batched);
954 public void testTransactionMessagesWithNoLeader() {
955 new ShardTestKit(getSystem()) {{
956 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
957 shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
958 final TestActorRef<Shard> shard = actorFactory.createTestActor(
959 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
960 "testTransactionMessagesWithNoLeader");
962 waitUntilNoLeader(shard);
964 shard.tell(new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, ""), getRef());
965 Failure failure = expectMsgClass(Failure.class);
966 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
968 shard.tell(prepareForwardedReadyTransaction(mock(ShardDataTreeCohort.class), "tx",
969 DataStoreVersions.CURRENT_VERSION, true), getRef());
970 failure = expectMsgClass(Failure.class);
971 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
973 shard.tell(new ReadyLocalTransaction("tx", mock(DataTreeModification.class), true), getRef());
974 failure = expectMsgClass(Failure.class);
975 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
980 public void testReadyWithImmediateCommit() throws Exception{
981 testReadyWithImmediateCommit(true);
982 testReadyWithImmediateCommit(false);
985 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception{
986 new ShardTestKit(getSystem()) {{
987 final TestActorRef<Shard> shard = actorFactory.createTestActor(
988 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
989 "testReadyWithImmediateCommit-" + readWrite);
991 waitUntilLeader(shard);
993 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
995 final String transactionID = "tx1";
996 final MutableCompositeModification modification = new MutableCompositeModification();
997 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
998 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
999 TestModel.TEST_PATH, containerNode, modification);
1001 final FiniteDuration duration = duration("5 seconds");
1003 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
1005 expectMsgClass(duration, CommitTransactionReply.class);
1007 final InOrder inOrder = inOrder(cohort);
1008 inOrder.verify(cohort).canCommit();
1009 inOrder.verify(cohort).preCommit();
1010 inOrder.verify(cohort).commit();
1012 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1013 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1018 public void testReadyLocalTransactionWithImmediateCommit() throws Exception{
1019 new ShardTestKit(getSystem()) {{
1020 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1021 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1022 "testReadyLocalTransactionWithImmediateCommit");
1024 waitUntilLeader(shard);
1026 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1028 final DataTreeModification modification = dataStore.newModification();
1030 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1031 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1032 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1033 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1035 final String txId = "tx1";
1036 modification.ready();
1037 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1039 shard.tell(readyMessage, getRef());
1041 expectMsgClass(CommitTransactionReply.class);
1043 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1044 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1049 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception{
1050 new ShardTestKit(getSystem()) {{
1051 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1052 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1053 "testReadyLocalTransactionWithThreePhaseCommit");
1055 waitUntilLeader(shard);
1057 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1059 final DataTreeModification modification = dataStore.newModification();
1061 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1062 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1063 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1064 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1066 final String txId = "tx1";
1067 modification.ready();
1068 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1070 shard.tell(readyMessage, getRef());
1072 expectMsgClass(ReadyTransactionReply.class);
1074 // Send the CanCommitTransaction message.
1076 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1077 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1078 expectMsgClass(CanCommitTransactionReply.class));
1079 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1081 // Send the CanCommitTransaction message.
1083 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1084 expectMsgClass(CommitTransactionReply.class);
1086 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1087 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1092 public void testCommitWithPersistenceDisabled() throws Throwable {
1093 testCommitWithPersistenceDisabled(true);
1094 testCommitWithPersistenceDisabled(false);
1097 private void testCommitWithPersistenceDisabled(final boolean readWrite) throws Throwable {
1098 dataStoreContextBuilder.persistent(false);
1099 new ShardTestKit(getSystem()) {{
1100 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1101 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1102 "testCommitWithPersistenceDisabled-" + readWrite);
1104 waitUntilLeader(shard);
1106 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1108 // Setup a simulated transactions with a mock cohort.
1110 final String transactionID = "tx";
1111 final MutableCompositeModification modification = new MutableCompositeModification();
1112 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1113 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
1114 TestModel.TEST_PATH, containerNode, modification);
1116 final FiniteDuration duration = duration("5 seconds");
1118 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1119 expectMsgClass(duration, ReadyTransactionReply.class);
1121 // Send the CanCommitTransaction message.
1123 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1124 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1125 expectMsgClass(duration, CanCommitTransactionReply.class));
1126 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1128 // Send the CanCommitTransaction message.
1130 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1131 expectMsgClass(duration, CommitTransactionReply.class);
1133 final InOrder inOrder = inOrder(cohort);
1134 inOrder.verify(cohort).canCommit();
1135 inOrder.verify(cohort).preCommit();
1136 inOrder.verify(cohort).commit();
1138 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1139 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1144 public void testCommitWhenTransactionHasNoModifications() {
1145 testCommitWhenTransactionHasNoModifications(true);
1146 testCommitWhenTransactionHasNoModifications(false);
1149 private void testCommitWhenTransactionHasNoModifications(final boolean readWrite){
1150 // Note that persistence is enabled which would normally result in the entry getting written to the journal
1151 // but here that need not happen
1152 new ShardTestKit(getSystem()) {
1154 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1155 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1156 "testCommitWhenTransactionHasNoModifications-" + readWrite);
1158 waitUntilLeader(shard);
1160 final String transactionID = "tx1";
1161 final MutableCompositeModification modification = new MutableCompositeModification();
1162 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1163 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1164 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1165 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1166 doReturn(mockUnmodifiedCandidate("cohort1-candidate")).when(cohort).getCandidate();
1168 final FiniteDuration duration = duration("5 seconds");
1170 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1171 expectMsgClass(duration, ReadyTransactionReply.class);
1173 // Send the CanCommitTransaction message.
1175 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1176 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1177 expectMsgClass(duration, CanCommitTransactionReply.class));
1178 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1180 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1181 expectMsgClass(duration, CommitTransactionReply.class);
1183 final InOrder inOrder = inOrder(cohort);
1184 inOrder.verify(cohort).canCommit();
1185 inOrder.verify(cohort).preCommit();
1186 inOrder.verify(cohort).commit();
1188 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1189 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1191 // Use MBean for verification
1192 // Committed transaction count should increase as usual
1193 assertEquals(1,shardStats.getCommittedTransactionsCount());
1195 // Commit index should not advance because this does not go into the journal
1196 assertEquals(-1, shardStats.getCommitIndex());
1202 public void testCommitWhenTransactionHasModifications() {
1203 testCommitWhenTransactionHasModifications(true);
1204 testCommitWhenTransactionHasModifications(false);
1207 private void testCommitWhenTransactionHasModifications(final boolean readWrite){
1208 new ShardTestKit(getSystem()) {
1210 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1211 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1212 "testCommitWhenTransactionHasModifications-" + readWrite);
1214 waitUntilLeader(shard);
1216 final String transactionID = "tx1";
1217 final MutableCompositeModification modification = new MutableCompositeModification();
1218 modification.addModification(new DeleteModification(YangInstanceIdentifier.builder().build()));
1219 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1220 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1221 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1222 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1223 doReturn(mockCandidate("cohort1-candidate")).when(cohort).getCandidate();
1225 final FiniteDuration duration = duration("5 seconds");
1227 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1228 expectMsgClass(duration, ReadyTransactionReply.class);
1230 // Send the CanCommitTransaction message.
1232 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1233 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1234 expectMsgClass(duration, CanCommitTransactionReply.class));
1235 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1237 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1238 expectMsgClass(duration, CommitTransactionReply.class);
1240 final InOrder inOrder = inOrder(cohort);
1241 inOrder.verify(cohort).canCommit();
1242 inOrder.verify(cohort).preCommit();
1243 inOrder.verify(cohort).commit();
1245 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1246 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1248 // Use MBean for verification
1249 // Committed transaction count should increase as usual
1250 assertEquals(1, shardStats.getCommittedTransactionsCount());
1252 // Commit index should advance as we do not have an empty modification
1253 assertEquals(0, shardStats.getCommitIndex());
1259 public void testCommitPhaseFailure() throws Throwable {
1260 testCommitPhaseFailure(true);
1261 testCommitPhaseFailure(false);
1264 private void testCommitPhaseFailure(final boolean readWrite) throws Throwable {
1265 new ShardTestKit(getSystem()) {{
1266 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1267 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1268 "testCommitPhaseFailure-" + readWrite);
1270 waitUntilLeader(shard);
1272 // Setup 2 simulated transactions with mock cohorts. The first one fails in the
1275 final String transactionID1 = "tx1";
1276 final MutableCompositeModification modification1 = new MutableCompositeModification();
1277 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1278 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1279 doReturn(Futures.immediateFuture(null)).when(cohort1).preCommit();
1280 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).commit();
1281 doReturn(mockCandidate("cohort1-candidate")).when(cohort1).getCandidate();
1283 final String transactionID2 = "tx2";
1284 final MutableCompositeModification modification2 = new MutableCompositeModification();
1285 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1286 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1288 final FiniteDuration duration = duration("5 seconds");
1289 final Timeout timeout = new Timeout(duration);
1291 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1292 expectMsgClass(duration, ReadyTransactionReply.class);
1294 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1295 expectMsgClass(duration, ReadyTransactionReply.class);
1297 // Send the CanCommitTransaction message for the first Tx.
1299 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1300 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1301 expectMsgClass(duration, CanCommitTransactionReply.class));
1302 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1304 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1305 // processed after the first Tx completes.
1307 final Future<Object> canCommitFuture = Patterns.ask(shard,
1308 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1310 // Send the CommitTransaction message for the first Tx. This should send back an error
1311 // and trigger the 2nd Tx to proceed.
1313 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1314 expectMsgClass(duration, akka.actor.Status.Failure.class);
1316 // Wait for the 2nd Tx to complete the canCommit phase.
1318 final CountDownLatch latch = new CountDownLatch(1);
1319 canCommitFuture.onComplete(new OnComplete<Object>() {
1321 public void onComplete(final Throwable t, final Object resp) {
1324 }, getSystem().dispatcher());
1326 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1328 final InOrder inOrder = inOrder(cohort1, cohort2);
1329 inOrder.verify(cohort1).canCommit();
1330 inOrder.verify(cohort1).preCommit();
1331 inOrder.verify(cohort1).commit();
1332 inOrder.verify(cohort2).canCommit();
1337 public void testPreCommitPhaseFailure() throws Throwable {
1338 testPreCommitPhaseFailure(true);
1339 testPreCommitPhaseFailure(false);
1342 private void testPreCommitPhaseFailure(final boolean readWrite) throws Throwable {
1343 new ShardTestKit(getSystem()) {{
1344 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1345 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1346 "testPreCommitPhaseFailure-" + readWrite);
1348 waitUntilLeader(shard);
1350 final String transactionID1 = "tx1";
1351 final MutableCompositeModification modification1 = new MutableCompositeModification();
1352 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1353 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1354 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).preCommit();
1356 final String transactionID2 = "tx2";
1357 final MutableCompositeModification modification2 = new MutableCompositeModification();
1358 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1359 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1361 final FiniteDuration duration = duration("5 seconds");
1362 final Timeout timeout = new Timeout(duration);
1364 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1365 expectMsgClass(duration, ReadyTransactionReply.class);
1367 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1368 expectMsgClass(duration, ReadyTransactionReply.class);
1370 // Send the CanCommitTransaction message for the first Tx.
1372 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1373 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1374 expectMsgClass(duration, CanCommitTransactionReply.class));
1375 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1377 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1378 // processed after the first Tx completes.
1380 final Future<Object> canCommitFuture = Patterns.ask(shard,
1381 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1383 // Send the CommitTransaction message for the first Tx. This should send back an error
1384 // and trigger the 2nd Tx to proceed.
1386 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1387 expectMsgClass(duration, akka.actor.Status.Failure.class);
1389 // Wait for the 2nd Tx to complete the canCommit phase.
1391 final CountDownLatch latch = new CountDownLatch(1);
1392 canCommitFuture.onComplete(new OnComplete<Object>() {
1394 public void onComplete(final Throwable t, final Object resp) {
1397 }, getSystem().dispatcher());
1399 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1401 final InOrder inOrder = inOrder(cohort1, cohort2);
1402 inOrder.verify(cohort1).canCommit();
1403 inOrder.verify(cohort1).preCommit();
1404 inOrder.verify(cohort2).canCommit();
1409 public void testCanCommitPhaseFailure() throws Throwable {
1410 testCanCommitPhaseFailure(true);
1411 testCanCommitPhaseFailure(false);
1414 private void testCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1415 new ShardTestKit(getSystem()) {{
1416 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1417 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1418 "testCanCommitPhaseFailure-" + readWrite);
1420 waitUntilLeader(shard);
1422 final FiniteDuration duration = duration("5 seconds");
1424 final String transactionID1 = "tx1";
1425 final MutableCompositeModification modification = new MutableCompositeModification();
1426 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1427 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1429 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1430 expectMsgClass(duration, ReadyTransactionReply.class);
1432 // Send the CanCommitTransaction message.
1434 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1435 expectMsgClass(duration, akka.actor.Status.Failure.class);
1437 // Send another can commit to ensure the failed one got cleaned up.
1441 final String transactionID2 = "tx2";
1442 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1444 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1445 expectMsgClass(duration, ReadyTransactionReply.class);
1447 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1448 final CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1449 expectMsgClass(CanCommitTransactionReply.class));
1450 assertEquals("getCanCommit", true, reply.getCanCommit());
1455 public void testCanCommitPhaseFalseResponse() throws Throwable {
1456 testCanCommitPhaseFalseResponse(true);
1457 testCanCommitPhaseFalseResponse(false);
1460 private void testCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1461 new ShardTestKit(getSystem()) {{
1462 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1463 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1464 "testCanCommitPhaseFalseResponse-" + readWrite);
1466 waitUntilLeader(shard);
1468 final FiniteDuration duration = duration("5 seconds");
1470 final String transactionID1 = "tx1";
1471 final MutableCompositeModification modification = new MutableCompositeModification();
1472 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1473 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1475 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1476 expectMsgClass(duration, ReadyTransactionReply.class);
1478 // Send the CanCommitTransaction message.
1480 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1481 CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1482 expectMsgClass(CanCommitTransactionReply.class));
1483 assertEquals("getCanCommit", false, reply.getCanCommit());
1485 // Send another can commit to ensure the failed one got cleaned up.
1489 final String transactionID2 = "tx2";
1490 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1492 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1493 expectMsgClass(duration, ReadyTransactionReply.class);
1495 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1496 reply = CanCommitTransactionReply.fromSerializable(
1497 expectMsgClass(CanCommitTransactionReply.class));
1498 assertEquals("getCanCommit", true, reply.getCanCommit());
1503 public void testImmediateCommitWithCanCommitPhaseFailure() throws Throwable {
1504 testImmediateCommitWithCanCommitPhaseFailure(true);
1505 testImmediateCommitWithCanCommitPhaseFailure(false);
1508 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1509 new ShardTestKit(getSystem()) {{
1510 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1511 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1512 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1514 waitUntilLeader(shard);
1516 final FiniteDuration duration = duration("5 seconds");
1518 final String transactionID1 = "tx1";
1519 final MutableCompositeModification modification = new MutableCompositeModification();
1520 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1521 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1523 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification, true), getRef());
1525 expectMsgClass(duration, akka.actor.Status.Failure.class);
1527 // Send another can commit to ensure the failed one got cleaned up.
1531 final String transactionID2 = "tx2";
1532 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1533 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1534 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1535 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1536 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1537 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1538 doReturn(candidateRoot).when(candidate).getRootNode();
1539 doReturn(candidate).when(cohort).getCandidate();
1541 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1543 expectMsgClass(duration, CommitTransactionReply.class);
1548 public void testImmediateCommitWithCanCommitPhaseFalseResponse() throws Throwable {
1549 testImmediateCommitWithCanCommitPhaseFalseResponse(true);
1550 testImmediateCommitWithCanCommitPhaseFalseResponse(false);
1553 private void testImmediateCommitWithCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1554 new ShardTestKit(getSystem()) {{
1555 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1556 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1557 "testImmediateCommitWithCanCommitPhaseFalseResponse-" + readWrite);
1559 waitUntilLeader(shard);
1561 final FiniteDuration duration = duration("5 seconds");
1563 final String transactionID = "tx1";
1564 final MutableCompositeModification modification = new MutableCompositeModification();
1565 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1566 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1568 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
1570 expectMsgClass(duration, akka.actor.Status.Failure.class);
1572 // Send another can commit to ensure the failed one got cleaned up.
1576 final String transactionID2 = "tx2";
1577 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1578 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1579 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1580 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1581 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1582 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1583 doReturn(candidateRoot).when(candidate).getRootNode();
1584 doReturn(candidate).when(cohort).getCandidate();
1586 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1588 expectMsgClass(duration, CommitTransactionReply.class);
1593 public void testAbortBeforeFinishCommit() throws Throwable {
1594 testAbortBeforeFinishCommit(true);
1595 testAbortBeforeFinishCommit(false);
1598 private void testAbortBeforeFinishCommit(final boolean readWrite) throws Throwable {
1599 new ShardTestKit(getSystem()) {{
1600 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1601 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1602 "testAbortBeforeFinishCommit-" + readWrite);
1604 waitUntilLeader(shard);
1606 final FiniteDuration duration = duration("5 seconds");
1607 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1609 final String transactionID = "tx1";
1610 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit =
1611 new Function<ShardDataTreeCohort, ListenableFuture<Void>>() {
1613 public ListenableFuture<Void> apply(final ShardDataTreeCohort cohort) {
1614 final ListenableFuture<Void> preCommitFuture = cohort.preCommit();
1616 // Simulate an AbortTransaction message occurring during replication, after
1617 // persisting and before finishing the commit to the in-memory store.
1618 // We have no followers so due to optimizations in the RaftActor, it does not
1619 // attempt replication and thus we can't send an AbortTransaction message b/c
1620 // it would be processed too late after CommitTransaction completes. So we'll
1621 // simulate an AbortTransaction message occurring during replication by calling
1622 // the shard directly.
1624 shard.underlyingActor().doAbortTransaction(transactionID, null);
1626 return preCommitFuture;
1630 final MutableCompositeModification modification = new MutableCompositeModification();
1631 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort1", dataStore,
1632 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME),
1633 modification, preCommit);
1635 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1636 expectMsgClass(duration, ReadyTransactionReply.class);
1638 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1639 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1640 expectMsgClass(duration, CanCommitTransactionReply.class));
1641 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1643 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1644 expectMsgClass(duration, CommitTransactionReply.class);
1646 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1648 // Since we're simulating an abort occurring during replication and before finish commit,
1649 // the data should still get written to the in-memory store since we've gotten past
1650 // canCommit and preCommit and persisted the data.
1651 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1656 public void testTransactionCommitTimeout() throws Throwable {
1657 testTransactionCommitTimeout(true);
1658 testTransactionCommitTimeout(false);
1661 private void testTransactionCommitTimeout(final boolean readWrite) throws Throwable {
1662 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1664 new ShardTestKit(getSystem()) {{
1665 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1666 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1667 "testTransactionCommitTimeout-" + readWrite);
1669 waitUntilLeader(shard);
1671 final FiniteDuration duration = duration("5 seconds");
1673 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1675 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1676 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1677 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1679 // Create 1st Tx - will timeout
1681 final String transactionID1 = "tx1";
1682 final MutableCompositeModification modification1 = new MutableCompositeModification();
1683 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1684 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1685 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1686 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
1691 final String transactionID2 = "tx3";
1692 final MutableCompositeModification modification2 = new MutableCompositeModification();
1693 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1694 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1695 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort3", dataStore,
1697 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2),
1702 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1703 expectMsgClass(duration, ReadyTransactionReply.class);
1705 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1706 expectMsgClass(duration, ReadyTransactionReply.class);
1708 // canCommit 1st Tx. We don't send the commit so it should timeout.
1710 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1711 expectMsgClass(duration, CanCommitTransactionReply.class);
1713 // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1715 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1716 expectMsgClass(duration, CanCommitTransactionReply.class);
1718 // Try to commit the 1st Tx - should fail as it's not the current Tx.
1720 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1721 expectMsgClass(duration, akka.actor.Status.Failure.class);
1723 // Commit the 2nd Tx.
1725 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1726 expectMsgClass(duration, CommitTransactionReply.class);
1728 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1729 assertNotNull(listNodePath + " not found", node);
1734 public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1735 dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1737 new ShardTestKit(getSystem()) {{
1738 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1739 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1740 "testTransactionCommitQueueCapacityExceeded");
1742 waitUntilLeader(shard);
1744 final FiniteDuration duration = duration("5 seconds");
1746 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1748 final String transactionID1 = "tx1";
1749 final MutableCompositeModification modification1 = new MutableCompositeModification();
1750 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1751 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1753 final String transactionID2 = "tx2";
1754 final MutableCompositeModification modification2 = new MutableCompositeModification();
1755 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1756 TestModel.OUTER_LIST_PATH,
1757 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
1760 final String transactionID3 = "tx3";
1761 final MutableCompositeModification modification3 = new MutableCompositeModification();
1762 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1763 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification3);
1767 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1768 expectMsgClass(duration, ReadyTransactionReply.class);
1770 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1771 expectMsgClass(duration, ReadyTransactionReply.class);
1773 // The 3rd Tx should exceed queue capacity and fail.
1775 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1776 expectMsgClass(duration, akka.actor.Status.Failure.class);
1778 // canCommit 1st Tx.
1780 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1781 expectMsgClass(duration, CanCommitTransactionReply.class);
1783 // canCommit the 2nd Tx - it should get queued.
1785 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1787 // canCommit the 3rd Tx - should exceed queue capacity and fail.
1789 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1790 expectMsgClass(duration, akka.actor.Status.Failure.class);
1795 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Throwable {
1796 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1798 new ShardTestKit(getSystem()) {{
1799 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1800 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1801 "testTransactionCommitWithPriorExpiredCohortEntries");
1803 waitUntilLeader(shard);
1805 final FiniteDuration duration = duration("5 seconds");
1807 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1809 final String transactionID1 = "tx1";
1810 final MutableCompositeModification modification1 = new MutableCompositeModification();
1811 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1812 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1814 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1815 expectMsgClass(duration, ReadyTransactionReply.class);
1817 final String transactionID2 = "tx2";
1818 final MutableCompositeModification modification2 = new MutableCompositeModification();
1819 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1820 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1822 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1823 expectMsgClass(duration, ReadyTransactionReply.class);
1825 final String transactionID3 = "tx3";
1826 final MutableCompositeModification modification3 = new MutableCompositeModification();
1827 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1828 TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME), modification3);
1830 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1831 expectMsgClass(duration, ReadyTransactionReply.class);
1833 // All Tx's are readied. We'll send canCommit for the last one but not the others. The others
1834 // should expire from the queue and the last one should be processed.
1836 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1837 expectMsgClass(duration, CanCommitTransactionReply.class);
1842 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Throwable {
1843 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1845 new ShardTestKit(getSystem()) {{
1846 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1847 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1848 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1850 waitUntilLeader(shard);
1852 final FiniteDuration duration = duration("5 seconds");
1854 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1856 final String transactionID1 = "tx1";
1857 final MutableCompositeModification modification1 = new MutableCompositeModification();
1858 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1859 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1861 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1862 expectMsgClass(duration, ReadyTransactionReply.class);
1864 // CanCommit the first one so it's the current in-progress CohortEntry.
1866 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1867 expectMsgClass(duration, CanCommitTransactionReply.class);
1869 // Ready the second Tx.
1871 final String transactionID2 = "tx2";
1872 final MutableCompositeModification modification2 = new MutableCompositeModification();
1873 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1874 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1876 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1877 expectMsgClass(duration, ReadyTransactionReply.class);
1879 // Ready the third Tx.
1881 final String transactionID3 = "tx3";
1882 final DataTreeModification modification3 = dataStore.newModification();
1883 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1884 .apply(modification3);
1885 modification3.ready();
1886 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3, true);
1888 shard.tell(readyMessage, getRef());
1890 // Commit the first Tx. After completing, the second should expire from the queue and the third
1893 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1894 expectMsgClass(duration, CommitTransactionReply.class);
1896 // Expect commit reply from the third Tx.
1898 expectMsgClass(duration, CommitTransactionReply.class);
1900 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1901 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1906 public void testCanCommitBeforeReadyFailure() throws Throwable {
1907 new ShardTestKit(getSystem()) {{
1908 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1909 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1910 "testCanCommitBeforeReadyFailure");
1912 shard.tell(new CanCommitTransaction("tx", CURRENT_VERSION).toSerializable(), getRef());
1913 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1918 public void testAbortCurrentTransaction() throws Throwable {
1919 testAbortCurrentTransaction(true);
1920 testAbortCurrentTransaction(false);
1923 private void testAbortCurrentTransaction(final boolean readWrite) throws Throwable {
1924 new ShardTestKit(getSystem()) {{
1925 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1926 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1927 "testAbortCurrentTransaction-" + readWrite);
1929 waitUntilLeader(shard);
1931 // Setup 2 simulated transactions with mock cohorts. The first one will be aborted.
1933 final String transactionID1 = "tx1";
1934 final MutableCompositeModification modification1 = new MutableCompositeModification();
1935 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1936 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1937 doReturn(Futures.immediateFuture(null)).when(cohort1).abort();
1939 final String transactionID2 = "tx2";
1940 final MutableCompositeModification modification2 = new MutableCompositeModification();
1941 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1942 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1944 final FiniteDuration duration = duration("5 seconds");
1945 final Timeout timeout = new Timeout(duration);
1947 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1948 expectMsgClass(duration, ReadyTransactionReply.class);
1950 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1951 expectMsgClass(duration, ReadyTransactionReply.class);
1953 // Send the CanCommitTransaction message for the first Tx.
1955 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1956 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1957 expectMsgClass(duration, CanCommitTransactionReply.class));
1958 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1960 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1961 // processed after the first Tx completes.
1963 final Future<Object> canCommitFuture = Patterns.ask(shard,
1964 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1966 // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1969 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1970 expectMsgClass(duration, AbortTransactionReply.class);
1972 // Wait for the 2nd Tx to complete the canCommit phase.
1974 Await.ready(canCommitFuture, duration);
1976 final InOrder inOrder = inOrder(cohort1, cohort2);
1977 inOrder.verify(cohort1).canCommit();
1978 inOrder.verify(cohort2).canCommit();
1983 public void testAbortQueuedTransaction() throws Throwable {
1984 testAbortQueuedTransaction(true);
1985 testAbortQueuedTransaction(false);
1988 private void testAbortQueuedTransaction(final boolean readWrite) throws Throwable {
1989 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1990 new ShardTestKit(getSystem()) {{
1991 final AtomicReference<CountDownLatch> cleaupCheckLatch = new AtomicReference<>();
1992 @SuppressWarnings("serial")
1993 final Creator<Shard> creator = new Creator<Shard>() {
1995 public Shard create() throws Exception {
1996 return new Shard(newShardBuilder()) {
1998 public void onReceiveCommand(final Object message) throws Exception {
1999 super.onReceiveCommand(message);
2000 if(message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
2001 if(cleaupCheckLatch.get() != null) {
2002 cleaupCheckLatch.get().countDown();
2010 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2011 Props.create(new DelegatingShardCreator(creator)).withDispatcher(
2012 Dispatchers.DefaultDispatcherId()), "testAbortQueuedTransaction-" + readWrite);
2014 waitUntilLeader(shard);
2016 final String transactionID = "tx1";
2018 final MutableCompositeModification modification = new MutableCompositeModification();
2019 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort");
2020 doReturn(Futures.immediateFuture(null)).when(cohort).abort();
2022 final FiniteDuration duration = duration("5 seconds");
2026 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
2027 expectMsgClass(duration, ReadyTransactionReply.class);
2029 assertEquals("getPendingTxCommitQueueSize", 1, shard.underlyingActor().getPendingTxCommitQueueSize());
2031 // Send the AbortTransaction message.
2033 shard.tell(new AbortTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2034 expectMsgClass(duration, AbortTransactionReply.class);
2036 verify(cohort).abort();
2038 // Verify the tx cohort is removed from queue at the cleanup check interval.
2040 cleaupCheckLatch.set(new CountDownLatch(1));
2041 assertEquals("TX_COMMIT_TIMEOUT_CHECK_MESSAGE received", true,
2042 cleaupCheckLatch.get().await(5, TimeUnit.SECONDS));
2044 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
2046 // Now send CanCommitTransaction - should fail.
2048 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2050 Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
2051 assertTrue("Failure type", failure instanceof IllegalStateException);
2056 public void testCreateSnapshot() throws Exception {
2057 testCreateSnapshot(true, "testCreateSnapshot");
2061 public void testCreateSnapshotWithNonPersistentData() throws Exception {
2062 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
2065 @SuppressWarnings("serial")
2066 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
2068 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
2070 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
2071 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
2072 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
2077 public void saveSnapshot(final Object o) {
2078 savedSnapshot.set(o);
2079 super.saveSnapshot(o);
2083 dataStoreContextBuilder.persistent(persistent);
2085 new ShardTestKit(getSystem()) {{
2086 class TestShard extends Shard {
2088 protected TestShard(AbstractBuilder<?, ?> builder) {
2090 setPersistence(new TestPersistentDataProvider(super.persistence()));
2094 public void handleCommand(final Object message) {
2095 super.handleCommand(message);
2097 if (message instanceof SaveSnapshotSuccess || message.equals("commit_snapshot")) {
2098 latch.get().countDown();
2103 public RaftActorContext getRaftActorContext() {
2104 return super.getRaftActorContext();
2108 final Creator<Shard> creator = new Creator<Shard>() {
2110 public Shard create() throws Exception {
2111 return new TestShard(newShardBuilder());
2115 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2116 Props.create(new DelegatingShardCreator(creator)), shardActorName);
2118 waitUntilLeader(shard);
2119 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2121 final NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.builder().build());
2123 // Trigger creation of a snapshot by ensuring
2124 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
2125 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2126 awaitAndValidateSnapshot(expectedRoot);
2128 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2129 awaitAndValidateSnapshot(expectedRoot);
2132 private void awaitAndValidateSnapshot(NormalizedNode<?,?> expectedRoot) throws InterruptedException {
2133 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
2135 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
2136 savedSnapshot.get() instanceof Snapshot);
2138 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
2140 latch.set(new CountDownLatch(1));
2141 savedSnapshot.set(null);
2144 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?,?> expectedRoot) {
2146 final NormalizedNode<?, ?> actual = SerializationUtils.deserializeNormalizedNode(snapshot.getState());
2147 assertEquals("Root node", expectedRoot, actual);
2153 * This test simply verifies that the applySnapShot logic will work
2154 * @throws ReadFailedException
2155 * @throws DataValidationFailedException
2158 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
2159 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
2160 store.setSchemaContext(SCHEMA_CONTEXT);
2162 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
2163 putTransaction.write(TestModel.TEST_PATH,
2164 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2165 commitTransaction(store, putTransaction);
2168 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.builder().build());
2170 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2172 writeTransaction.delete(YangInstanceIdentifier.builder().build());
2173 writeTransaction.write(YangInstanceIdentifier.builder().build(), expected);
2175 commitTransaction(store, writeTransaction);
2177 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.builder().build());
2179 assertEquals(expected, actual);
2183 public void testRecoveryApplicable(){
2185 final DatastoreContext persistentContext = DatastoreContext.newBuilder().
2186 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2188 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext).
2189 schemaContext(SCHEMA_CONTEXT).props();
2191 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
2192 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2194 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext).
2195 schemaContext(SCHEMA_CONTEXT).props();
2197 new ShardTestKit(getSystem()) {{
2198 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2200 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2202 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2204 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2209 public void testOnDatastoreContext() {
2210 new ShardTestKit(getSystem()) {{
2211 dataStoreContextBuilder.persistent(true);
2213 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
2215 assertEquals("isRecoveryApplicable", true,
2216 shard.underlyingActor().persistence().isRecoveryApplicable());
2218 waitUntilLeader(shard);
2220 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2222 assertEquals("isRecoveryApplicable", false,
2223 shard.underlyingActor().persistence().isRecoveryApplicable());
2225 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2227 assertEquals("isRecoveryApplicable", true,
2228 shard.underlyingActor().persistence().isRecoveryApplicable());
2233 public void testRegisterRoleChangeListener() throws Exception {
2234 new ShardTestKit(getSystem()) {
2236 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2237 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2238 "testRegisterRoleChangeListener");
2240 waitUntilLeader(shard);
2242 final TestActorRef<MessageCollectorActor> listener =
2243 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2245 shard.tell(new RegisterRoleChangeListener(), listener);
2247 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2249 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2250 ShardLeaderStateChanged.class);
2251 assertEquals("getLocalShardDataTree present", true,
2252 leaderStateChanged.getLocalShardDataTree().isPresent());
2253 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2254 leaderStateChanged.getLocalShardDataTree().get());
2256 MessageCollectorActor.clearMessages(listener);
2258 // Force a leader change
2260 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2262 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2263 ShardLeaderStateChanged.class);
2264 assertEquals("getLocalShardDataTree present", false,
2265 leaderStateChanged.getLocalShardDataTree().isPresent());
2271 public void testFollowerInitialSyncStatus() throws Exception {
2272 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2273 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2274 "testFollowerInitialSyncStatus");
2276 shard.underlyingActor().onReceiveCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
2278 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2280 shard.underlyingActor().onReceiveCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
2282 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2286 public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
2287 new ShardTestKit(getSystem()) {{
2288 String testName = "testClusteredDataChangeListenerDelayedRegistration";
2289 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2290 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2292 final MockDataChangeListener listener = new MockDataChangeListener(1);
2293 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2294 actorFactory.generateActorId(testName + "-DataChangeListener"));
2296 setupInMemorySnapshotStore();
2298 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2299 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2300 actorFactory.generateActorId(testName + "-shard"));
2302 waitUntilNoLeader(shard);
2304 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2306 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2307 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2308 RegisterChangeListenerReply.class);
2309 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2311 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2312 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2314 listener.waitForChangeEvents();
2319 public void testClusteredDataChangeListenerRegistration() throws Exception {
2320 new ShardTestKit(getSystem()) {{
2321 String testName = "testClusteredDataChangeListenerRegistration";
2322 final ShardIdentifier followerShardID = ShardIdentifier.builder().memberName(
2323 actorFactory.generateActorId(testName + "-follower")).shardName("inventory").type("config").build();
2325 final ShardIdentifier leaderShardID = ShardIdentifier.builder().memberName(
2326 actorFactory.generateActorId(testName + "-leader")).shardName("inventory").type("config").build();
2328 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2329 Shard.builder().id(followerShardID).
2330 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2331 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2332 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2333 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2335 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2336 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2337 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2338 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2339 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2341 leaderShard.tell(ElectionTimeout.INSTANCE, ActorRef.noSender());
2342 String leaderPath = waitUntilLeader(followerShard);
2343 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2345 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2346 final MockDataChangeListener listener = new MockDataChangeListener(1);
2347 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2348 actorFactory.generateActorId(testName + "-DataChangeListener"));
2350 followerShard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2351 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2352 RegisterChangeListenerReply.class);
2353 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2355 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2357 listener.waitForChangeEvents();
2362 public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
2363 new ShardTestKit(getSystem()) {{
2364 String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
2365 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2366 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2368 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2369 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2370 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2372 setupInMemorySnapshotStore();
2374 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2375 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2376 actorFactory.generateActorId(testName + "-shard"));
2378 waitUntilNoLeader(shard);
2380 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2382 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2383 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2384 RegisterDataTreeChangeListenerReply.class);
2385 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2387 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2388 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2390 listener.waitForChangeEvents();
2395 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2396 new ShardTestKit(getSystem()) {{
2397 String testName = "testClusteredDataTreeChangeListenerRegistration";
2398 final ShardIdentifier followerShardID = ShardIdentifier.builder().memberName(
2399 actorFactory.generateActorId(testName + "-follower")).shardName("inventory").type("config").build();
2401 final ShardIdentifier leaderShardID = ShardIdentifier.builder().memberName(
2402 actorFactory.generateActorId(testName + "-leader")).shardName("inventory").type("config").build();
2404 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2405 Shard.builder().id(followerShardID).
2406 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2407 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2408 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2409 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2411 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2412 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2413 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2414 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2415 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2417 leaderShard.tell(ElectionTimeout.INSTANCE, ActorRef.noSender());
2418 String leaderPath = waitUntilLeader(followerShard);
2419 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2421 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2422 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2423 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2424 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2426 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2427 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2428 RegisterDataTreeChangeListenerReply.class);
2429 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2431 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2433 listener.waitForChangeEvents();
2438 public void testServerRemoved() throws Exception {
2439 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2441 final ActorRef shard = parent.underlyingActor().context().actorOf(
2442 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2443 "testServerRemoved");
2445 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2447 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);