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.assertNull;
15 import static org.junit.Assert.assertSame;
16 import static org.junit.Assert.assertTrue;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.inOrder;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.reset;
21 import static org.mockito.Mockito.verify;
22 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
23 import akka.actor.ActorRef;
24 import akka.actor.ActorSelection;
25 import akka.actor.Props;
26 import akka.actor.Status.Failure;
27 import akka.dispatch.Dispatchers;
28 import akka.dispatch.OnComplete;
29 import akka.japi.Creator;
30 import akka.pattern.Patterns;
31 import akka.persistence.SaveSnapshotSuccess;
32 import akka.testkit.TestActorRef;
33 import akka.util.Timeout;
34 import com.google.common.base.Function;
35 import com.google.common.util.concurrent.Futures;
36 import com.google.common.util.concurrent.ListenableFuture;
37 import com.google.common.util.concurrent.Uninterruptibles;
38 import java.util.Collections;
39 import java.util.HashSet;
41 import java.util.concurrent.CountDownLatch;
42 import java.util.concurrent.TimeUnit;
43 import java.util.concurrent.atomic.AtomicBoolean;
44 import java.util.concurrent.atomic.AtomicReference;
45 import org.junit.Test;
46 import org.mockito.InOrder;
47 import org.opendaylight.controller.cluster.DataPersistenceProvider;
48 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
49 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
50 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
51 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
52 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
53 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
54 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
55 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
56 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
57 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
58 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
59 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
60 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
61 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
62 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
63 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
64 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
65 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
67 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
68 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
69 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
70 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListenerReply;
71 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
72 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
73 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
74 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
75 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
76 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
77 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
78 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
79 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
80 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
81 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
82 import org.opendaylight.controller.cluster.raft.RaftActorContext;
83 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
84 import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry;
85 import org.opendaylight.controller.cluster.raft.Snapshot;
86 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
87 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
88 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
89 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
90 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
91 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
92 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
93 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
94 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
95 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
96 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
97 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
98 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
99 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
100 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
101 import org.opendaylight.controller.protobuff.messages.cohort3pc.ThreePhaseCommitCohortMessages;
102 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
103 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
104 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
105 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
106 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
107 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
108 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
109 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
110 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
111 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
112 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
113 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
114 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
115 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
116 import scala.concurrent.Await;
117 import scala.concurrent.Future;
118 import scala.concurrent.duration.FiniteDuration;
120 public class ShardTest extends AbstractShardTest {
121 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";
124 public void testRegisterChangeListener() throws Exception {
125 new ShardTestKit(getSystem()) {{
126 final TestActorRef<Shard> shard = actorFactory.createTestActor(
127 newShardProps(), "testRegisterChangeListener");
129 waitUntilLeader(shard);
131 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
133 final MockDataChangeListener listener = new MockDataChangeListener(1);
134 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
135 "testRegisterChangeListener-DataChangeListener");
137 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
138 dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
140 final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
141 RegisterChangeListenerReply.class);
142 final String replyPath = reply.getListenerRegistrationPath().toString();
143 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
144 "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
146 final YangInstanceIdentifier path = TestModel.TEST_PATH;
147 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
149 listener.waitForChangeEvents(path);
153 @SuppressWarnings("serial")
155 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
156 // This test tests the timing window in which a change listener is registered before the
157 // shard becomes the leader. We verify that the listener is registered and notified of the
158 // existing data when the shard becomes the leader.
159 new ShardTestKit(getSystem()) {{
160 // For this test, we want to send the RegisterChangeListener message after the shard
161 // has recovered from persistence and before it becomes the leader. So we subclass
162 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
163 // we know that the shard has been initialized to a follower and has started the
164 // election process. The following 2 CountDownLatches are used to coordinate the
165 // ElectionTimeout with the sending of the RegisterChangeListener message.
166 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
167 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
168 final Creator<Shard> creator = new Creator<Shard>() {
169 boolean firstElectionTimeout = true;
172 public Shard create() throws Exception {
173 // Use a non persistent provider because this test actually invokes persist on the journal
174 // this will cause all other messages to not be queued properly after that.
175 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
176 // it does do a persist)
177 return new Shard(newShardBuilder()) {
179 public void onReceiveCommand(final Object message) throws Exception {
180 if(message instanceof ElectionTimeout && firstElectionTimeout) {
181 // Got the first ElectionTimeout. We don't forward it to the
182 // base Shard yet until we've sent the RegisterChangeListener
183 // message. So we signal the onFirstElectionTimeout latch to tell
184 // the main thread to send the RegisterChangeListener message and
185 // start a thread to wait on the onChangeListenerRegistered latch,
186 // which the main thread signals after it has sent the message.
187 // After the onChangeListenerRegistered is triggered, we send the
188 // original ElectionTimeout message to proceed with the election.
189 firstElectionTimeout = false;
190 final ActorRef self = getSelf();
194 Uninterruptibles.awaitUninterruptibly(
195 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
196 self.tell(message, self);
200 onFirstElectionTimeout.countDown();
202 super.onReceiveCommand(message);
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 // Write initial data into the in-memory store.
218 final YangInstanceIdentifier path = TestModel.TEST_PATH;
219 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
221 // Wait until the shard receives the first ElectionTimeout message.
222 assertEquals("Got first ElectionTimeout", true,
223 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
225 // Now send the RegisterChangeListener and wait for the reply.
226 shard.tell(new RegisterChangeListener(path, dclActor,
227 AsyncDataBroker.DataChangeScope.SUBTREE, false), getRef());
229 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
230 RegisterChangeListenerReply.class);
231 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
233 // Sanity check - verify the shard is not the leader yet.
234 shard.tell(new FindLeader(), getRef());
235 final FindLeaderReply findLeadeReply =
236 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
237 assertNull("Expected the shard not to be the leader", findLeadeReply.getLeaderActor());
239 // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
240 // with the election process.
241 onChangeListenerRegistered.countDown();
243 // Wait for the shard to become the leader and notify our listener with the existing
244 // data in the store.
245 listener.waitForChangeEvents(path);
250 public void testRegisterDataTreeChangeListener() throws Exception {
251 new ShardTestKit(getSystem()) {{
252 final TestActorRef<Shard> shard = actorFactory.createTestActor(
253 newShardProps(), "testRegisterDataTreeChangeListener");
255 waitUntilLeader(shard);
257 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
259 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
260 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
261 "testRegisterDataTreeChangeListener-DataTreeChangeListener");
263 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
265 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
266 RegisterDataTreeChangeListenerReply.class);
267 final String replyPath = reply.getListenerRegistrationPath().toString();
268 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
269 "akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
271 final YangInstanceIdentifier path = TestModel.TEST_PATH;
272 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
274 listener.waitForChangeEvents();
278 @SuppressWarnings("serial")
280 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
281 new ShardTestKit(getSystem()) {{
282 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
283 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
284 final Creator<Shard> creator = new Creator<Shard>() {
285 boolean firstElectionTimeout = true;
288 public Shard create() throws Exception {
289 return new Shard(Shard.builder().id(shardID).datastoreContext(
290 dataStoreContextBuilder.persistent(false).build()).schemaContext(SCHEMA_CONTEXT)) {
292 public void onReceiveCommand(final Object message) throws Exception {
293 if(message instanceof ElectionTimeout && firstElectionTimeout) {
294 firstElectionTimeout = false;
295 final ActorRef self = getSelf();
299 Uninterruptibles.awaitUninterruptibly(
300 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
301 self.tell(message, self);
305 onFirstElectionTimeout.countDown();
307 super.onReceiveCommand(message);
314 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
315 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
316 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
318 final TestActorRef<Shard> shard = actorFactory.createTestActor(
319 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
320 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
322 final YangInstanceIdentifier path = TestModel.TEST_PATH;
323 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
325 assertEquals("Got first ElectionTimeout", true,
326 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
328 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
329 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
330 RegisterDataTreeChangeListenerReply.class);
331 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
333 shard.tell(new FindLeader(), getRef());
334 final FindLeaderReply findLeadeReply =
335 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
336 assertNull("Expected the shard not to be the leader", findLeadeReply.getLeaderActor());
338 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
340 onChangeListenerRegistered.countDown();
342 // TODO: investigate why we do not receive data chage events
343 listener.waitForChangeEvents();
348 public void testCreateTransaction(){
349 new ShardTestKit(getSystem()) {{
350 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
352 waitUntilLeader(shard);
354 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
356 shard.tell(new CreateTransaction("txn-1", TransactionType.READ_ONLY.ordinal(), null,
357 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
359 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
360 CreateTransactionReply.class);
362 final String path = reply.getTransactionPath().toString();
363 assertTrue("Unexpected transaction path " + path,
364 path.contains("akka://test/user/testCreateTransaction/shard-txn-1"));
369 public void testCreateTransactionOnChain(){
370 new ShardTestKit(getSystem()) {{
371 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
373 waitUntilLeader(shard);
375 shard.tell(new CreateTransaction("txn-1",TransactionType.READ_ONLY.ordinal(), "foobar",
376 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
378 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
379 CreateTransactionReply.class);
381 final String path = reply.getTransactionPath().toString();
382 assertTrue("Unexpected transaction path " + path,
383 path.contains("akka://test/user/testCreateTransactionOnChain/shard-txn-1"));
387 @SuppressWarnings("serial")
389 public void testPeerAddressResolved() throws Exception {
390 new ShardTestKit(getSystem()) {{
391 final CountDownLatch recoveryComplete = new CountDownLatch(1);
392 class TestShard extends Shard {
394 super(Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).
395 peerAddresses(Collections.<String, String>singletonMap(shardID.toString(), null)).
396 schemaContext(SCHEMA_CONTEXT));
399 String getPeerAddress(String id) {
400 return getRaftActorContext().getPeerAddress(id);
404 protected void onRecoveryComplete() {
406 super.onRecoveryComplete();
408 recoveryComplete.countDown();
413 final TestActorRef<Shard> shard = actorFactory.createTestActor(
414 Props.create(new DelegatingShardCreator(new Creator<Shard>() {
416 public TestShard create() throws Exception {
417 return new TestShard();
419 })), "testPeerAddressResolved");
421 assertEquals("Recovery complete", true,
422 Uninterruptibles.awaitUninterruptibly(recoveryComplete, 5, TimeUnit.SECONDS));
424 final String address = "akka://foobar";
425 shard.underlyingActor().onReceiveCommand(new PeerAddressResolved(shardID.toString(), address));
427 assertEquals("getPeerAddress", address,
428 ((TestShard) shard.underlyingActor()).getPeerAddress(shardID.toString()));
433 public void testApplySnapshot() throws Exception {
435 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testApplySnapshot");
437 ShardTestKit.waitUntilLeader(shard);
439 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
440 store.setSchemaContext(SCHEMA_CONTEXT);
442 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
443 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
444 withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
445 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
447 writeToStore(store, TestModel.TEST_PATH, container);
449 final YangInstanceIdentifier root = YangInstanceIdentifier.builder().build();
450 final NormalizedNode<?,?> expected = readStore(store, root);
452 final Snapshot snapshot = Snapshot.create(SerializationUtils.serializeNormalizedNode(expected),
453 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
455 shard.underlyingActor().getRaftActorSnapshotCohort().applySnapshot(snapshot.getState());
457 final NormalizedNode<?,?> actual = readStore(shard, root);
459 assertEquals("Root node", expected, actual);
463 public void testApplyState() throws Exception {
464 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testApplyState");
466 ShardTestKit.waitUntilLeader(shard);
468 final DataTree source = setupInMemorySnapshotStore();
469 final DataTreeModification writeMod = source.takeSnapshot().newModification();
470 ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
471 writeMod.write(TestModel.TEST_PATH, node);
474 final ApplyState applyState = new ApplyState(null, "test", new ReplicatedLogImplEntry(1, 2,
475 payloadForModification(source, writeMod)));
477 shard.underlyingActor().onReceiveCommand(applyState);
479 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
480 assertEquals("Applied state", node, actual);
484 public void testDataTreeCandidateRecovery() throws Exception {
485 // Set up the InMemorySnapshotStore.
486 final DataTree source = setupInMemorySnapshotStore();
488 final DataTreeModification writeMod = source.takeSnapshot().newModification();
489 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
491 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
493 // Set up the InMemoryJournal.
494 InMemoryJournal.addEntry(shardID.toString(), 1, new ReplicatedLogImplEntry(0, 1, payloadForModification(source, writeMod)));
496 final int nListEntries = 16;
497 final Set<Integer> listEntryKeys = new HashSet<>();
499 // Add some ModificationPayload entries
500 for (int i = 1; i <= nListEntries; i++) {
501 listEntryKeys.add(Integer.valueOf(i));
503 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
504 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
506 final DataTreeModification mod = source.takeSnapshot().newModification();
507 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
509 InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
510 payloadForModification(source, mod)));
513 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
514 new ApplyJournalEntries(nListEntries));
516 testRecovery(listEntryKeys);
520 public void testConcurrentThreePhaseCommits() throws Throwable {
521 new ShardTestKit(getSystem()) {{
522 final TestActorRef<Shard> shard = actorFactory.createTestActor(
523 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
524 "testConcurrentThreePhaseCommits");
526 waitUntilLeader(shard);
528 // Setup 3 simulated transactions with mock cohorts backed by real cohorts.
530 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
532 final String transactionID1 = "tx1";
533 final MutableCompositeModification modification1 = new MutableCompositeModification();
534 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
535 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
537 final String transactionID2 = "tx2";
538 final MutableCompositeModification modification2 = new MutableCompositeModification();
539 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
540 TestModel.OUTER_LIST_PATH,
541 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
544 final String transactionID3 = "tx3";
545 final MutableCompositeModification modification3 = new MutableCompositeModification();
546 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
547 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
548 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
549 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
552 final long timeoutSec = 5;
553 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
554 final Timeout timeout = new Timeout(duration);
556 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
557 final ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
558 expectMsgClass(duration, ReadyTransactionReply.class));
559 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
561 // Send the CanCommitTransaction message for the first Tx.
563 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
564 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
565 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
566 assertEquals("Can commit", true, canCommitReply.getCanCommit());
568 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
569 expectMsgClass(duration, ReadyTransactionReply.class);
571 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
572 expectMsgClass(duration, ReadyTransactionReply.class);
574 // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
575 // processed after the first Tx completes.
577 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
578 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
580 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
581 new CanCommitTransaction(transactionID3).toSerializable(), timeout);
583 // Send the CommitTransaction message for the first Tx. After it completes, it should
584 // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
586 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
587 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
589 // Wait for the next 2 Tx's to complete.
591 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
592 final CountDownLatch commitLatch = new CountDownLatch(2);
594 class OnFutureComplete extends OnComplete<Object> {
595 private final Class<?> expRespType;
597 OnFutureComplete(final Class<?> expRespType) {
598 this.expRespType = expRespType;
602 public void onComplete(final Throwable error, final Object resp) {
604 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
607 assertEquals("Commit response type", expRespType, resp.getClass());
609 } catch (final Exception e) {
615 void onSuccess(final Object resp) throws Exception {
619 class OnCommitFutureComplete extends OnFutureComplete {
620 OnCommitFutureComplete() {
621 super(CommitTransactionReply.SERIALIZABLE_CLASS);
625 public void onComplete(final Throwable error, final Object resp) {
626 super.onComplete(error, resp);
627 commitLatch.countDown();
631 class OnCanCommitFutureComplete extends OnFutureComplete {
632 private final String transactionID;
634 OnCanCommitFutureComplete(final String transactionID) {
635 super(CanCommitTransactionReply.SERIALIZABLE_CLASS);
636 this.transactionID = transactionID;
640 void onSuccess(final Object resp) throws Exception {
641 final CanCommitTransactionReply canCommitReply =
642 CanCommitTransactionReply.fromSerializable(resp);
643 assertEquals("Can commit", true, canCommitReply.getCanCommit());
645 final Future<Object> commitFuture = Patterns.ask(shard,
646 new CommitTransaction(transactionID).toSerializable(), timeout);
647 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
651 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
652 getSystem().dispatcher());
654 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
655 getSystem().dispatcher());
657 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
659 if(caughtEx.get() != null) {
660 throw caughtEx.get();
663 assertEquals("Commits complete", true, done);
665 final InOrder inOrder = inOrder(cohort1, cohort2, cohort3);
666 inOrder.verify(cohort1).canCommit();
667 inOrder.verify(cohort1).preCommit();
668 inOrder.verify(cohort1).commit();
669 inOrder.verify(cohort2).canCommit();
670 inOrder.verify(cohort2).preCommit();
671 inOrder.verify(cohort2).commit();
672 inOrder.verify(cohort3).canCommit();
673 inOrder.verify(cohort3).preCommit();
674 inOrder.verify(cohort3).commit();
676 // Verify data in the data store.
678 verifyOuterListEntry(shard, 1);
680 verifyLastApplied(shard, 2);
685 public void testBatchedModificationsWithNoCommitOnReady() throws Throwable {
686 new ShardTestKit(getSystem()) {{
687 final TestActorRef<Shard> shard = actorFactory.createTestActor(
688 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
689 "testBatchedModificationsWithNoCommitOnReady");
691 waitUntilLeader(shard);
693 final String transactionID = "tx";
694 final FiniteDuration duration = duration("5 seconds");
696 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
697 final ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
699 public ShardDataTreeCohort decorate(final String txID, final ShardDataTreeCohort actual) {
700 if(mockCohort.get() == null) {
701 mockCohort.set(createDelegatingMockCohort("cohort", actual));
704 return mockCohort.get();
708 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
710 // Send a BatchedModifications to start a transaction.
712 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
713 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
714 expectMsgClass(duration, BatchedModificationsReply.class);
716 // Send a couple more BatchedModifications.
718 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
719 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
720 expectMsgClass(duration, BatchedModificationsReply.class);
722 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
723 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
724 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3), getRef());
725 expectMsgClass(duration, ReadyTransactionReply.class);
727 // Send the CanCommitTransaction message.
729 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
730 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
731 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
732 assertEquals("Can commit", true, canCommitReply.getCanCommit());
734 // Send the CanCommitTransaction message.
736 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
737 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
739 final InOrder inOrder = inOrder(mockCohort.get());
740 inOrder.verify(mockCohort.get()).canCommit();
741 inOrder.verify(mockCohort.get()).preCommit();
742 inOrder.verify(mockCohort.get()).commit();
744 // Verify data in the data store.
746 verifyOuterListEntry(shard, 1);
751 public void testBatchedModificationsWithCommitOnReady() throws Throwable {
752 new ShardTestKit(getSystem()) {{
753 final TestActorRef<Shard> shard = actorFactory.createTestActor(
754 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
755 "testBatchedModificationsWithCommitOnReady");
757 waitUntilLeader(shard);
759 final String transactionID = "tx";
760 final FiniteDuration duration = duration("5 seconds");
762 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
763 final ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
765 public ShardDataTreeCohort decorate(final String txID, final ShardDataTreeCohort actual) {
766 if(mockCohort.get() == null) {
767 mockCohort.set(createDelegatingMockCohort("cohort", actual));
770 return mockCohort.get();
774 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
776 // Send a BatchedModifications to start a transaction.
778 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
779 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
780 expectMsgClass(duration, BatchedModificationsReply.class);
782 // Send a couple more BatchedModifications.
784 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
785 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
786 expectMsgClass(duration, BatchedModificationsReply.class);
788 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
789 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
790 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3), getRef());
792 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
794 final InOrder inOrder = inOrder(mockCohort.get());
795 inOrder.verify(mockCohort.get()).canCommit();
796 inOrder.verify(mockCohort.get()).preCommit();
797 inOrder.verify(mockCohort.get()).commit();
799 // Verify data in the data store.
801 verifyOuterListEntry(shard, 1);
805 @Test(expected=IllegalStateException.class)
806 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Throwable {
807 new ShardTestKit(getSystem()) {{
808 final TestActorRef<Shard> shard = actorFactory.createTestActor(
809 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
810 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
812 waitUntilLeader(shard);
814 final String transactionID = "tx1";
815 final BatchedModifications batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION, null);
816 batched.setReady(true);
817 batched.setTotalMessagesSent(2);
819 shard.tell(batched, getRef());
821 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
823 if(failure != null) {
824 throw failure.cause();
830 public void testBatchedModificationsWithOperationFailure() throws Throwable {
831 new ShardTestKit(getSystem()) {{
832 final TestActorRef<Shard> shard = actorFactory.createTestActor(
833 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
834 "testBatchedModificationsWithOperationFailure");
836 waitUntilLeader(shard);
838 // Test merge with invalid data. An exception should occur when the merge is applied. Note that
839 // write will not validate the children for performance reasons.
841 String transactionID = "tx1";
843 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
844 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
845 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
847 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, null);
848 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
849 shard.tell(batched, getRef());
850 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
852 Throwable cause = failure.cause();
854 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION, null);
855 batched.setReady(true);
856 batched.setTotalMessagesSent(2);
858 shard.tell(batched, getRef());
860 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
861 assertEquals("Failure cause", cause, failure.cause());
866 public void testBatchedModificationsOnTransactionChain() throws Throwable {
867 new ShardTestKit(getSystem()) {{
868 final TestActorRef<Shard> shard = actorFactory.createTestActor(
869 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
870 "testBatchedModificationsOnTransactionChain");
872 waitUntilLeader(shard);
874 final String transactionChainID = "txChain";
875 final String transactionID1 = "tx1";
876 final String transactionID2 = "tx2";
878 final FiniteDuration duration = duration("5 seconds");
880 // Send a BatchedModifications to start a chained write transaction and ready it.
882 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
883 final YangInstanceIdentifier path = TestModel.TEST_PATH;
884 shard.tell(newBatchedModifications(transactionID1, transactionChainID, path,
885 containerNode, true, false, 1), getRef());
886 expectMsgClass(duration, ReadyTransactionReply.class);
888 // Create a read Tx on the same chain.
890 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
891 transactionChainID, DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
893 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
895 getSystem().actorSelection(createReply.getTransactionPath()).tell(
896 new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
897 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
898 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
900 // Commit the write transaction.
902 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
903 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
904 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
905 assertEquals("Can commit", true, canCommitReply.getCanCommit());
907 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
908 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
910 // Verify data in the data store.
912 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
913 assertEquals("Stored node", containerNode, actualNode);
918 public void testOnBatchedModificationsWhenNotLeader() {
919 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
920 new ShardTestKit(getSystem()) {{
921 final Creator<Shard> creator = new Creator<Shard>() {
922 private static final long serialVersionUID = 1L;
925 public Shard create() throws Exception {
926 return new Shard(newShardBuilder()) {
928 protected boolean isLeader() {
929 return overrideLeaderCalls.get() ? false : super.isLeader();
933 protected ActorSelection getLeader() {
934 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
941 final TestActorRef<Shard> shard = actorFactory.createTestActor(
942 Props.create(new DelegatingShardCreator(creator)), "testOnBatchedModificationsWhenNotLeader");
944 waitUntilLeader(shard);
946 overrideLeaderCalls.set(true);
948 final BatchedModifications batched = new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, "");
950 shard.tell(batched, ActorRef.noSender());
952 expectMsgEquals(batched);
957 public void testTransactionMessagesWithNoLeader() {
958 new ShardTestKit(getSystem()) {{
959 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
960 shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
961 final TestActorRef<Shard> shard = actorFactory.createTestActor(
962 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
963 "testTransactionMessagesWithNoLeader");
965 waitUntilNoLeader(shard);
967 shard.tell(new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, ""), getRef());
968 Failure failure = expectMsgClass(Failure.class);
969 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
971 shard.tell(prepareForwardedReadyTransaction(mock(ShardDataTreeCohort.class), "tx",
972 DataStoreVersions.CURRENT_VERSION, true), getRef());
973 failure = expectMsgClass(Failure.class);
974 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
976 shard.tell(new ReadyLocalTransaction("tx", mock(DataTreeModification.class), true), getRef());
977 failure = expectMsgClass(Failure.class);
978 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
983 public void testReadyWithImmediateCommit() throws Exception{
984 testReadyWithImmediateCommit(true);
985 testReadyWithImmediateCommit(false);
988 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception{
989 new ShardTestKit(getSystem()) {{
990 final TestActorRef<Shard> shard = actorFactory.createTestActor(
991 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
992 "testReadyWithImmediateCommit-" + readWrite);
994 waitUntilLeader(shard);
996 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
998 final String transactionID = "tx1";
999 final MutableCompositeModification modification = new MutableCompositeModification();
1000 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1001 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
1002 TestModel.TEST_PATH, containerNode, modification);
1004 final FiniteDuration duration = duration("5 seconds");
1006 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
1008 expectMsgClass(duration, ThreePhaseCommitCohortMessages.CommitTransactionReply.class);
1010 final InOrder inOrder = inOrder(cohort);
1011 inOrder.verify(cohort).canCommit();
1012 inOrder.verify(cohort).preCommit();
1013 inOrder.verify(cohort).commit();
1015 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1016 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1021 public void testReadyLocalTransactionWithImmediateCommit() throws Exception{
1022 new ShardTestKit(getSystem()) {{
1023 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1024 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1025 "testReadyLocalTransactionWithImmediateCommit");
1027 waitUntilLeader(shard);
1029 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1031 final DataTreeModification modification = dataStore.newModification();
1033 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1034 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1035 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1036 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1038 final String txId = "tx1";
1039 modification.ready();
1040 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1042 shard.tell(readyMessage, getRef());
1044 expectMsgClass(CommitTransactionReply.SERIALIZABLE_CLASS);
1046 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1047 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1052 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception{
1053 new ShardTestKit(getSystem()) {{
1054 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1055 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1056 "testReadyLocalTransactionWithThreePhaseCommit");
1058 waitUntilLeader(shard);
1060 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1062 final DataTreeModification modification = dataStore.newModification();
1064 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1065 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1066 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1067 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1069 final String txId = "tx1";
1070 modification.ready();
1071 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1073 shard.tell(readyMessage, getRef());
1075 expectMsgClass(ReadyTransactionReply.class);
1077 // Send the CanCommitTransaction message.
1079 shard.tell(new CanCommitTransaction(txId).toSerializable(), getRef());
1080 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1081 expectMsgClass(CanCommitTransactionReply.SERIALIZABLE_CLASS));
1082 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1084 // Send the CanCommitTransaction message.
1086 shard.tell(new CommitTransaction(txId).toSerializable(), getRef());
1087 expectMsgClass(CommitTransactionReply.SERIALIZABLE_CLASS);
1089 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1090 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1095 public void testCommitWithPersistenceDisabled() throws Throwable {
1096 testCommitWithPersistenceDisabled(true);
1097 testCommitWithPersistenceDisabled(false);
1100 private void testCommitWithPersistenceDisabled(final boolean readWrite) throws Throwable {
1101 dataStoreContextBuilder.persistent(false);
1102 new ShardTestKit(getSystem()) {{
1103 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1104 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1105 "testCommitWithPersistenceDisabled-" + readWrite);
1107 waitUntilLeader(shard);
1109 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1111 // Setup a simulated transactions with a mock cohort.
1113 final String transactionID = "tx";
1114 final MutableCompositeModification modification = new MutableCompositeModification();
1115 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1116 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
1117 TestModel.TEST_PATH, containerNode, modification);
1119 final FiniteDuration duration = duration("5 seconds");
1121 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1122 expectMsgClass(duration, ReadyTransactionReply.class);
1124 // Send the CanCommitTransaction message.
1126 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1127 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1128 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1129 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1131 // Send the CanCommitTransaction message.
1133 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
1134 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1136 final InOrder inOrder = inOrder(cohort);
1137 inOrder.verify(cohort).canCommit();
1138 inOrder.verify(cohort).preCommit();
1139 inOrder.verify(cohort).commit();
1141 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1142 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1147 public void testCommitWhenTransactionHasNoModifications() {
1148 testCommitWhenTransactionHasNoModifications(true);
1149 testCommitWhenTransactionHasNoModifications(false);
1152 private void testCommitWhenTransactionHasNoModifications(final boolean readWrite){
1153 // Note that persistence is enabled which would normally result in the entry getting written to the journal
1154 // but here that need not happen
1155 new ShardTestKit(getSystem()) {
1157 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1158 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1159 "testCommitWhenTransactionHasNoModifications-" + readWrite);
1161 waitUntilLeader(shard);
1163 final String transactionID = "tx1";
1164 final MutableCompositeModification modification = new MutableCompositeModification();
1165 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1166 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1167 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1168 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1169 doReturn(mockUnmodifiedCandidate("cohort1-candidate")).when(cohort).getCandidate();
1171 final FiniteDuration duration = duration("5 seconds");
1173 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1174 expectMsgClass(duration, ReadyTransactionReply.class);
1176 // Send the CanCommitTransaction message.
1178 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1179 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1180 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1181 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1183 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
1184 expectMsgClass(duration, ThreePhaseCommitCohortMessages.CommitTransactionReply.class);
1186 final InOrder inOrder = inOrder(cohort);
1187 inOrder.verify(cohort).canCommit();
1188 inOrder.verify(cohort).preCommit();
1189 inOrder.verify(cohort).commit();
1191 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1192 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1194 // Use MBean for verification
1195 // Committed transaction count should increase as usual
1196 assertEquals(1,shardStats.getCommittedTransactionsCount());
1198 // Commit index should not advance because this does not go into the journal
1199 assertEquals(-1, shardStats.getCommitIndex());
1205 public void testCommitWhenTransactionHasModifications() {
1206 testCommitWhenTransactionHasModifications(true);
1207 testCommitWhenTransactionHasModifications(false);
1210 private void testCommitWhenTransactionHasModifications(final boolean readWrite){
1211 new ShardTestKit(getSystem()) {
1213 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1214 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1215 "testCommitWhenTransactionHasModifications-" + readWrite);
1217 waitUntilLeader(shard);
1219 final String transactionID = "tx1";
1220 final MutableCompositeModification modification = new MutableCompositeModification();
1221 modification.addModification(new DeleteModification(YangInstanceIdentifier.builder().build()));
1222 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1223 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1224 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1225 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1226 doReturn(mockCandidate("cohort1-candidate")).when(cohort).getCandidate();
1228 final FiniteDuration duration = duration("5 seconds");
1230 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1231 expectMsgClass(duration, ReadyTransactionReply.class);
1233 // Send the CanCommitTransaction message.
1235 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1236 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1237 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1238 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1240 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
1241 expectMsgClass(duration, ThreePhaseCommitCohortMessages.CommitTransactionReply.class);
1243 final InOrder inOrder = inOrder(cohort);
1244 inOrder.verify(cohort).canCommit();
1245 inOrder.verify(cohort).preCommit();
1246 inOrder.verify(cohort).commit();
1248 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1249 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1251 // Use MBean for verification
1252 // Committed transaction count should increase as usual
1253 assertEquals(1, shardStats.getCommittedTransactionsCount());
1255 // Commit index should advance as we do not have an empty modification
1256 assertEquals(0, shardStats.getCommitIndex());
1262 public void testCommitPhaseFailure() throws Throwable {
1263 testCommitPhaseFailure(true);
1264 testCommitPhaseFailure(false);
1267 private void testCommitPhaseFailure(final boolean readWrite) throws Throwable {
1268 new ShardTestKit(getSystem()) {{
1269 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1270 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1271 "testCommitPhaseFailure-" + readWrite);
1273 waitUntilLeader(shard);
1275 // Setup 2 simulated transactions with mock cohorts. The first one fails in the
1278 final String transactionID1 = "tx1";
1279 final MutableCompositeModification modification1 = new MutableCompositeModification();
1280 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1281 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1282 doReturn(Futures.immediateFuture(null)).when(cohort1).preCommit();
1283 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).commit();
1284 doReturn(mockCandidate("cohort1-candidate")).when(cohort1).getCandidate();
1286 final String transactionID2 = "tx2";
1287 final MutableCompositeModification modification2 = new MutableCompositeModification();
1288 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1289 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1291 final FiniteDuration duration = duration("5 seconds");
1292 final Timeout timeout = new Timeout(duration);
1294 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1295 expectMsgClass(duration, ReadyTransactionReply.class);
1297 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1298 expectMsgClass(duration, ReadyTransactionReply.class);
1300 // Send the CanCommitTransaction message for the first Tx.
1302 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1303 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1304 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1305 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1307 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1308 // processed after the first Tx completes.
1310 final Future<Object> canCommitFuture = Patterns.ask(shard,
1311 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
1313 // Send the CommitTransaction message for the first Tx. This should send back an error
1314 // and trigger the 2nd Tx to proceed.
1316 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
1317 expectMsgClass(duration, akka.actor.Status.Failure.class);
1319 // Wait for the 2nd Tx to complete the canCommit phase.
1321 final CountDownLatch latch = new CountDownLatch(1);
1322 canCommitFuture.onComplete(new OnComplete<Object>() {
1324 public void onComplete(final Throwable t, final Object resp) {
1327 }, getSystem().dispatcher());
1329 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1331 final InOrder inOrder = inOrder(cohort1, cohort2);
1332 inOrder.verify(cohort1).canCommit();
1333 inOrder.verify(cohort1).preCommit();
1334 inOrder.verify(cohort1).commit();
1335 inOrder.verify(cohort2).canCommit();
1340 public void testPreCommitPhaseFailure() throws Throwable {
1341 testPreCommitPhaseFailure(true);
1342 testPreCommitPhaseFailure(false);
1345 private void testPreCommitPhaseFailure(final boolean readWrite) throws Throwable {
1346 new ShardTestKit(getSystem()) {{
1347 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1348 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1349 "testPreCommitPhaseFailure-" + readWrite);
1351 waitUntilLeader(shard);
1353 final String transactionID1 = "tx1";
1354 final MutableCompositeModification modification1 = new MutableCompositeModification();
1355 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1356 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1357 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).preCommit();
1359 final String transactionID2 = "tx2";
1360 final MutableCompositeModification modification2 = new MutableCompositeModification();
1361 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1362 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1364 final FiniteDuration duration = duration("5 seconds");
1365 final Timeout timeout = new Timeout(duration);
1367 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1368 expectMsgClass(duration, ReadyTransactionReply.class);
1370 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1371 expectMsgClass(duration, ReadyTransactionReply.class);
1373 // Send the CanCommitTransaction message for the first Tx.
1375 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1376 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1377 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1378 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1380 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1381 // processed after the first Tx completes.
1383 final Future<Object> canCommitFuture = Patterns.ask(shard,
1384 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
1386 // Send the CommitTransaction message for the first Tx. This should send back an error
1387 // and trigger the 2nd Tx to proceed.
1389 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
1390 expectMsgClass(duration, akka.actor.Status.Failure.class);
1392 // Wait for the 2nd Tx to complete the canCommit phase.
1394 final CountDownLatch latch = new CountDownLatch(1);
1395 canCommitFuture.onComplete(new OnComplete<Object>() {
1397 public void onComplete(final Throwable t, final Object resp) {
1400 }, getSystem().dispatcher());
1402 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1404 final InOrder inOrder = inOrder(cohort1, cohort2);
1405 inOrder.verify(cohort1).canCommit();
1406 inOrder.verify(cohort1).preCommit();
1407 inOrder.verify(cohort2).canCommit();
1412 public void testCanCommitPhaseFailure() throws Throwable {
1413 testCanCommitPhaseFailure(true);
1414 testCanCommitPhaseFailure(false);
1417 private void testCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1418 new ShardTestKit(getSystem()) {{
1419 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1420 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1421 "testCanCommitPhaseFailure-" + readWrite);
1423 waitUntilLeader(shard);
1425 final FiniteDuration duration = duration("5 seconds");
1427 final String transactionID1 = "tx1";
1428 final MutableCompositeModification modification = new MutableCompositeModification();
1429 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1430 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1432 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1433 expectMsgClass(duration, ReadyTransactionReply.class);
1435 // Send the CanCommitTransaction message.
1437 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1438 expectMsgClass(duration, akka.actor.Status.Failure.class);
1440 // Send another can commit to ensure the failed one got cleaned up.
1444 final String transactionID2 = "tx2";
1445 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1447 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1448 expectMsgClass(duration, ReadyTransactionReply.class);
1450 shard.tell(new CanCommitTransaction(transactionID2).toSerializable(), getRef());
1451 final CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1452 expectMsgClass(CanCommitTransactionReply.SERIALIZABLE_CLASS));
1453 assertEquals("getCanCommit", true, reply.getCanCommit());
1458 public void testCanCommitPhaseFalseResponse() throws Throwable {
1459 testCanCommitPhaseFalseResponse(true);
1460 testCanCommitPhaseFalseResponse(false);
1463 private void testCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1464 new ShardTestKit(getSystem()) {{
1465 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1466 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1467 "testCanCommitPhaseFalseResponse-" + readWrite);
1469 waitUntilLeader(shard);
1471 final FiniteDuration duration = duration("5 seconds");
1473 final String transactionID1 = "tx1";
1474 final MutableCompositeModification modification = new MutableCompositeModification();
1475 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1476 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1478 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1479 expectMsgClass(duration, ReadyTransactionReply.class);
1481 // Send the CanCommitTransaction message.
1483 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1484 CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1485 expectMsgClass(CanCommitTransactionReply.SERIALIZABLE_CLASS));
1486 assertEquals("getCanCommit", false, reply.getCanCommit());
1488 // Send another can commit to ensure the failed one got cleaned up.
1492 final String transactionID2 = "tx2";
1493 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1495 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1496 expectMsgClass(duration, ReadyTransactionReply.class);
1498 shard.tell(new CanCommitTransaction(transactionID2).toSerializable(), getRef());
1499 reply = CanCommitTransactionReply.fromSerializable(
1500 expectMsgClass(CanCommitTransactionReply.SERIALIZABLE_CLASS));
1501 assertEquals("getCanCommit", true, reply.getCanCommit());
1506 public void testImmediateCommitWithCanCommitPhaseFailure() throws Throwable {
1507 testImmediateCommitWithCanCommitPhaseFailure(true);
1508 testImmediateCommitWithCanCommitPhaseFailure(false);
1511 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1512 new ShardTestKit(getSystem()) {{
1513 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1514 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1515 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1517 waitUntilLeader(shard);
1519 final FiniteDuration duration = duration("5 seconds");
1521 final String transactionID1 = "tx1";
1522 final MutableCompositeModification modification = new MutableCompositeModification();
1523 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1524 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1526 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification, true), getRef());
1528 expectMsgClass(duration, akka.actor.Status.Failure.class);
1530 // Send another can commit to ensure the failed one got cleaned up.
1534 final String transactionID2 = "tx2";
1535 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1536 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1537 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1538 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1539 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1540 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1541 doReturn(candidateRoot).when(candidate).getRootNode();
1542 doReturn(candidate).when(cohort).getCandidate();
1544 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1546 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1551 public void testImmediateCommitWithCanCommitPhaseFalseResponse() throws Throwable {
1552 testImmediateCommitWithCanCommitPhaseFalseResponse(true);
1553 testImmediateCommitWithCanCommitPhaseFalseResponse(false);
1556 private void testImmediateCommitWithCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1557 new ShardTestKit(getSystem()) {{
1558 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1559 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1560 "testImmediateCommitWithCanCommitPhaseFalseResponse-" + readWrite);
1562 waitUntilLeader(shard);
1564 final FiniteDuration duration = duration("5 seconds");
1566 final String transactionID = "tx1";
1567 final MutableCompositeModification modification = new MutableCompositeModification();
1568 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1569 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1571 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
1573 expectMsgClass(duration, akka.actor.Status.Failure.class);
1575 // Send another can commit to ensure the failed one got cleaned up.
1579 final String transactionID2 = "tx2";
1580 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1581 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1582 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1583 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1584 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1585 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1586 doReturn(candidateRoot).when(candidate).getRootNode();
1587 doReturn(candidate).when(cohort).getCandidate();
1589 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1591 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1596 public void testAbortBeforeFinishCommit() throws Throwable {
1597 testAbortBeforeFinishCommit(true);
1598 testAbortBeforeFinishCommit(false);
1601 private void testAbortBeforeFinishCommit(final boolean readWrite) throws Throwable {
1602 new ShardTestKit(getSystem()) {{
1603 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1604 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1605 "testAbortBeforeFinishCommit-" + readWrite);
1607 waitUntilLeader(shard);
1609 final FiniteDuration duration = duration("5 seconds");
1610 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1612 final String transactionID = "tx1";
1613 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit =
1614 new Function<ShardDataTreeCohort, ListenableFuture<Void>>() {
1616 public ListenableFuture<Void> apply(final ShardDataTreeCohort cohort) {
1617 final ListenableFuture<Void> preCommitFuture = cohort.preCommit();
1619 // Simulate an AbortTransaction message occurring during replication, after
1620 // persisting and before finishing the commit to the in-memory store.
1621 // We have no followers so due to optimizations in the RaftActor, it does not
1622 // attempt replication and thus we can't send an AbortTransaction message b/c
1623 // it would be processed too late after CommitTransaction completes. So we'll
1624 // simulate an AbortTransaction message occurring during replication by calling
1625 // the shard directly.
1627 shard.underlyingActor().doAbortTransaction(transactionID, null);
1629 return preCommitFuture;
1633 final MutableCompositeModification modification = new MutableCompositeModification();
1634 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort1", dataStore,
1635 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME),
1636 modification, preCommit);
1638 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1639 expectMsgClass(duration, ReadyTransactionReply.class);
1641 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1642 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1643 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1644 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1646 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
1647 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1649 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1651 // Since we're simulating an abort occurring during replication and before finish commit,
1652 // the data should still get written to the in-memory store since we've gotten past
1653 // canCommit and preCommit and persisted the data.
1654 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1659 public void testTransactionCommitTimeout() throws Throwable {
1660 testTransactionCommitTimeout(true);
1661 testTransactionCommitTimeout(false);
1664 private void testTransactionCommitTimeout(final boolean readWrite) throws Throwable {
1665 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1667 new ShardTestKit(getSystem()) {{
1668 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1669 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1670 "testTransactionCommitTimeout-" + readWrite);
1672 waitUntilLeader(shard);
1674 final FiniteDuration duration = duration("5 seconds");
1676 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1678 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1679 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1680 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1682 // Create 1st Tx - will timeout
1684 final String transactionID1 = "tx1";
1685 final MutableCompositeModification modification1 = new MutableCompositeModification();
1686 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1687 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1688 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1689 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
1694 final String transactionID2 = "tx3";
1695 final MutableCompositeModification modification2 = new MutableCompositeModification();
1696 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1697 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1698 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort3", dataStore,
1700 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2),
1705 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1706 expectMsgClass(duration, ReadyTransactionReply.class);
1708 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1709 expectMsgClass(duration, ReadyTransactionReply.class);
1711 // canCommit 1st Tx. We don't send the commit so it should timeout.
1713 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1714 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1716 // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1718 shard.tell(new CanCommitTransaction(transactionID2).toSerializable(), getRef());
1719 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1721 // Try to commit the 1st Tx - should fail as it's not the current Tx.
1723 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
1724 expectMsgClass(duration, akka.actor.Status.Failure.class);
1726 // Commit the 2nd Tx.
1728 shard.tell(new CommitTransaction(transactionID2).toSerializable(), getRef());
1729 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1731 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1732 assertNotNull(listNodePath + " not found", node);
1737 public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1738 dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1740 new ShardTestKit(getSystem()) {{
1741 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1742 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1743 "testTransactionCommitQueueCapacityExceeded");
1745 waitUntilLeader(shard);
1747 final FiniteDuration duration = duration("5 seconds");
1749 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1751 final String transactionID1 = "tx1";
1752 final MutableCompositeModification modification1 = new MutableCompositeModification();
1753 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1754 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1756 final String transactionID2 = "tx2";
1757 final MutableCompositeModification modification2 = new MutableCompositeModification();
1758 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1759 TestModel.OUTER_LIST_PATH,
1760 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
1763 final String transactionID3 = "tx3";
1764 final MutableCompositeModification modification3 = new MutableCompositeModification();
1765 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1766 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification3);
1770 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1771 expectMsgClass(duration, ReadyTransactionReply.class);
1773 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1774 expectMsgClass(duration, ReadyTransactionReply.class);
1776 // The 3rd Tx should exceed queue capacity and fail.
1778 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1779 expectMsgClass(duration, akka.actor.Status.Failure.class);
1781 // canCommit 1st Tx.
1783 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1784 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1786 // canCommit the 2nd Tx - it should get queued.
1788 shard.tell(new CanCommitTransaction(transactionID2).toSerializable(), getRef());
1790 // canCommit the 3rd Tx - should exceed queue capacity and fail.
1792 shard.tell(new CanCommitTransaction(transactionID3).toSerializable(), getRef());
1793 expectMsgClass(duration, akka.actor.Status.Failure.class);
1798 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Throwable {
1799 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1801 new ShardTestKit(getSystem()) {{
1802 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1803 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1804 "testTransactionCommitWithPriorExpiredCohortEntries");
1806 waitUntilLeader(shard);
1808 final FiniteDuration duration = duration("5 seconds");
1810 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1812 final String transactionID1 = "tx1";
1813 final MutableCompositeModification modification1 = new MutableCompositeModification();
1814 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1815 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1817 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1818 expectMsgClass(duration, ReadyTransactionReply.class);
1820 final String transactionID2 = "tx2";
1821 final MutableCompositeModification modification2 = new MutableCompositeModification();
1822 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1823 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1825 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1826 expectMsgClass(duration, ReadyTransactionReply.class);
1828 final String transactionID3 = "tx3";
1829 final MutableCompositeModification modification3 = new MutableCompositeModification();
1830 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1831 TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME), modification3);
1833 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1834 expectMsgClass(duration, ReadyTransactionReply.class);
1836 // All Tx's are readied. We'll send canCommit for the last one but not the others. The others
1837 // should expire from the queue and the last one should be processed.
1839 shard.tell(new CanCommitTransaction(transactionID3).toSerializable(), getRef());
1840 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1845 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Throwable {
1846 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1848 new ShardTestKit(getSystem()) {{
1849 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1850 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1851 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1853 waitUntilLeader(shard);
1855 final FiniteDuration duration = duration("5 seconds");
1857 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1859 final String transactionID1 = "tx1";
1860 final MutableCompositeModification modification1 = new MutableCompositeModification();
1861 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1862 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1864 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1865 expectMsgClass(duration, ReadyTransactionReply.class);
1867 // CanCommit the first one so it's the current in-progress CohortEntry.
1869 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1870 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1872 // Ready the second Tx.
1874 final String transactionID2 = "tx2";
1875 final MutableCompositeModification modification2 = new MutableCompositeModification();
1876 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1877 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1879 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1880 expectMsgClass(duration, ReadyTransactionReply.class);
1882 // Ready the third Tx.
1884 final String transactionID3 = "tx3";
1885 final DataTreeModification modification3 = dataStore.newModification();
1886 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1887 .apply(modification3);
1888 modification3.ready();
1889 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3, true);
1891 shard.tell(readyMessage, getRef());
1893 // Commit the first Tx. After completing, the second should expire from the queue and the third
1896 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
1897 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1899 // Expect commit reply from the third Tx.
1901 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1903 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1904 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1909 public void testCanCommitBeforeReadyFailure() throws Throwable {
1910 new ShardTestKit(getSystem()) {{
1911 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1912 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1913 "testCanCommitBeforeReadyFailure");
1915 shard.tell(new CanCommitTransaction("tx").toSerializable(), getRef());
1916 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1921 public void testAbortCurrentTransaction() throws Throwable {
1922 testAbortCurrentTransaction(true);
1923 testAbortCurrentTransaction(false);
1926 private void testAbortCurrentTransaction(final boolean readWrite) throws Throwable {
1927 new ShardTestKit(getSystem()) {{
1928 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1929 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1930 "testAbortCurrentTransaction-" + readWrite);
1932 waitUntilLeader(shard);
1934 // Setup 2 simulated transactions with mock cohorts. The first one will be aborted.
1936 final String transactionID1 = "tx1";
1937 final MutableCompositeModification modification1 = new MutableCompositeModification();
1938 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1939 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1940 doReturn(Futures.immediateFuture(null)).when(cohort1).abort();
1942 final String transactionID2 = "tx2";
1943 final MutableCompositeModification modification2 = new MutableCompositeModification();
1944 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1945 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1947 final FiniteDuration duration = duration("5 seconds");
1948 final Timeout timeout = new Timeout(duration);
1950 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1951 expectMsgClass(duration, ReadyTransactionReply.class);
1953 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1954 expectMsgClass(duration, ReadyTransactionReply.class);
1956 // Send the CanCommitTransaction message for the first Tx.
1958 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1959 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1960 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1961 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1963 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1964 // processed after the first Tx completes.
1966 final Future<Object> canCommitFuture = Patterns.ask(shard,
1967 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
1969 // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1972 shard.tell(new AbortTransaction(transactionID1).toSerializable(), getRef());
1973 expectMsgClass(duration, AbortTransactionReply.SERIALIZABLE_CLASS);
1975 // Wait for the 2nd Tx to complete the canCommit phase.
1977 Await.ready(canCommitFuture, duration);
1979 final InOrder inOrder = inOrder(cohort1, cohort2);
1980 inOrder.verify(cohort1).canCommit();
1981 inOrder.verify(cohort2).canCommit();
1986 public void testAbortQueuedTransaction() throws Throwable {
1987 testAbortQueuedTransaction(true);
1988 testAbortQueuedTransaction(false);
1991 private void testAbortQueuedTransaction(final boolean readWrite) throws Throwable {
1992 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1993 new ShardTestKit(getSystem()) {{
1994 final AtomicReference<CountDownLatch> cleaupCheckLatch = new AtomicReference<>();
1995 @SuppressWarnings("serial")
1996 final Creator<Shard> creator = new Creator<Shard>() {
1998 public Shard create() throws Exception {
1999 return new Shard(newShardBuilder()) {
2001 public void onReceiveCommand(final Object message) throws Exception {
2002 super.onReceiveCommand(message);
2003 if(message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
2004 if(cleaupCheckLatch.get() != null) {
2005 cleaupCheckLatch.get().countDown();
2013 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2014 Props.create(new DelegatingShardCreator(creator)).withDispatcher(
2015 Dispatchers.DefaultDispatcherId()), "testAbortQueuedTransaction-" + readWrite);
2017 waitUntilLeader(shard);
2019 final String transactionID = "tx1";
2021 final MutableCompositeModification modification = new MutableCompositeModification();
2022 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort");
2023 doReturn(Futures.immediateFuture(null)).when(cohort).abort();
2025 final FiniteDuration duration = duration("5 seconds");
2029 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
2030 expectMsgClass(duration, ReadyTransactionReply.class);
2032 assertEquals("getPendingTxCommitQueueSize", 1, shard.underlyingActor().getPendingTxCommitQueueSize());
2034 // Send the AbortTransaction message.
2036 shard.tell(new AbortTransaction(transactionID).toSerializable(), getRef());
2037 expectMsgClass(duration, AbortTransactionReply.SERIALIZABLE_CLASS);
2039 verify(cohort).abort();
2041 // Verify the tx cohort is removed from queue at the cleanup check interval.
2043 cleaupCheckLatch.set(new CountDownLatch(1));
2044 assertEquals("TX_COMMIT_TIMEOUT_CHECK_MESSAGE received", true,
2045 cleaupCheckLatch.get().await(5, TimeUnit.SECONDS));
2047 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
2049 // Now send CanCommitTransaction - should fail.
2051 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
2053 Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
2054 assertTrue("Failure type", failure instanceof IllegalStateException);
2059 public void testCreateSnapshot() throws Exception {
2060 testCreateSnapshot(true, "testCreateSnapshot");
2064 public void testCreateSnapshotWithNonPersistentData() throws Exception {
2065 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
2068 @SuppressWarnings("serial")
2069 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
2071 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
2073 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
2074 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
2075 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
2080 public void saveSnapshot(final Object o) {
2081 savedSnapshot.set(o);
2082 super.saveSnapshot(o);
2086 dataStoreContextBuilder.persistent(persistent);
2088 new ShardTestKit(getSystem()) {{
2089 class TestShard extends Shard {
2091 protected TestShard(AbstractBuilder<?, ?> builder) {
2093 setPersistence(new TestPersistentDataProvider(super.persistence()));
2097 public void handleCommand(final Object message) {
2098 super.handleCommand(message);
2100 if (message instanceof SaveSnapshotSuccess || message.equals("commit_snapshot")) {
2101 latch.get().countDown();
2106 public RaftActorContext getRaftActorContext() {
2107 return super.getRaftActorContext();
2111 final Creator<Shard> creator = new Creator<Shard>() {
2113 public Shard create() throws Exception {
2114 return new TestShard(newShardBuilder());
2118 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2119 Props.create(new DelegatingShardCreator(creator)), shardActorName);
2121 waitUntilLeader(shard);
2122 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2124 final NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.builder().build());
2126 // Trigger creation of a snapshot by ensuring
2127 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
2128 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2129 awaitAndValidateSnapshot(expectedRoot);
2131 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2132 awaitAndValidateSnapshot(expectedRoot);
2135 private void awaitAndValidateSnapshot(NormalizedNode<?,?> expectedRoot) throws InterruptedException {
2136 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
2138 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
2139 savedSnapshot.get() instanceof Snapshot);
2141 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
2143 latch.set(new CountDownLatch(1));
2144 savedSnapshot.set(null);
2147 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?,?> expectedRoot) {
2149 final NormalizedNode<?, ?> actual = SerializationUtils.deserializeNormalizedNode(snapshot.getState());
2150 assertEquals("Root node", expectedRoot, actual);
2156 * This test simply verifies that the applySnapShot logic will work
2157 * @throws ReadFailedException
2158 * @throws DataValidationFailedException
2161 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
2162 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
2163 store.setSchemaContext(SCHEMA_CONTEXT);
2165 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
2166 putTransaction.write(TestModel.TEST_PATH,
2167 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2168 commitTransaction(store, putTransaction);
2171 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.builder().build());
2173 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2175 writeTransaction.delete(YangInstanceIdentifier.builder().build());
2176 writeTransaction.write(YangInstanceIdentifier.builder().build(), expected);
2178 commitTransaction(store, writeTransaction);
2180 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.builder().build());
2182 assertEquals(expected, actual);
2186 public void testRecoveryApplicable(){
2188 final DatastoreContext persistentContext = DatastoreContext.newBuilder().
2189 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2191 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext).
2192 schemaContext(SCHEMA_CONTEXT).props();
2194 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
2195 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2197 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext).
2198 schemaContext(SCHEMA_CONTEXT).props();
2200 new ShardTestKit(getSystem()) {{
2201 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2203 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2205 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2207 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2212 public void testOnDatastoreContext() {
2213 new ShardTestKit(getSystem()) {{
2214 dataStoreContextBuilder.persistent(true);
2216 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
2218 assertEquals("isRecoveryApplicable", true,
2219 shard.underlyingActor().persistence().isRecoveryApplicable());
2221 waitUntilLeader(shard);
2223 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2225 assertEquals("isRecoveryApplicable", false,
2226 shard.underlyingActor().persistence().isRecoveryApplicable());
2228 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2230 assertEquals("isRecoveryApplicable", true,
2231 shard.underlyingActor().persistence().isRecoveryApplicable());
2236 public void testRegisterRoleChangeListener() throws Exception {
2237 new ShardTestKit(getSystem()) {
2239 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2240 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2241 "testRegisterRoleChangeListener");
2243 waitUntilLeader(shard);
2245 final TestActorRef<MessageCollectorActor> listener =
2246 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2248 shard.tell(new RegisterRoleChangeListener(), listener);
2250 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2252 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2253 ShardLeaderStateChanged.class);
2254 assertEquals("getLocalShardDataTree present", true,
2255 leaderStateChanged.getLocalShardDataTree().isPresent());
2256 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2257 leaderStateChanged.getLocalShardDataTree().get());
2259 MessageCollectorActor.clearMessages(listener);
2261 // Force a leader change
2263 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2265 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2266 ShardLeaderStateChanged.class);
2267 assertEquals("getLocalShardDataTree present", false,
2268 leaderStateChanged.getLocalShardDataTree().isPresent());
2274 public void testFollowerInitialSyncStatus() throws Exception {
2275 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2276 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2277 "testFollowerInitialSyncStatus");
2279 shard.underlyingActor().onReceiveCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
2281 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2283 shard.underlyingActor().onReceiveCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
2285 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2289 public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
2290 new ShardTestKit(getSystem()) {{
2291 String testName = "testClusteredDataChangeListenerDelayedRegistration";
2292 dataStoreContextBuilder.shardElectionTimeoutFactor(1000);
2294 final MockDataChangeListener listener = new MockDataChangeListener(1);
2295 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2296 actorFactory.generateActorId(testName + "-DataChangeListener"));
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 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2313 shard.tell(new ElectionTimeout(), ActorRef.noSender());
2315 listener.waitForChangeEvents();
2320 public void testClusteredDataChangeListenerRegistration() throws Exception {
2321 new ShardTestKit(getSystem()) {{
2322 String testName = "testClusteredDataChangeListenerRegistration";
2323 final ShardIdentifier followerShardID = ShardIdentifier.builder().memberName(
2324 actorFactory.generateActorId(testName + "-follower")).shardName("inventory").type("config").build();
2326 final ShardIdentifier leaderShardID = ShardIdentifier.builder().memberName(
2327 actorFactory.generateActorId(testName + "-leader")).shardName("inventory").type("config").build();
2329 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2330 Shard.builder().id(followerShardID).
2331 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2332 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2333 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2334 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2336 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2337 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2338 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2339 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2340 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2342 leaderShard.tell(new ElectionTimeout(), ActorRef.noSender());
2343 String leaderPath = waitUntilLeader(followerShard);
2344 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2346 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2347 final MockDataChangeListener listener = new MockDataChangeListener(1);
2348 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2349 actorFactory.generateActorId(testName + "-DataChangeListener"));
2351 followerShard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2352 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2353 RegisterChangeListenerReply.class);
2354 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2356 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2358 listener.waitForChangeEvents();
2363 public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
2364 new ShardTestKit(getSystem()) {{
2365 String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
2366 dataStoreContextBuilder.shardElectionTimeoutFactor(1000);
2368 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2369 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2370 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2372 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2373 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2374 actorFactory.generateActorId(testName + "-shard"));
2376 waitUntilNoLeader(shard);
2378 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2380 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2381 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2382 RegisterDataTreeChangeListenerReply.class);
2383 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2385 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2387 shard.tell(new ElectionTimeout(), ActorRef.noSender());
2389 listener.waitForChangeEvents();
2394 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2395 new ShardTestKit(getSystem()) {{
2396 String testName = "testClusteredDataTreeChangeListenerRegistration";
2397 final ShardIdentifier followerShardID = ShardIdentifier.builder().memberName(
2398 actorFactory.generateActorId(testName + "-follower")).shardName("inventory").type("config").build();
2400 final ShardIdentifier leaderShardID = ShardIdentifier.builder().memberName(
2401 actorFactory.generateActorId(testName + "-leader")).shardName("inventory").type("config").build();
2403 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2404 Shard.builder().id(followerShardID).
2405 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2406 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2407 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2408 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2410 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2411 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2412 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2413 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2414 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2416 leaderShard.tell(new ElectionTimeout(), ActorRef.noSender());
2417 String leaderPath = waitUntilLeader(followerShard);
2418 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2420 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2421 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2422 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2423 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2425 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2426 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2427 RegisterDataTreeChangeListenerReply.class);
2428 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2430 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2432 listener.waitForChangeEvents();
2437 public void testServerRemoved() throws Exception {
2438 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2440 final ActorRef shard = parent.underlyingActor().context().actorOf(
2441 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2442 "testServerRemoved");
2444 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2446 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);