2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.cluster.datastore;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertSame;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
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;
24 import akka.actor.ActorRef;
25 import akka.actor.ActorSelection;
26 import akka.actor.Props;
27 import akka.actor.Status.Failure;
28 import akka.dispatch.Dispatchers;
29 import akka.dispatch.OnComplete;
30 import akka.japi.Creator;
31 import akka.pattern.Patterns;
32 import akka.persistence.SaveSnapshotSuccess;
33 import akka.testkit.TestActorRef;
34 import akka.util.Timeout;
35 import com.google.common.base.Function;
36 import com.google.common.base.Stopwatch;
37 import com.google.common.util.concurrent.Futures;
38 import com.google.common.util.concurrent.ListenableFuture;
39 import com.google.common.util.concurrent.Uninterruptibles;
40 import java.util.Collections;
41 import java.util.HashSet;
43 import java.util.concurrent.CountDownLatch;
44 import java.util.concurrent.TimeUnit;
45 import java.util.concurrent.atomic.AtomicBoolean;
46 import java.util.concurrent.atomic.AtomicReference;
47 import org.junit.Test;
48 import org.mockito.InOrder;
49 import org.opendaylight.controller.cluster.DataPersistenceProvider;
50 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
51 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
52 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
53 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
54 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
55 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
56 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
57 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
58 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
59 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
60 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
61 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
62 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
64 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
65 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
66 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
67 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
68 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
69 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
70 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
71 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
72 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListenerReply;
73 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
74 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
75 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
76 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
77 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
78 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
79 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
80 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
81 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
82 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
83 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
84 import org.opendaylight.controller.cluster.raft.RaftActorContext;
85 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
86 import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry;
87 import org.opendaylight.controller.cluster.raft.Snapshot;
88 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
89 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
90 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
91 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
92 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
93 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
94 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
95 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
96 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
97 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
98 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
99 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
100 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
101 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
102 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
103 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
104 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
105 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
106 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
107 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
108 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
109 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
110 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
112 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
113 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
114 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
116 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
117 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
118 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
119 import scala.concurrent.Await;
120 import scala.concurrent.Future;
121 import scala.concurrent.duration.FiniteDuration;
123 public class ShardTest extends AbstractShardTest {
124 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";
127 public void testRegisterChangeListener() throws Exception {
128 new ShardTestKit(getSystem()) {{
129 final TestActorRef<Shard> shard = actorFactory.createTestActor(
130 newShardProps(), "testRegisterChangeListener");
132 waitUntilLeader(shard);
134 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
136 final MockDataChangeListener listener = new MockDataChangeListener(1);
137 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
138 "testRegisterChangeListener-DataChangeListener");
140 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
141 dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
143 final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
144 RegisterChangeListenerReply.class);
145 final String replyPath = reply.getListenerRegistrationPath().toString();
146 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
147 "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
149 final YangInstanceIdentifier path = TestModel.TEST_PATH;
150 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
152 listener.waitForChangeEvents(path);
156 @SuppressWarnings("serial")
158 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
159 // This test tests the timing window in which a change listener is registered before the
160 // shard becomes the leader. We verify that the listener is registered and notified of the
161 // existing data when the shard becomes the leader.
162 new ShardTestKit(getSystem()) {{
163 // For this test, we want to send the RegisterChangeListener message after the shard
164 // has recovered from persistence and before it becomes the leader. So we subclass
165 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
166 // we know that the shard has been initialized to a follower and has started the
167 // election process. The following 2 CountDownLatches are used to coordinate the
168 // ElectionTimeout with the sending of the RegisterChangeListener message.
169 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
170 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
171 final Creator<Shard> creator = new Creator<Shard>() {
172 boolean firstElectionTimeout = true;
175 public Shard create() throws Exception {
176 // Use a non persistent provider because this test actually invokes persist on the journal
177 // this will cause all other messages to not be queued properly after that.
178 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
179 // it does do a persist)
180 return new Shard(newShardBuilder()) {
182 public void handleCommand(final Object message) {
183 if(message instanceof ElectionTimeout && firstElectionTimeout) {
184 // Got the first ElectionTimeout. We don't forward it to the
185 // base Shard yet until we've sent the RegisterChangeListener
186 // message. So we signal the onFirstElectionTimeout latch to tell
187 // the main thread to send the RegisterChangeListener message and
188 // start a thread to wait on the onChangeListenerRegistered latch,
189 // which the main thread signals after it has sent the message.
190 // After the onChangeListenerRegistered is triggered, we send the
191 // original ElectionTimeout message to proceed with the election.
192 firstElectionTimeout = false;
193 final ActorRef self = getSelf();
197 Uninterruptibles.awaitUninterruptibly(
198 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
199 self.tell(message, self);
203 onFirstElectionTimeout.countDown();
205 super.handleCommand(message);
212 setupInMemorySnapshotStore();
214 final MockDataChangeListener listener = new MockDataChangeListener(1);
215 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
216 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
218 final TestActorRef<Shard> shard = actorFactory.createTestActor(
219 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
220 "testRegisterChangeListenerWhenNotLeaderInitially");
222 final YangInstanceIdentifier path = TestModel.TEST_PATH;
224 // Wait until the shard receives the first ElectionTimeout message.
225 assertEquals("Got first ElectionTimeout", true,
226 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
228 // Now send the RegisterChangeListener and wait for the reply.
229 shard.tell(new RegisterChangeListener(path, dclActor,
230 AsyncDataBroker.DataChangeScope.SUBTREE, false), getRef());
232 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
233 RegisterChangeListenerReply.class);
234 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
236 // Sanity check - verify the shard is not the leader yet.
237 shard.tell(FindLeader.INSTANCE, getRef());
238 final FindLeaderReply findLeadeReply =
239 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
240 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
242 // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
243 // with the election process.
244 onChangeListenerRegistered.countDown();
246 // Wait for the shard to become the leader and notify our listener with the existing
247 // data in the store.
248 listener.waitForChangeEvents(path);
253 public void testRegisterDataTreeChangeListener() throws Exception {
254 new ShardTestKit(getSystem()) {{
255 final TestActorRef<Shard> shard = actorFactory.createTestActor(
256 newShardProps(), "testRegisterDataTreeChangeListener");
258 waitUntilLeader(shard);
260 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
262 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
263 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
264 "testRegisterDataTreeChangeListener-DataTreeChangeListener");
266 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
268 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
269 RegisterDataTreeChangeListenerReply.class);
270 final String replyPath = reply.getListenerRegistrationPath().toString();
271 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
272 "akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
274 final YangInstanceIdentifier path = TestModel.TEST_PATH;
275 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
277 listener.waitForChangeEvents();
281 @SuppressWarnings("serial")
283 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
284 new ShardTestKit(getSystem()) {{
285 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
286 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
287 final Creator<Shard> creator = new Creator<Shard>() {
288 boolean firstElectionTimeout = true;
291 public Shard create() throws Exception {
292 return new Shard(newShardBuilder()) {
294 public void handleCommand(final Object message) {
295 if(message instanceof ElectionTimeout && firstElectionTimeout) {
296 firstElectionTimeout = false;
297 final ActorRef self = getSelf();
301 Uninterruptibles.awaitUninterruptibly(
302 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
303 self.tell(message, self);
307 onFirstElectionTimeout.countDown();
309 super.handleCommand(message);
316 setupInMemorySnapshotStore();
318 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
319 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
320 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
322 final TestActorRef<Shard> shard = actorFactory.createTestActor(
323 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
324 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
326 final YangInstanceIdentifier path = TestModel.TEST_PATH;
328 assertEquals("Got first ElectionTimeout", true,
329 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
331 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
332 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
333 RegisterDataTreeChangeListenerReply.class);
334 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
336 shard.tell(FindLeader.INSTANCE, getRef());
337 final FindLeaderReply findLeadeReply =
338 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
339 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
342 onChangeListenerRegistered.countDown();
344 // TODO: investigate why we do not receive data chage events
345 listener.waitForChangeEvents();
350 public void testCreateTransaction(){
351 new ShardTestKit(getSystem()) {{
352 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
354 waitUntilLeader(shard);
356 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
358 shard.tell(new CreateTransaction("txn-1", TransactionType.READ_ONLY.ordinal(), null,
359 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
361 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
362 CreateTransactionReply.class);
364 final String path = reply.getTransactionPath().toString();
365 assertTrue("Unexpected transaction path " + path,
366 path.contains("akka://test/user/testCreateTransaction/shard-txn-1"));
371 public void testCreateTransactionOnChain(){
372 new ShardTestKit(getSystem()) {{
373 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
375 waitUntilLeader(shard);
377 shard.tell(new CreateTransaction("txn-1",TransactionType.READ_ONLY.ordinal(), "foobar",
378 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
380 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
381 CreateTransactionReply.class);
383 final String path = reply.getTransactionPath().toString();
384 assertTrue("Unexpected transaction path " + path,
385 path.contains("akka://test/user/testCreateTransactionOnChain/shard-txn-1"));
390 public void testPeerAddressResolved() throws Exception {
391 new ShardTestKit(getSystem()) {{
392 ShardIdentifier peerID = ShardIdentifier.builder().memberName("member-2")
393 .shardName("inventory").type("config").build();
394 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder().
395 peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null)).props().
396 withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
398 final String address = "akka://foobar";
399 shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
401 shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
402 OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
403 assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
408 public void testApplySnapshot() throws Exception {
410 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testApplySnapshot");
412 ShardTestKit.waitUntilLeader(shard);
414 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
415 store.setSchemaContext(SCHEMA_CONTEXT);
417 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
418 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
419 withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
420 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
422 writeToStore(store, TestModel.TEST_PATH, container);
424 final YangInstanceIdentifier root = YangInstanceIdentifier.builder().build();
425 final NormalizedNode<?,?> expected = readStore(store, root);
427 final Snapshot snapshot = Snapshot.create(SerializationUtils.serializeNormalizedNode(expected),
428 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
430 shard.underlyingActor().getRaftActorSnapshotCohort().applySnapshot(snapshot.getState());
432 final NormalizedNode<?,?> actual = readStore(shard, root);
434 assertEquals("Root node", expected, actual);
438 public void testApplyState() throws Exception {
439 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testApplyState");
441 ShardTestKit.waitUntilLeader(shard);
443 final DataTree source = setupInMemorySnapshotStore();
444 final DataTreeModification writeMod = source.takeSnapshot().newModification();
445 ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
446 writeMod.write(TestModel.TEST_PATH, node);
449 final ApplyState applyState = new ApplyState(null, "test", new ReplicatedLogImplEntry(1, 2,
450 payloadForModification(source, writeMod)));
452 shard.tell(applyState, shard);
454 Stopwatch sw = Stopwatch.createStarted();
455 while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
456 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
458 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
460 assertEquals("Applied state", node, actual);
465 fail("State was not applied");
469 public void testDataTreeCandidateRecovery() throws Exception {
470 // Set up the InMemorySnapshotStore.
471 final DataTree source = setupInMemorySnapshotStore();
473 final DataTreeModification writeMod = source.takeSnapshot().newModification();
474 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
476 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
478 // Set up the InMemoryJournal.
479 InMemoryJournal.addEntry(shardID.toString(), 1, new ReplicatedLogImplEntry(0, 1, payloadForModification(source, writeMod)));
481 final int nListEntries = 16;
482 final Set<Integer> listEntryKeys = new HashSet<>();
484 // Add some ModificationPayload entries
485 for (int i = 1; i <= nListEntries; i++) {
486 listEntryKeys.add(Integer.valueOf(i));
488 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
489 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
491 final DataTreeModification mod = source.takeSnapshot().newModification();
492 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
494 InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
495 payloadForModification(source, mod)));
498 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
499 new ApplyJournalEntries(nListEntries));
501 testRecovery(listEntryKeys);
505 public void testConcurrentThreePhaseCommits() throws Throwable {
506 new ShardTestKit(getSystem()) {{
507 final TestActorRef<Shard> shard = actorFactory.createTestActor(
508 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
509 "testConcurrentThreePhaseCommits");
511 waitUntilLeader(shard);
513 // Setup 3 simulated transactions with mock cohorts backed by real cohorts.
515 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
517 final String transactionID1 = "tx1";
518 final MutableCompositeModification modification1 = new MutableCompositeModification();
519 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
520 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
522 final String transactionID2 = "tx2";
523 final MutableCompositeModification modification2 = new MutableCompositeModification();
524 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
525 TestModel.OUTER_LIST_PATH,
526 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
529 final String transactionID3 = "tx3";
530 final MutableCompositeModification modification3 = new MutableCompositeModification();
531 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
532 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
533 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
534 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
537 final long timeoutSec = 5;
538 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
539 final Timeout timeout = new Timeout(duration);
541 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
542 final ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
543 expectMsgClass(duration, ReadyTransactionReply.class));
544 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
546 // Send the CanCommitTransaction message for the first Tx.
548 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
549 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
550 expectMsgClass(duration, CanCommitTransactionReply.class));
551 assertEquals("Can commit", true, canCommitReply.getCanCommit());
553 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
554 expectMsgClass(duration, ReadyTransactionReply.class);
556 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
557 expectMsgClass(duration, ReadyTransactionReply.class);
559 // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
560 // processed after the first Tx completes.
562 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
563 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
565 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
566 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
568 // Send the CommitTransaction message for the first Tx. After it completes, it should
569 // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
571 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
572 expectMsgClass(duration, CommitTransactionReply.class);
574 // Wait for the next 2 Tx's to complete.
576 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
577 final CountDownLatch commitLatch = new CountDownLatch(2);
579 class OnFutureComplete extends OnComplete<Object> {
580 private final Class<?> expRespType;
582 OnFutureComplete(final Class<?> expRespType) {
583 this.expRespType = expRespType;
587 public void onComplete(final Throwable error, final Object resp) {
589 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
592 assertEquals("Commit response type", expRespType, resp.getClass());
594 } catch (final Exception e) {
600 void onSuccess(final Object resp) throws Exception {
604 class OnCommitFutureComplete extends OnFutureComplete {
605 OnCommitFutureComplete() {
606 super(CommitTransactionReply.class);
610 public void onComplete(final Throwable error, final Object resp) {
611 super.onComplete(error, resp);
612 commitLatch.countDown();
616 class OnCanCommitFutureComplete extends OnFutureComplete {
617 private final String transactionID;
619 OnCanCommitFutureComplete(final String transactionID) {
620 super(CanCommitTransactionReply.class);
621 this.transactionID = transactionID;
625 void onSuccess(final Object resp) throws Exception {
626 final CanCommitTransactionReply canCommitReply =
627 CanCommitTransactionReply.fromSerializable(resp);
628 assertEquals("Can commit", true, canCommitReply.getCanCommit());
630 final Future<Object> commitFuture = Patterns.ask(shard,
631 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
632 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
636 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
637 getSystem().dispatcher());
639 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
640 getSystem().dispatcher());
642 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
644 if(caughtEx.get() != null) {
645 throw caughtEx.get();
648 assertEquals("Commits complete", true, done);
650 final InOrder inOrder = inOrder(cohort1, cohort2, cohort3);
651 inOrder.verify(cohort1).canCommit();
652 inOrder.verify(cohort1).preCommit();
653 inOrder.verify(cohort1).commit();
654 inOrder.verify(cohort2).canCommit();
655 inOrder.verify(cohort2).preCommit();
656 inOrder.verify(cohort2).commit();
657 inOrder.verify(cohort3).canCommit();
658 inOrder.verify(cohort3).preCommit();
659 inOrder.verify(cohort3).commit();
661 // Verify data in the data store.
663 verifyOuterListEntry(shard, 1);
665 verifyLastApplied(shard, 2);
670 public void testBatchedModificationsWithNoCommitOnReady() throws Throwable {
671 new ShardTestKit(getSystem()) {{
672 final TestActorRef<Shard> shard = actorFactory.createTestActor(
673 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
674 "testBatchedModificationsWithNoCommitOnReady");
676 waitUntilLeader(shard);
678 final String transactionID = "tx";
679 final FiniteDuration duration = duration("5 seconds");
681 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
682 final ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
684 public ShardDataTreeCohort decorate(final String txID, final ShardDataTreeCohort actual) {
685 if(mockCohort.get() == null) {
686 mockCohort.set(createDelegatingMockCohort("cohort", actual));
689 return mockCohort.get();
693 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
695 // Send a BatchedModifications to start a transaction.
697 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
698 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
699 expectMsgClass(duration, BatchedModificationsReply.class);
701 // Send a couple more BatchedModifications.
703 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
704 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
705 expectMsgClass(duration, BatchedModificationsReply.class);
707 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
708 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
709 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3), getRef());
710 expectMsgClass(duration, ReadyTransactionReply.class);
712 // Send the CanCommitTransaction message.
714 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
715 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
716 expectMsgClass(duration, CanCommitTransactionReply.class));
717 assertEquals("Can commit", true, canCommitReply.getCanCommit());
719 // Send the CanCommitTransaction message.
721 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
722 expectMsgClass(duration, CommitTransactionReply.class);
724 final InOrder inOrder = inOrder(mockCohort.get());
725 inOrder.verify(mockCohort.get()).canCommit();
726 inOrder.verify(mockCohort.get()).preCommit();
727 inOrder.verify(mockCohort.get()).commit();
729 // Verify data in the data store.
731 verifyOuterListEntry(shard, 1);
736 public void testBatchedModificationsWithCommitOnReady() throws Throwable {
737 new ShardTestKit(getSystem()) {{
738 final TestActorRef<Shard> shard = actorFactory.createTestActor(
739 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
740 "testBatchedModificationsWithCommitOnReady");
742 waitUntilLeader(shard);
744 final String transactionID = "tx";
745 final FiniteDuration duration = duration("5 seconds");
747 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
748 final ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
750 public ShardDataTreeCohort decorate(final String txID, final ShardDataTreeCohort actual) {
751 if(mockCohort.get() == null) {
752 mockCohort.set(createDelegatingMockCohort("cohort", actual));
755 return mockCohort.get();
759 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
761 // Send a BatchedModifications to start a transaction.
763 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
764 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
765 expectMsgClass(duration, BatchedModificationsReply.class);
767 // Send a couple more BatchedModifications.
769 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
770 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
771 expectMsgClass(duration, BatchedModificationsReply.class);
773 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
774 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
775 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3), getRef());
777 expectMsgClass(duration, CommitTransactionReply.class);
779 final InOrder inOrder = inOrder(mockCohort.get());
780 inOrder.verify(mockCohort.get()).canCommit();
781 inOrder.verify(mockCohort.get()).preCommit();
782 inOrder.verify(mockCohort.get()).commit();
784 // Verify data in the data store.
786 verifyOuterListEntry(shard, 1);
790 @Test(expected=IllegalStateException.class)
791 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Throwable {
792 new ShardTestKit(getSystem()) {{
793 final TestActorRef<Shard> shard = actorFactory.createTestActor(
794 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
795 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
797 waitUntilLeader(shard);
799 final String transactionID = "tx1";
800 final BatchedModifications batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION, null);
801 batched.setReady(true);
802 batched.setTotalMessagesSent(2);
804 shard.tell(batched, getRef());
806 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
808 if(failure != null) {
809 throw failure.cause();
815 public void testBatchedModificationsWithOperationFailure() throws Throwable {
816 new ShardTestKit(getSystem()) {{
817 final TestActorRef<Shard> shard = actorFactory.createTestActor(
818 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
819 "testBatchedModificationsWithOperationFailure");
821 waitUntilLeader(shard);
823 // Test merge with invalid data. An exception should occur when the merge is applied. Note that
824 // write will not validate the children for performance reasons.
826 String transactionID = "tx1";
828 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
829 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
830 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
832 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, null);
833 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
834 shard.tell(batched, getRef());
835 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
837 Throwable cause = failure.cause();
839 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION, null);
840 batched.setReady(true);
841 batched.setTotalMessagesSent(2);
843 shard.tell(batched, getRef());
845 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
846 assertEquals("Failure cause", cause, failure.cause());
851 public void testBatchedModificationsOnTransactionChain() throws Throwable {
852 new ShardTestKit(getSystem()) {{
853 final TestActorRef<Shard> shard = actorFactory.createTestActor(
854 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
855 "testBatchedModificationsOnTransactionChain");
857 waitUntilLeader(shard);
859 final String transactionChainID = "txChain";
860 final String transactionID1 = "tx1";
861 final String transactionID2 = "tx2";
863 final FiniteDuration duration = duration("5 seconds");
865 // Send a BatchedModifications to start a chained write transaction and ready it.
867 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
868 final YangInstanceIdentifier path = TestModel.TEST_PATH;
869 shard.tell(newBatchedModifications(transactionID1, transactionChainID, path,
870 containerNode, true, false, 1), getRef());
871 expectMsgClass(duration, ReadyTransactionReply.class);
873 // Create a read Tx on the same chain.
875 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
876 transactionChainID, DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
878 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
880 getSystem().actorSelection(createReply.getTransactionPath()).tell(
881 new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
882 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
883 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
885 // Commit the write transaction.
887 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
888 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
889 expectMsgClass(duration, CanCommitTransactionReply.class));
890 assertEquals("Can commit", true, canCommitReply.getCanCommit());
892 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
893 expectMsgClass(duration, CommitTransactionReply.class);
895 // Verify data in the data store.
897 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
898 assertEquals("Stored node", containerNode, actualNode);
903 public void testOnBatchedModificationsWhenNotLeader() {
904 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
905 new ShardTestKit(getSystem()) {{
906 final Creator<Shard> creator = new Creator<Shard>() {
907 private static final long serialVersionUID = 1L;
910 public Shard create() throws Exception {
911 return new Shard(newShardBuilder()) {
913 protected boolean isLeader() {
914 return overrideLeaderCalls.get() ? false : super.isLeader();
918 protected ActorSelection getLeader() {
919 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
926 final TestActorRef<Shard> shard = actorFactory.createTestActor(
927 Props.create(new DelegatingShardCreator(creator)), "testOnBatchedModificationsWhenNotLeader");
929 waitUntilLeader(shard);
931 overrideLeaderCalls.set(true);
933 final BatchedModifications batched = new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, "");
935 shard.tell(batched, ActorRef.noSender());
937 expectMsgEquals(batched);
942 public void testTransactionMessagesWithNoLeader() {
943 new ShardTestKit(getSystem()) {{
944 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
945 shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
946 final TestActorRef<Shard> shard = actorFactory.createTestActor(
947 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
948 "testTransactionMessagesWithNoLeader");
950 waitUntilNoLeader(shard);
952 shard.tell(new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, ""), getRef());
953 Failure failure = expectMsgClass(Failure.class);
954 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
956 shard.tell(prepareForwardedReadyTransaction(mock(ShardDataTreeCohort.class), "tx",
957 DataStoreVersions.CURRENT_VERSION, true), getRef());
958 failure = expectMsgClass(Failure.class);
959 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
961 shard.tell(new ReadyLocalTransaction("tx", mock(DataTreeModification.class), true), getRef());
962 failure = expectMsgClass(Failure.class);
963 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
968 public void testReadyWithReadWriteImmediateCommit() throws Exception{
969 testReadyWithImmediateCommit(true);
973 public void testReadyWithWriteOnlyImmediateCommit() throws Exception{
974 testReadyWithImmediateCommit(false);
977 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception{
978 new ShardTestKit(getSystem()) {{
979 final TestActorRef<Shard> shard = actorFactory.createTestActor(
980 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
981 "testReadyWithImmediateCommit-" + readWrite);
983 waitUntilLeader(shard);
985 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
987 final String transactionID = "tx1";
988 final MutableCompositeModification modification = new MutableCompositeModification();
989 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
990 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
991 TestModel.TEST_PATH, containerNode, modification);
993 final FiniteDuration duration = duration("5 seconds");
995 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
997 expectMsgClass(duration, CommitTransactionReply.class);
999 final InOrder inOrder = inOrder(cohort);
1000 inOrder.verify(cohort).canCommit();
1001 inOrder.verify(cohort).preCommit();
1002 inOrder.verify(cohort).commit();
1004 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1005 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1010 public void testReadyLocalTransactionWithImmediateCommit() throws Exception{
1011 new ShardTestKit(getSystem()) {{
1012 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1013 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1014 "testReadyLocalTransactionWithImmediateCommit");
1016 waitUntilLeader(shard);
1018 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1020 final DataTreeModification modification = dataStore.newModification();
1022 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1023 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1024 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1025 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1027 final String txId = "tx1";
1028 modification.ready();
1029 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1031 shard.tell(readyMessage, getRef());
1033 expectMsgClass(CommitTransactionReply.class);
1035 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1036 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1041 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception{
1042 new ShardTestKit(getSystem()) {{
1043 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1044 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1045 "testReadyLocalTransactionWithThreePhaseCommit");
1047 waitUntilLeader(shard);
1049 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1051 final DataTreeModification modification = dataStore.newModification();
1053 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1054 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1055 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1056 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1058 final String txId = "tx1";
1059 modification.ready();
1060 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1062 shard.tell(readyMessage, getRef());
1064 expectMsgClass(ReadyTransactionReply.class);
1066 // Send the CanCommitTransaction message.
1068 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1069 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1070 expectMsgClass(CanCommitTransactionReply.class));
1071 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1073 // Send the CanCommitTransaction message.
1075 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1076 expectMsgClass(CommitTransactionReply.class);
1078 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1079 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1084 public void testReadWriteCommitWithPersistenceDisabled() throws Throwable {
1085 testCommitWithPersistenceDisabled(true);
1089 public void testWriteOnlyCommitWithPersistenceDisabled() throws Throwable {
1090 testCommitWithPersistenceDisabled(true);
1093 private void testCommitWithPersistenceDisabled(final boolean readWrite) throws Throwable {
1094 dataStoreContextBuilder.persistent(false);
1095 new ShardTestKit(getSystem()) {{
1096 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1097 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1098 "testCommitWithPersistenceDisabled-" + readWrite);
1100 waitUntilLeader(shard);
1102 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1104 // Setup a simulated transactions with a mock cohort.
1106 final String transactionID = "tx";
1107 final MutableCompositeModification modification = new MutableCompositeModification();
1108 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1109 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
1110 TestModel.TEST_PATH, containerNode, modification);
1112 final FiniteDuration duration = duration("5 seconds");
1114 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1115 expectMsgClass(duration, ReadyTransactionReply.class);
1117 // Send the CanCommitTransaction message.
1119 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1120 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1121 expectMsgClass(duration, CanCommitTransactionReply.class));
1122 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1124 // Send the CanCommitTransaction message.
1126 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1127 expectMsgClass(duration, CommitTransactionReply.class);
1129 final InOrder inOrder = inOrder(cohort);
1130 inOrder.verify(cohort).canCommit();
1131 inOrder.verify(cohort).preCommit();
1132 inOrder.verify(cohort).commit();
1134 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1135 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1140 public void testReadWriteCommitWhenTransactionHasNoModifications() {
1141 testCommitWhenTransactionHasNoModifications(true);
1145 public void testWriteOnlyCommitWhenTransactionHasNoModifications() {
1146 testCommitWhenTransactionHasNoModifications(false);
1149 private void testCommitWhenTransactionHasNoModifications(final boolean readWrite){
1150 // Note that persistence is enabled which would normally result in the entry getting written to the journal
1151 // but here that need not happen
1152 new ShardTestKit(getSystem()) {
1154 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1155 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1156 "testCommitWhenTransactionHasNoModifications-" + readWrite);
1158 waitUntilLeader(shard);
1160 final String transactionID = "tx1";
1161 final MutableCompositeModification modification = new MutableCompositeModification();
1162 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1163 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1164 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1165 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1166 doReturn(mockUnmodifiedCandidate("cohort1-candidate")).when(cohort).getCandidate();
1168 final FiniteDuration duration = duration("5 seconds");
1170 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1171 expectMsgClass(duration, ReadyTransactionReply.class);
1173 // Send the CanCommitTransaction message.
1175 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1176 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1177 expectMsgClass(duration, CanCommitTransactionReply.class));
1178 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1180 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1181 expectMsgClass(duration, CommitTransactionReply.class);
1183 final InOrder inOrder = inOrder(cohort);
1184 inOrder.verify(cohort).canCommit();
1185 inOrder.verify(cohort).preCommit();
1186 inOrder.verify(cohort).commit();
1188 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1189 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1191 // Use MBean for verification
1192 // Committed transaction count should increase as usual
1193 assertEquals(1,shardStats.getCommittedTransactionsCount());
1195 // Commit index should not advance because this does not go into the journal
1196 assertEquals(-1, shardStats.getCommitIndex());
1202 public void testReadWriteCommitWhenTransactionHasModifications() {
1203 testCommitWhenTransactionHasModifications(true);
1207 public void testWriteOnlyCommitWhenTransactionHasModifications() {
1208 testCommitWhenTransactionHasModifications(false);
1211 private void testCommitWhenTransactionHasModifications(final boolean readWrite){
1212 new ShardTestKit(getSystem()) {
1214 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1215 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1216 "testCommitWhenTransactionHasModifications-" + readWrite);
1218 waitUntilLeader(shard);
1220 final String transactionID = "tx1";
1221 final MutableCompositeModification modification = new MutableCompositeModification();
1222 modification.addModification(new DeleteModification(YangInstanceIdentifier.builder().build()));
1223 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1224 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1225 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1226 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1227 doReturn(mockCandidate("cohort1-candidate")).when(cohort).getCandidate();
1229 final FiniteDuration duration = duration("5 seconds");
1231 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1232 expectMsgClass(duration, ReadyTransactionReply.class);
1234 // Send the CanCommitTransaction message.
1236 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1237 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1238 expectMsgClass(duration, CanCommitTransactionReply.class));
1239 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1241 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1242 expectMsgClass(duration, CommitTransactionReply.class);
1244 final InOrder inOrder = inOrder(cohort);
1245 inOrder.verify(cohort).canCommit();
1246 inOrder.verify(cohort).preCommit();
1247 inOrder.verify(cohort).commit();
1249 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1250 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1252 // Use MBean for verification
1253 // Committed transaction count should increase as usual
1254 assertEquals(1, shardStats.getCommittedTransactionsCount());
1256 // Commit index should advance as we do not have an empty modification
1257 assertEquals(0, shardStats.getCommitIndex());
1263 public void testCommitPhaseFailure() throws Throwable {
1264 testCommitPhaseFailure(true);
1265 testCommitPhaseFailure(false);
1268 private void testCommitPhaseFailure(final boolean readWrite) throws Throwable {
1269 new ShardTestKit(getSystem()) {{
1270 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1271 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1272 "testCommitPhaseFailure-" + readWrite);
1274 waitUntilLeader(shard);
1276 // Setup 2 simulated transactions with mock cohorts. The first one fails in the
1279 final String transactionID1 = "tx1";
1280 final MutableCompositeModification modification1 = new MutableCompositeModification();
1281 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1282 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1283 doReturn(Futures.immediateFuture(null)).when(cohort1).preCommit();
1284 doReturn(Futures.immediateFailedFuture(new RuntimeException("mock"))).when(cohort1).commit();
1285 doReturn(mockCandidate("cohort1-candidate")).when(cohort1).getCandidate();
1287 final String transactionID2 = "tx2";
1288 final MutableCompositeModification modification2 = new MutableCompositeModification();
1289 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1290 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1292 final FiniteDuration duration = duration("5 seconds");
1293 final Timeout timeout = new Timeout(duration);
1295 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1296 expectMsgClass(duration, ReadyTransactionReply.class);
1298 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1299 expectMsgClass(duration, ReadyTransactionReply.class);
1301 // Send the CanCommitTransaction message for the first Tx.
1303 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1304 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1305 expectMsgClass(duration, CanCommitTransactionReply.class));
1306 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1308 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1309 // processed after the first Tx completes.
1311 final Future<Object> canCommitFuture = Patterns.ask(shard,
1312 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1314 // Send the CommitTransaction message for the first Tx. This should send back an error
1315 // and trigger the 2nd Tx to proceed.
1317 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1318 expectMsgClass(duration, akka.actor.Status.Failure.class);
1320 // Wait for the 2nd Tx to complete the canCommit phase.
1322 final CountDownLatch latch = new CountDownLatch(1);
1323 canCommitFuture.onComplete(new OnComplete<Object>() {
1325 public void onComplete(final Throwable t, final Object resp) {
1328 }, getSystem().dispatcher());
1330 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1332 final InOrder inOrder = inOrder(cohort1, cohort2);
1333 inOrder.verify(cohort1).canCommit();
1334 inOrder.verify(cohort1).preCommit();
1335 inOrder.verify(cohort1).commit();
1336 inOrder.verify(cohort2).canCommit();
1341 public void testPreCommitPhaseFailure() throws Throwable {
1342 testPreCommitPhaseFailure(true);
1343 testPreCommitPhaseFailure(false);
1346 private void testPreCommitPhaseFailure(final boolean readWrite) throws Throwable {
1347 new ShardTestKit(getSystem()) {{
1348 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1349 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1350 "testPreCommitPhaseFailure-" + readWrite);
1352 waitUntilLeader(shard);
1354 final String transactionID1 = "tx1";
1355 final MutableCompositeModification modification1 = new MutableCompositeModification();
1356 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1357 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1358 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).preCommit();
1360 final String transactionID2 = "tx2";
1361 final MutableCompositeModification modification2 = new MutableCompositeModification();
1362 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1363 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1365 final FiniteDuration duration = duration("5 seconds");
1366 final Timeout timeout = new Timeout(duration);
1368 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1369 expectMsgClass(duration, ReadyTransactionReply.class);
1371 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1372 expectMsgClass(duration, ReadyTransactionReply.class);
1374 // Send the CanCommitTransaction message for the first Tx.
1376 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1377 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1378 expectMsgClass(duration, CanCommitTransactionReply.class));
1379 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1381 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1382 // processed after the first Tx completes.
1384 final Future<Object> canCommitFuture = Patterns.ask(shard,
1385 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1387 // Send the CommitTransaction message for the first Tx. This should send back an error
1388 // and trigger the 2nd Tx to proceed.
1390 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1391 expectMsgClass(duration, akka.actor.Status.Failure.class);
1393 // Wait for the 2nd Tx to complete the canCommit phase.
1395 final CountDownLatch latch = new CountDownLatch(1);
1396 canCommitFuture.onComplete(new OnComplete<Object>() {
1398 public void onComplete(final Throwable t, final Object resp) {
1401 }, getSystem().dispatcher());
1403 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1405 final InOrder inOrder = inOrder(cohort1, cohort2);
1406 inOrder.verify(cohort1).canCommit();
1407 inOrder.verify(cohort1).preCommit();
1408 inOrder.verify(cohort2).canCommit();
1413 public void testCanCommitPhaseFailure() throws Throwable {
1414 testCanCommitPhaseFailure(true);
1415 testCanCommitPhaseFailure(false);
1418 private void testCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1419 new ShardTestKit(getSystem()) {{
1420 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1421 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1422 "testCanCommitPhaseFailure-" + readWrite);
1424 waitUntilLeader(shard);
1426 final FiniteDuration duration = duration("5 seconds");
1428 final String transactionID1 = "tx1";
1429 final MutableCompositeModification modification = new MutableCompositeModification();
1430 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1431 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1433 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1434 expectMsgClass(duration, ReadyTransactionReply.class);
1436 // Send the CanCommitTransaction message.
1438 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1439 expectMsgClass(duration, akka.actor.Status.Failure.class);
1441 // Send another can commit to ensure the failed one got cleaned up.
1445 final String transactionID2 = "tx2";
1446 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1448 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1449 expectMsgClass(duration, ReadyTransactionReply.class);
1451 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1452 final CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1453 expectMsgClass(CanCommitTransactionReply.class));
1454 assertEquals("getCanCommit", true, reply.getCanCommit());
1459 public void testCanCommitPhaseFalseResponse() throws Throwable {
1460 testCanCommitPhaseFalseResponse(true);
1461 testCanCommitPhaseFalseResponse(false);
1464 private void testCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1465 new ShardTestKit(getSystem()) {{
1466 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1467 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1468 "testCanCommitPhaseFalseResponse-" + readWrite);
1470 waitUntilLeader(shard);
1472 final FiniteDuration duration = duration("5 seconds");
1474 final String transactionID1 = "tx1";
1475 final MutableCompositeModification modification = new MutableCompositeModification();
1476 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1477 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1479 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1480 expectMsgClass(duration, ReadyTransactionReply.class);
1482 // Send the CanCommitTransaction message.
1484 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1485 CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1486 expectMsgClass(CanCommitTransactionReply.class));
1487 assertEquals("getCanCommit", false, reply.getCanCommit());
1489 // Send another can commit to ensure the failed one got cleaned up.
1493 final String transactionID2 = "tx2";
1494 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1496 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1497 expectMsgClass(duration, ReadyTransactionReply.class);
1499 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1500 reply = CanCommitTransactionReply.fromSerializable(
1501 expectMsgClass(CanCommitTransactionReply.class));
1502 assertEquals("getCanCommit", true, reply.getCanCommit());
1507 public void testImmediateCommitWithCanCommitPhaseFailure() throws Throwable {
1508 testImmediateCommitWithCanCommitPhaseFailure(true);
1509 testImmediateCommitWithCanCommitPhaseFailure(false);
1512 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1513 new ShardTestKit(getSystem()) {{
1514 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1515 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1516 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1518 waitUntilLeader(shard);
1520 final FiniteDuration duration = duration("5 seconds");
1522 final String transactionID1 = "tx1";
1523 final MutableCompositeModification modification = new MutableCompositeModification();
1524 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1525 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1527 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification, true), getRef());
1529 expectMsgClass(duration, akka.actor.Status.Failure.class);
1531 // Send another can commit to ensure the failed one got cleaned up.
1535 final String transactionID2 = "tx2";
1536 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1537 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1538 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1539 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1540 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1541 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1542 doReturn(candidateRoot).when(candidate).getRootNode();
1543 doReturn(YangInstanceIdentifier.EMPTY).when(candidate).getRootPath();
1544 doReturn(candidate).when(cohort).getCandidate();
1546 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1548 expectMsgClass(duration, CommitTransactionReply.class);
1553 public void testImmediateCommitWithCanCommitPhaseFalseResponse() throws Throwable {
1554 testImmediateCommitWithCanCommitPhaseFalseResponse(true);
1555 testImmediateCommitWithCanCommitPhaseFalseResponse(false);
1558 private void testImmediateCommitWithCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1559 new ShardTestKit(getSystem()) {{
1560 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1561 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1562 "testImmediateCommitWithCanCommitPhaseFalseResponse-" + readWrite);
1564 waitUntilLeader(shard);
1566 final FiniteDuration duration = duration("5 seconds");
1568 final String transactionID = "tx1";
1569 final MutableCompositeModification modification = new MutableCompositeModification();
1570 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1571 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1573 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
1575 expectMsgClass(duration, akka.actor.Status.Failure.class);
1577 // Send another can commit to ensure the failed one got cleaned up.
1581 final String transactionID2 = "tx2";
1582 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1583 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1584 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1585 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1586 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1587 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1588 doReturn(candidateRoot).when(candidate).getRootNode();
1589 doReturn(YangInstanceIdentifier.EMPTY).when(candidate).getRootPath();
1590 doReturn(candidate).when(cohort).getCandidate();
1592 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1594 expectMsgClass(duration, CommitTransactionReply.class);
1599 public void testAbortBeforeFinishCommit() throws Throwable {
1600 testAbortBeforeFinishCommit(true);
1601 testAbortBeforeFinishCommit(false);
1604 private void testAbortBeforeFinishCommit(final boolean readWrite) throws Throwable {
1605 new ShardTestKit(getSystem()) {{
1606 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1607 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1608 "testAbortBeforeFinishCommit-" + readWrite);
1610 waitUntilLeader(shard);
1612 final FiniteDuration duration = duration("5 seconds");
1613 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1615 final String transactionID = "tx1";
1616 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit =
1617 new Function<ShardDataTreeCohort, ListenableFuture<Void>>() {
1619 public ListenableFuture<Void> apply(final ShardDataTreeCohort cohort) {
1620 final ListenableFuture<Void> preCommitFuture = cohort.preCommit();
1622 // Simulate an AbortTransaction message occurring during replication, after
1623 // persisting and before finishing the commit to the in-memory store.
1624 // We have no followers so due to optimizations in the RaftActor, it does not
1625 // attempt replication and thus we can't send an AbortTransaction message b/c
1626 // it would be processed too late after CommitTransaction completes. So we'll
1627 // simulate an AbortTransaction message occurring during replication by calling
1628 // the shard directly.
1630 shard.underlyingActor().doAbortTransaction(transactionID, null);
1632 return preCommitFuture;
1636 final MutableCompositeModification modification = new MutableCompositeModification();
1637 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort1", dataStore,
1638 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME),
1639 modification, preCommit);
1641 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1642 expectMsgClass(duration, ReadyTransactionReply.class);
1644 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1645 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1646 expectMsgClass(duration, CanCommitTransactionReply.class));
1647 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1649 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1650 expectMsgClass(duration, CommitTransactionReply.class);
1652 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1654 // Since we're simulating an abort occurring during replication and before finish commit,
1655 // the data should still get written to the in-memory store since we've gotten past
1656 // canCommit and preCommit and persisted the data.
1657 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1662 public void testTransactionCommitTimeout() throws Throwable {
1663 testTransactionCommitTimeout(true);
1664 testTransactionCommitTimeout(false);
1667 private void testTransactionCommitTimeout(final boolean readWrite) throws Throwable {
1668 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1670 new ShardTestKit(getSystem()) {{
1671 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1672 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1673 "testTransactionCommitTimeout-" + readWrite);
1675 waitUntilLeader(shard);
1677 final FiniteDuration duration = duration("5 seconds");
1679 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1681 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1682 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1683 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1685 // Create 1st Tx - will timeout
1687 final String transactionID1 = "tx1";
1688 final MutableCompositeModification modification1 = new MutableCompositeModification();
1689 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1690 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1691 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1692 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
1697 final String transactionID2 = "tx3";
1698 final MutableCompositeModification modification2 = new MutableCompositeModification();
1699 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1700 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1701 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort3", dataStore,
1703 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2),
1708 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1709 expectMsgClass(duration, ReadyTransactionReply.class);
1711 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1712 expectMsgClass(duration, ReadyTransactionReply.class);
1714 // canCommit 1st Tx. We don't send the commit so it should timeout.
1716 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1717 expectMsgClass(duration, CanCommitTransactionReply.class);
1719 // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1721 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1722 expectMsgClass(duration, CanCommitTransactionReply.class);
1724 // Try to commit the 1st Tx - should fail as it's not the current Tx.
1726 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1727 expectMsgClass(duration, akka.actor.Status.Failure.class);
1729 // Commit the 2nd Tx.
1731 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1732 expectMsgClass(duration, CommitTransactionReply.class);
1734 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1735 assertNotNull(listNodePath + " not found", node);
1740 public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1741 dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1743 new ShardTestKit(getSystem()) {{
1744 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1745 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1746 "testTransactionCommitQueueCapacityExceeded");
1748 waitUntilLeader(shard);
1750 final FiniteDuration duration = duration("5 seconds");
1752 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1754 final String transactionID1 = "tx1";
1755 final MutableCompositeModification modification1 = new MutableCompositeModification();
1756 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1757 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1759 final String transactionID2 = "tx2";
1760 final MutableCompositeModification modification2 = new MutableCompositeModification();
1761 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1762 TestModel.OUTER_LIST_PATH,
1763 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
1766 final String transactionID3 = "tx3";
1767 final MutableCompositeModification modification3 = new MutableCompositeModification();
1768 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1769 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification3);
1773 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1774 expectMsgClass(duration, ReadyTransactionReply.class);
1776 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1777 expectMsgClass(duration, ReadyTransactionReply.class);
1779 // The 3rd Tx should exceed queue capacity and fail.
1781 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1782 expectMsgClass(duration, akka.actor.Status.Failure.class);
1784 // canCommit 1st Tx.
1786 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1787 expectMsgClass(duration, CanCommitTransactionReply.class);
1789 // canCommit the 2nd Tx - it should get queued.
1791 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1793 // canCommit the 3rd Tx - should exceed queue capacity and fail.
1795 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1796 expectMsgClass(duration, akka.actor.Status.Failure.class);
1801 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Throwable {
1802 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1804 new ShardTestKit(getSystem()) {{
1805 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1806 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1807 "testTransactionCommitWithPriorExpiredCohortEntries");
1809 waitUntilLeader(shard);
1811 final FiniteDuration duration = duration("5 seconds");
1813 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1815 final String transactionID1 = "tx1";
1816 final MutableCompositeModification modification1 = new MutableCompositeModification();
1817 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1818 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1820 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1821 expectMsgClass(duration, ReadyTransactionReply.class);
1823 final String transactionID2 = "tx2";
1824 final MutableCompositeModification modification2 = new MutableCompositeModification();
1825 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1826 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1828 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1829 expectMsgClass(duration, ReadyTransactionReply.class);
1831 final String transactionID3 = "tx3";
1832 final MutableCompositeModification modification3 = new MutableCompositeModification();
1833 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1834 TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME), modification3);
1836 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1837 expectMsgClass(duration, ReadyTransactionReply.class);
1839 // All Tx's are readied. We'll send canCommit for the last one but not the others. The others
1840 // should expire from the queue and the last one should be processed.
1842 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1843 expectMsgClass(duration, CanCommitTransactionReply.class);
1848 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Throwable {
1849 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1851 new ShardTestKit(getSystem()) {{
1852 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1853 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1854 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1856 waitUntilLeader(shard);
1858 final FiniteDuration duration = duration("5 seconds");
1860 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1862 final String transactionID1 = "tx1";
1863 final MutableCompositeModification modification1 = new MutableCompositeModification();
1864 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1865 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1867 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1868 expectMsgClass(duration, ReadyTransactionReply.class);
1870 // CanCommit the first one so it's the current in-progress CohortEntry.
1872 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1873 expectMsgClass(duration, CanCommitTransactionReply.class);
1875 // Ready the second Tx.
1877 final String transactionID2 = "tx2";
1878 final MutableCompositeModification modification2 = new MutableCompositeModification();
1879 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1880 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1882 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1883 expectMsgClass(duration, ReadyTransactionReply.class);
1885 // Ready the third Tx.
1887 final String transactionID3 = "tx3";
1888 final DataTreeModification modification3 = dataStore.newModification();
1889 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1890 .apply(modification3);
1891 modification3.ready();
1892 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3, true);
1894 shard.tell(readyMessage, getRef());
1896 // Commit the first Tx. After completing, the second should expire from the queue and the third
1899 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1900 expectMsgClass(duration, CommitTransactionReply.class);
1902 // Expect commit reply from the third Tx.
1904 expectMsgClass(duration, CommitTransactionReply.class);
1906 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1907 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1912 public void testCanCommitBeforeReadyFailure() throws Throwable {
1913 new ShardTestKit(getSystem()) {{
1914 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1915 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1916 "testCanCommitBeforeReadyFailure");
1918 shard.tell(new CanCommitTransaction("tx", CURRENT_VERSION).toSerializable(), getRef());
1919 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1924 public void testAbortCurrentTransaction() throws Throwable {
1925 testAbortCurrentTransaction(true);
1926 testAbortCurrentTransaction(false);
1929 private void testAbortCurrentTransaction(final boolean readWrite) throws Throwable {
1930 new ShardTestKit(getSystem()) {{
1931 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1932 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1933 "testAbortCurrentTransaction-" + readWrite);
1935 waitUntilLeader(shard);
1937 // Setup 2 simulated transactions with mock cohorts. The first one will be aborted.
1939 final String transactionID1 = "tx1";
1940 final MutableCompositeModification modification1 = new MutableCompositeModification();
1941 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1942 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1943 doReturn(Futures.immediateFuture(null)).when(cohort1).abort();
1945 final String transactionID2 = "tx2";
1946 final MutableCompositeModification modification2 = new MutableCompositeModification();
1947 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1948 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1950 final FiniteDuration duration = duration("5 seconds");
1951 final Timeout timeout = new Timeout(duration);
1953 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1954 expectMsgClass(duration, ReadyTransactionReply.class);
1956 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1957 expectMsgClass(duration, ReadyTransactionReply.class);
1959 // Send the CanCommitTransaction message for the first Tx.
1961 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1962 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1963 expectMsgClass(duration, CanCommitTransactionReply.class));
1964 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1966 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1967 // processed after the first Tx completes.
1969 final Future<Object> canCommitFuture = Patterns.ask(shard,
1970 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1972 // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1975 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1976 expectMsgClass(duration, AbortTransactionReply.class);
1978 // Wait for the 2nd Tx to complete the canCommit phase.
1980 Await.ready(canCommitFuture, duration);
1982 final InOrder inOrder = inOrder(cohort1, cohort2);
1983 inOrder.verify(cohort1).canCommit();
1984 inOrder.verify(cohort2).canCommit();
1989 public void testAbortQueuedTransaction() throws Throwable {
1990 testAbortQueuedTransaction(true);
1991 testAbortQueuedTransaction(false);
1994 private void testAbortQueuedTransaction(final boolean readWrite) throws Throwable {
1995 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1996 new ShardTestKit(getSystem()) {{
1997 final AtomicReference<CountDownLatch> cleaupCheckLatch = new AtomicReference<>();
1998 @SuppressWarnings("serial")
1999 final Creator<Shard> creator = new Creator<Shard>() {
2001 public Shard create() throws Exception {
2002 return new Shard(newShardBuilder()) {
2004 public void handleCommand(final Object message) {
2005 super.handleCommand(message);
2006 if(TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
2007 if(cleaupCheckLatch.get() != null) {
2008 cleaupCheckLatch.get().countDown();
2016 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2017 Props.create(new DelegatingShardCreator(creator)).withDispatcher(
2018 Dispatchers.DefaultDispatcherId()), "testAbortQueuedTransaction-" + readWrite);
2020 waitUntilLeader(shard);
2022 final String transactionID = "tx1";
2024 final MutableCompositeModification modification = new MutableCompositeModification();
2025 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort");
2026 doReturn(Futures.immediateFuture(null)).when(cohort).abort();
2028 final FiniteDuration duration = duration("5 seconds");
2032 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
2033 expectMsgClass(duration, ReadyTransactionReply.class);
2035 assertEquals("getPendingTxCommitQueueSize", 1, shard.underlyingActor().getPendingTxCommitQueueSize());
2037 // Send the AbortTransaction message.
2039 shard.tell(new AbortTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2040 expectMsgClass(duration, AbortTransactionReply.class);
2042 verify(cohort).abort();
2044 // Verify the tx cohort is removed from queue at the cleanup check interval.
2046 cleaupCheckLatch.set(new CountDownLatch(1));
2047 assertEquals("TX_COMMIT_TIMEOUT_CHECK_MESSAGE received", true,
2048 cleaupCheckLatch.get().await(5, TimeUnit.SECONDS));
2050 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
2052 // Now send CanCommitTransaction - should fail.
2054 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2056 Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
2057 assertTrue("Failure type", failure instanceof IllegalStateException);
2062 public void testCreateSnapshot() throws Exception {
2063 testCreateSnapshot(true, "testCreateSnapshot");
2067 public void testCreateSnapshotWithNonPersistentData() throws Exception {
2068 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
2071 @SuppressWarnings("serial")
2072 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
2074 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
2076 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
2077 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
2078 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
2083 public void saveSnapshot(final Object o) {
2084 savedSnapshot.set(o);
2085 super.saveSnapshot(o);
2089 dataStoreContextBuilder.persistent(persistent);
2091 new ShardTestKit(getSystem()) {{
2092 class TestShard extends Shard {
2094 protected TestShard(AbstractBuilder<?, ?> builder) {
2096 setPersistence(new TestPersistentDataProvider(super.persistence()));
2100 public void handleCommand(final Object message) {
2101 super.handleCommand(message);
2103 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
2104 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
2105 latch.get().countDown();
2110 public RaftActorContext getRaftActorContext() {
2111 return super.getRaftActorContext();
2115 final Creator<Shard> creator = new Creator<Shard>() {
2117 public Shard create() throws Exception {
2118 return new TestShard(newShardBuilder());
2122 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2123 Props.create(new DelegatingShardCreator(creator)), shardActorName);
2125 waitUntilLeader(shard);
2126 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2128 final NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.builder().build());
2130 // Trigger creation of a snapshot by ensuring
2131 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
2132 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2133 awaitAndValidateSnapshot(expectedRoot);
2135 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2136 awaitAndValidateSnapshot(expectedRoot);
2139 private void awaitAndValidateSnapshot(NormalizedNode<?,?> expectedRoot) throws InterruptedException {
2140 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
2142 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
2143 savedSnapshot.get() instanceof Snapshot);
2145 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
2147 latch.set(new CountDownLatch(1));
2148 savedSnapshot.set(null);
2151 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?,?> expectedRoot) {
2153 final NormalizedNode<?, ?> actual = SerializationUtils.deserializeNormalizedNode(snapshot.getState());
2154 assertEquals("Root node", expectedRoot, actual);
2160 * This test simply verifies that the applySnapShot logic will work
2161 * @throws ReadFailedException
2162 * @throws DataValidationFailedException
2165 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
2166 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
2167 store.setSchemaContext(SCHEMA_CONTEXT);
2169 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
2170 putTransaction.write(TestModel.TEST_PATH,
2171 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2172 commitTransaction(store, putTransaction);
2175 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.builder().build());
2177 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2179 writeTransaction.delete(YangInstanceIdentifier.builder().build());
2180 writeTransaction.write(YangInstanceIdentifier.builder().build(), expected);
2182 commitTransaction(store, writeTransaction);
2184 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.builder().build());
2186 assertEquals(expected, actual);
2190 public void testRecoveryApplicable(){
2192 final DatastoreContext persistentContext = DatastoreContext.newBuilder().
2193 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2195 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext).
2196 schemaContext(SCHEMA_CONTEXT).props();
2198 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
2199 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2201 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext).
2202 schemaContext(SCHEMA_CONTEXT).props();
2204 new ShardTestKit(getSystem()) {{
2205 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2207 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2209 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2211 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2216 public void testOnDatastoreContext() {
2217 new ShardTestKit(getSystem()) {{
2218 dataStoreContextBuilder.persistent(true);
2220 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
2222 assertEquals("isRecoveryApplicable", true,
2223 shard.underlyingActor().persistence().isRecoveryApplicable());
2225 waitUntilLeader(shard);
2227 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2229 assertEquals("isRecoveryApplicable", false,
2230 shard.underlyingActor().persistence().isRecoveryApplicable());
2232 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2234 assertEquals("isRecoveryApplicable", true,
2235 shard.underlyingActor().persistence().isRecoveryApplicable());
2240 public void testRegisterRoleChangeListener() throws Exception {
2241 new ShardTestKit(getSystem()) {
2243 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2244 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2245 "testRegisterRoleChangeListener");
2247 waitUntilLeader(shard);
2249 final TestActorRef<MessageCollectorActor> listener =
2250 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2252 shard.tell(new RegisterRoleChangeListener(), listener);
2254 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2256 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2257 ShardLeaderStateChanged.class);
2258 assertEquals("getLocalShardDataTree present", true,
2259 leaderStateChanged.getLocalShardDataTree().isPresent());
2260 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2261 leaderStateChanged.getLocalShardDataTree().get());
2263 MessageCollectorActor.clearMessages(listener);
2265 // Force a leader change
2267 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2269 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2270 ShardLeaderStateChanged.class);
2271 assertEquals("getLocalShardDataTree present", false,
2272 leaderStateChanged.getLocalShardDataTree().isPresent());
2278 public void testFollowerInitialSyncStatus() throws Exception {
2279 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2280 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2281 "testFollowerInitialSyncStatus");
2283 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
2285 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2287 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
2289 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2293 public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
2294 new ShardTestKit(getSystem()) {{
2295 String testName = "testClusteredDataChangeListenerDelayedRegistration";
2296 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2297 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2299 final MockDataChangeListener listener = new MockDataChangeListener(1);
2300 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2301 actorFactory.generateActorId(testName + "-DataChangeListener"));
2303 setupInMemorySnapshotStore();
2305 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2306 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2307 actorFactory.generateActorId(testName + "-shard"));
2309 waitUntilNoLeader(shard);
2311 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2313 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2314 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2315 RegisterChangeListenerReply.class);
2316 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2318 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2319 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2321 listener.waitForChangeEvents();
2326 public void testClusteredDataChangeListenerRegistration() throws Exception {
2327 new ShardTestKit(getSystem()) {{
2328 String testName = "testClusteredDataChangeListenerRegistration";
2329 final ShardIdentifier followerShardID = ShardIdentifier.builder().memberName(
2330 actorFactory.generateActorId(testName + "-follower")).shardName("inventory").type("config").build();
2332 final ShardIdentifier leaderShardID = ShardIdentifier.builder().memberName(
2333 actorFactory.generateActorId(testName + "-leader")).shardName("inventory").type("config").build();
2335 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2336 Shard.builder().id(followerShardID).
2337 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2338 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2339 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2340 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2342 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2343 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2344 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2345 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2346 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2348 leaderShard.tell(ElectionTimeout.INSTANCE, ActorRef.noSender());
2349 String leaderPath = waitUntilLeader(followerShard);
2350 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2352 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2353 final MockDataChangeListener listener = new MockDataChangeListener(1);
2354 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2355 actorFactory.generateActorId(testName + "-DataChangeListener"));
2357 followerShard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2358 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2359 RegisterChangeListenerReply.class);
2360 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2362 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2364 listener.waitForChangeEvents();
2369 public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
2370 new ShardTestKit(getSystem()) {{
2371 String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
2372 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2373 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2375 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2376 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2377 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2379 setupInMemorySnapshotStore();
2381 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2382 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2383 actorFactory.generateActorId(testName + "-shard"));
2385 waitUntilNoLeader(shard);
2387 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2389 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2390 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2391 RegisterDataTreeChangeListenerReply.class);
2392 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2394 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2395 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2397 listener.waitForChangeEvents();
2402 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2403 new ShardTestKit(getSystem()) {{
2404 String testName = "testClusteredDataTreeChangeListenerRegistration";
2405 final ShardIdentifier followerShardID = ShardIdentifier.builder().memberName(
2406 actorFactory.generateActorId(testName + "-follower")).shardName("inventory").type("config").build();
2408 final ShardIdentifier leaderShardID = ShardIdentifier.builder().memberName(
2409 actorFactory.generateActorId(testName + "-leader")).shardName("inventory").type("config").build();
2411 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2412 Shard.builder().id(followerShardID).
2413 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2414 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2415 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2416 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2418 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2419 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2420 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2421 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2422 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2424 leaderShard.tell(ElectionTimeout.INSTANCE, ActorRef.noSender());
2425 String leaderPath = waitUntilLeader(followerShard);
2426 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2428 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2429 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2430 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2431 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2433 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2434 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2435 RegisterDataTreeChangeListenerReply.class);
2436 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2438 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2440 listener.waitForChangeEvents();
2445 public void testServerRemoved() throws Exception {
2446 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2448 final ActorRef shard = parent.underlyingActor().context().actorOf(
2449 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2450 "testServerRemoved");
2452 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2454 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);