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;
23 import akka.actor.ActorRef;
24 import akka.actor.ActorSelection;
25 import akka.actor.Props;
26 import akka.actor.Status.Failure;
27 import akka.dispatch.Dispatchers;
28 import akka.dispatch.OnComplete;
29 import akka.japi.Creator;
30 import akka.pattern.Patterns;
31 import akka.persistence.SaveSnapshotSuccess;
32 import akka.testkit.TestActorRef;
33 import akka.util.Timeout;
34 import com.google.common.base.Function;
35 import com.google.common.base.Stopwatch;
36 import com.google.common.util.concurrent.Futures;
37 import com.google.common.util.concurrent.ListenableFuture;
38 import com.google.common.util.concurrent.Uninterruptibles;
39 import java.util.Collections;
40 import java.util.HashSet;
42 import java.util.concurrent.CountDownLatch;
43 import java.util.concurrent.TimeUnit;
44 import java.util.concurrent.atomic.AtomicBoolean;
45 import java.util.concurrent.atomic.AtomicReference;
46 import org.junit.Test;
47 import org.mockito.InOrder;
48 import org.opendaylight.controller.cluster.DataPersistenceProvider;
49 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
50 import org.opendaylight.controller.cluster.access.concepts.MemberName;
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.util.StringIdentifier;
106 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
107 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
108 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
109 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
110 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
111 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
113 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
114 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
117 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
118 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
119 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
120 import scala.concurrent.Await;
121 import scala.concurrent.Future;
122 import scala.concurrent.duration.FiniteDuration;
124 public class ShardTest extends AbstractShardTest {
125 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";
128 public void testRegisterChangeListener() throws Exception {
129 new ShardTestKit(getSystem()) {{
130 final TestActorRef<Shard> shard = actorFactory.createTestActor(
131 newShardProps(), "testRegisterChangeListener");
133 waitUntilLeader(shard);
135 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
137 final MockDataChangeListener listener = new MockDataChangeListener(1);
138 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
139 "testRegisterChangeListener-DataChangeListener");
141 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
142 dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
144 final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
145 RegisterChangeListenerReply.class);
146 final String replyPath = reply.getListenerRegistrationPath().toString();
147 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
148 "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
150 final YangInstanceIdentifier path = TestModel.TEST_PATH;
151 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
153 listener.waitForChangeEvents(path);
157 @SuppressWarnings("serial")
159 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
160 // This test tests the timing window in which a change listener is registered before the
161 // shard becomes the leader. We verify that the listener is registered and notified of the
162 // existing data when the shard becomes the leader.
163 new ShardTestKit(getSystem()) {{
164 // For this test, we want to send the RegisterChangeListener message after the shard
165 // has recovered from persistence and before it becomes the leader. So we subclass
166 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
167 // we know that the shard has been initialized to a follower and has started the
168 // election process. The following 2 CountDownLatches are used to coordinate the
169 // ElectionTimeout with the sending of the RegisterChangeListener message.
170 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
171 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
172 final Creator<Shard> creator = new Creator<Shard>() {
173 boolean firstElectionTimeout = true;
176 public Shard create() throws Exception {
177 // Use a non persistent provider because this test actually invokes persist on the journal
178 // this will cause all other messages to not be queued properly after that.
179 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
180 // it does do a persist)
181 return new Shard(newShardBuilder()) {
183 public void handleCommand(final Object message) {
184 if(message instanceof ElectionTimeout && firstElectionTimeout) {
185 // Got the first ElectionTimeout. We don't forward it to the
186 // base Shard yet until we've sent the RegisterChangeListener
187 // message. So we signal the onFirstElectionTimeout latch to tell
188 // the main thread to send the RegisterChangeListener message and
189 // start a thread to wait on the onChangeListenerRegistered latch,
190 // which the main thread signals after it has sent the message.
191 // After the onChangeListenerRegistered is triggered, we send the
192 // original ElectionTimeout message to proceed with the election.
193 firstElectionTimeout = false;
194 final ActorRef self = getSelf();
198 Uninterruptibles.awaitUninterruptibly(
199 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
200 self.tell(message, self);
204 onFirstElectionTimeout.countDown();
206 super.handleCommand(message);
213 setupInMemorySnapshotStore();
215 final MockDataChangeListener listener = new MockDataChangeListener(1);
216 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
217 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
219 final TestActorRef<Shard> shard = actorFactory.createTestActor(
220 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
221 "testRegisterChangeListenerWhenNotLeaderInitially");
223 final YangInstanceIdentifier path = TestModel.TEST_PATH;
225 // Wait until the shard receives the first ElectionTimeout message.
226 assertEquals("Got first ElectionTimeout", true,
227 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
229 // Now send the RegisterChangeListener and wait for the reply.
230 shard.tell(new RegisterChangeListener(path, dclActor,
231 AsyncDataBroker.DataChangeScope.SUBTREE, false), getRef());
233 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
234 RegisterChangeListenerReply.class);
235 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
237 // Sanity check - verify the shard is not the leader yet.
238 shard.tell(FindLeader.INSTANCE, getRef());
239 final FindLeaderReply findLeadeReply =
240 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
241 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
243 // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
244 // with the election process.
245 onChangeListenerRegistered.countDown();
247 // Wait for the shard to become the leader and notify our listener with the existing
248 // data in the store.
249 listener.waitForChangeEvents(path);
254 public void testRegisterDataTreeChangeListener() throws Exception {
255 new ShardTestKit(getSystem()) {{
256 final TestActorRef<Shard> shard = actorFactory.createTestActor(
257 newShardProps(), "testRegisterDataTreeChangeListener");
259 waitUntilLeader(shard);
261 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
263 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
264 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
265 "testRegisterDataTreeChangeListener-DataTreeChangeListener");
267 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
269 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
270 RegisterDataTreeChangeListenerReply.class);
271 final String replyPath = reply.getListenerRegistrationPath().toString();
272 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
273 "akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
275 final YangInstanceIdentifier path = TestModel.TEST_PATH;
276 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
278 listener.waitForChangeEvents();
282 @SuppressWarnings("serial")
284 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
285 new ShardTestKit(getSystem()) {{
286 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
287 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
288 final Creator<Shard> creator = new Creator<Shard>() {
289 boolean firstElectionTimeout = true;
292 public Shard create() throws Exception {
293 return new Shard(newShardBuilder()) {
295 public void handleCommand(final Object message) {
296 if(message instanceof ElectionTimeout && firstElectionTimeout) {
297 firstElectionTimeout = false;
298 final ActorRef self = getSelf();
302 Uninterruptibles.awaitUninterruptibly(
303 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
304 self.tell(message, self);
308 onFirstElectionTimeout.countDown();
310 super.handleCommand(message);
317 setupInMemorySnapshotStore();
319 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
320 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
321 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
323 final TestActorRef<Shard> shard = actorFactory.createTestActor(
324 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
325 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
327 final YangInstanceIdentifier path = TestModel.TEST_PATH;
329 assertEquals("Got first ElectionTimeout", true,
330 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
332 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
333 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
334 RegisterDataTreeChangeListenerReply.class);
335 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
337 shard.tell(FindLeader.INSTANCE, getRef());
338 final FindLeaderReply findLeadeReply =
339 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
340 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
343 onChangeListenerRegistered.countDown();
345 // TODO: investigate why we do not receive data chage events
346 listener.waitForChangeEvents();
351 public void testCreateTransaction(){
352 new ShardTestKit(getSystem()) {{
353 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
355 waitUntilLeader(shard);
357 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
359 shard.tell(new CreateTransaction("txn-1", TransactionType.READ_ONLY.ordinal(), null,
360 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
362 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
363 CreateTransactionReply.class);
365 final String path = reply.getTransactionPath().toString();
366 assertTrue("Unexpected transaction path " + path,
367 path.contains("akka://test/user/testCreateTransaction/shard-txn-1"));
372 public void testCreateTransactionOnChain(){
373 new ShardTestKit(getSystem()) {{
374 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
376 waitUntilLeader(shard);
378 shard.tell(new CreateTransaction("txn-1",TransactionType.READ_ONLY.ordinal(), "foobar",
379 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
381 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
382 CreateTransactionReply.class);
384 final String path = reply.getTransactionPath().toString();
385 assertTrue("Unexpected transaction path " + path,
386 path.contains("akka://test/user/testCreateTransactionOnChain/shard-txn-1"));
391 public void testPeerAddressResolved() throws Exception {
392 new ShardTestKit(getSystem()) {{
393 ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"), "config");
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.EMPTY;
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, new StringIdentifier("test"),
450 new ReplicatedLogImplEntry(1, 2, 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 = (txID, actual) -> {
683 if(mockCohort.get() == null) {
684 mockCohort.set(createDelegatingMockCohort("cohort", actual));
687 return mockCohort.get();
690 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
692 // Send a BatchedModifications to start a transaction.
694 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
695 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
696 expectMsgClass(duration, BatchedModificationsReply.class);
698 // Send a couple more BatchedModifications.
700 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
701 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
702 expectMsgClass(duration, BatchedModificationsReply.class);
704 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
705 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
706 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3), getRef());
707 expectMsgClass(duration, ReadyTransactionReply.class);
709 // Send the CanCommitTransaction message.
711 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
712 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
713 expectMsgClass(duration, CanCommitTransactionReply.class));
714 assertEquals("Can commit", true, canCommitReply.getCanCommit());
716 // Send the CanCommitTransaction message.
718 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
719 expectMsgClass(duration, CommitTransactionReply.class);
721 final InOrder inOrder = inOrder(mockCohort.get());
722 inOrder.verify(mockCohort.get()).canCommit();
723 inOrder.verify(mockCohort.get()).preCommit();
724 inOrder.verify(mockCohort.get()).commit();
726 // Verify data in the data store.
728 verifyOuterListEntry(shard, 1);
733 public void testBatchedModificationsWithCommitOnReady() throws Throwable {
734 new ShardTestKit(getSystem()) {{
735 final TestActorRef<Shard> shard = actorFactory.createTestActor(
736 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
737 "testBatchedModificationsWithCommitOnReady");
739 waitUntilLeader(shard);
741 final String transactionID = "tx";
742 final FiniteDuration duration = duration("5 seconds");
744 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
745 final ShardCommitCoordinator.CohortDecorator cohortDecorator = (txID, actual) -> {
746 if(mockCohort.get() == null) {
747 mockCohort.set(createDelegatingMockCohort("cohort", actual));
750 return mockCohort.get();
753 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
755 // Send a BatchedModifications to start a transaction.
757 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
758 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
759 expectMsgClass(duration, BatchedModificationsReply.class);
761 // Send a couple more BatchedModifications.
763 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
764 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
765 expectMsgClass(duration, BatchedModificationsReply.class);
767 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
768 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
769 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3), getRef());
771 expectMsgClass(duration, CommitTransactionReply.class);
773 final InOrder inOrder = inOrder(mockCohort.get());
774 inOrder.verify(mockCohort.get()).canCommit();
775 inOrder.verify(mockCohort.get()).preCommit();
776 inOrder.verify(mockCohort.get()).commit();
778 // Verify data in the data store.
780 verifyOuterListEntry(shard, 1);
784 @Test(expected=IllegalStateException.class)
785 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Throwable {
786 new ShardTestKit(getSystem()) {{
787 final TestActorRef<Shard> shard = actorFactory.createTestActor(
788 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
789 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
791 waitUntilLeader(shard);
793 final String transactionID = "tx1";
794 final BatchedModifications batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION, null);
795 batched.setReady(true);
796 batched.setTotalMessagesSent(2);
798 shard.tell(batched, getRef());
800 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
802 if(failure != null) {
803 throw failure.cause();
809 public void testBatchedModificationsWithOperationFailure() throws Throwable {
810 new ShardTestKit(getSystem()) {{
811 final TestActorRef<Shard> shard = actorFactory.createTestActor(
812 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
813 "testBatchedModificationsWithOperationFailure");
815 waitUntilLeader(shard);
817 // Test merge with invalid data. An exception should occur when the merge is applied. Note that
818 // write will not validate the children for performance reasons.
820 String transactionID = "tx1";
822 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
823 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
824 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
826 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, null);
827 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
828 shard.tell(batched, getRef());
829 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
831 Throwable cause = failure.cause();
833 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION, null);
834 batched.setReady(true);
835 batched.setTotalMessagesSent(2);
837 shard.tell(batched, getRef());
839 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
840 assertEquals("Failure cause", cause, failure.cause());
845 public void testBatchedModificationsOnTransactionChain() throws Throwable {
846 new ShardTestKit(getSystem()) {{
847 final TestActorRef<Shard> shard = actorFactory.createTestActor(
848 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
849 "testBatchedModificationsOnTransactionChain");
851 waitUntilLeader(shard);
853 final String transactionChainID = "txChain";
854 final String transactionID1 = "tx1";
855 final String transactionID2 = "tx2";
857 final FiniteDuration duration = duration("5 seconds");
859 // Send a BatchedModifications to start a chained write transaction and ready it.
861 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
862 final YangInstanceIdentifier path = TestModel.TEST_PATH;
863 shard.tell(newBatchedModifications(transactionID1, transactionChainID, path,
864 containerNode, true, false, 1), getRef());
865 expectMsgClass(duration, ReadyTransactionReply.class);
867 // Create a read Tx on the same chain.
869 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
870 transactionChainID, DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
872 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
874 getSystem().actorSelection(createReply.getTransactionPath()).tell(
875 new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
876 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
877 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
879 // Commit the write transaction.
881 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
882 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
883 expectMsgClass(duration, CanCommitTransactionReply.class));
884 assertEquals("Can commit", true, canCommitReply.getCanCommit());
886 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
887 expectMsgClass(duration, CommitTransactionReply.class);
889 // Verify data in the data store.
891 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
892 assertEquals("Stored node", containerNode, actualNode);
897 public void testOnBatchedModificationsWhenNotLeader() {
898 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
899 new ShardTestKit(getSystem()) {{
900 final Creator<Shard> creator = new Creator<Shard>() {
901 private static final long serialVersionUID = 1L;
904 public Shard create() throws Exception {
905 return new Shard(newShardBuilder()) {
907 protected boolean isLeader() {
908 return overrideLeaderCalls.get() ? false : super.isLeader();
912 protected ActorSelection getLeader() {
913 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
920 final TestActorRef<Shard> shard = actorFactory.createTestActor(
921 Props.create(new DelegatingShardCreator(creator)), "testOnBatchedModificationsWhenNotLeader");
923 waitUntilLeader(shard);
925 overrideLeaderCalls.set(true);
927 final BatchedModifications batched = new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, "");
929 shard.tell(batched, ActorRef.noSender());
931 expectMsgEquals(batched);
936 public void testTransactionMessagesWithNoLeader() {
937 new ShardTestKit(getSystem()) {{
938 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
939 shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
940 final TestActorRef<Shard> shard = actorFactory.createTestActor(
941 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
942 "testTransactionMessagesWithNoLeader");
944 waitUntilNoLeader(shard);
946 shard.tell(new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, ""), getRef());
947 Failure failure = expectMsgClass(Failure.class);
948 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
950 shard.tell(prepareForwardedReadyTransaction(mock(ShardDataTreeCohort.class), "tx",
951 DataStoreVersions.CURRENT_VERSION, true), getRef());
952 failure = expectMsgClass(Failure.class);
953 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
955 shard.tell(new ReadyLocalTransaction("tx", mock(DataTreeModification.class), true), getRef());
956 failure = expectMsgClass(Failure.class);
957 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
962 public void testReadyWithReadWriteImmediateCommit() throws Exception{
963 testReadyWithImmediateCommit(true);
967 public void testReadyWithWriteOnlyImmediateCommit() throws Exception{
968 testReadyWithImmediateCommit(false);
971 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception{
972 new ShardTestKit(getSystem()) {{
973 final TestActorRef<Shard> shard = actorFactory.createTestActor(
974 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
975 "testReadyWithImmediateCommit-" + readWrite);
977 waitUntilLeader(shard);
979 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
981 final String transactionID = "tx1";
982 final MutableCompositeModification modification = new MutableCompositeModification();
983 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
984 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
985 TestModel.TEST_PATH, containerNode, modification);
987 final FiniteDuration duration = duration("5 seconds");
989 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
991 expectMsgClass(duration, CommitTransactionReply.class);
993 final InOrder inOrder = inOrder(cohort);
994 inOrder.verify(cohort).canCommit();
995 inOrder.verify(cohort).preCommit();
996 inOrder.verify(cohort).commit();
998 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
999 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1004 public void testReadyLocalTransactionWithImmediateCommit() throws Exception{
1005 new ShardTestKit(getSystem()) {{
1006 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1007 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1008 "testReadyLocalTransactionWithImmediateCommit");
1010 waitUntilLeader(shard);
1012 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1014 final DataTreeModification modification = dataStore.newModification();
1016 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1017 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1018 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1019 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1021 final String txId = "tx1";
1022 modification.ready();
1023 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1025 shard.tell(readyMessage, getRef());
1027 expectMsgClass(CommitTransactionReply.class);
1029 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1030 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1035 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception{
1036 new ShardTestKit(getSystem()) {{
1037 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1038 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1039 "testReadyLocalTransactionWithThreePhaseCommit");
1041 waitUntilLeader(shard);
1043 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1045 final DataTreeModification modification = dataStore.newModification();
1047 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1048 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1049 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1050 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1052 final String txId = "tx1";
1053 modification.ready();
1054 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1056 shard.tell(readyMessage, getRef());
1058 expectMsgClass(ReadyTransactionReply.class);
1060 // Send the CanCommitTransaction message.
1062 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1063 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1064 expectMsgClass(CanCommitTransactionReply.class));
1065 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1067 // Send the CanCommitTransaction message.
1069 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1070 expectMsgClass(CommitTransactionReply.class);
1072 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1073 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1078 public void testReadWriteCommitWithPersistenceDisabled() throws Throwable {
1079 testCommitWithPersistenceDisabled(true);
1083 public void testWriteOnlyCommitWithPersistenceDisabled() throws Throwable {
1084 testCommitWithPersistenceDisabled(true);
1087 private void testCommitWithPersistenceDisabled(final boolean readWrite) throws Throwable {
1088 dataStoreContextBuilder.persistent(false);
1089 new ShardTestKit(getSystem()) {{
1090 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1091 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1092 "testCommitWithPersistenceDisabled-" + readWrite);
1094 waitUntilLeader(shard);
1096 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1098 // Setup a simulated transactions with a mock cohort.
1100 final String transactionID = "tx";
1101 final MutableCompositeModification modification = new MutableCompositeModification();
1102 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1103 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
1104 TestModel.TEST_PATH, containerNode, modification);
1106 final FiniteDuration duration = duration("5 seconds");
1108 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1109 expectMsgClass(duration, ReadyTransactionReply.class);
1111 // Send the CanCommitTransaction message.
1113 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1114 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1115 expectMsgClass(duration, CanCommitTransactionReply.class));
1116 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1118 // Send the CanCommitTransaction message.
1120 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1121 expectMsgClass(duration, CommitTransactionReply.class);
1123 final InOrder inOrder = inOrder(cohort);
1124 inOrder.verify(cohort).canCommit();
1125 inOrder.verify(cohort).preCommit();
1126 inOrder.verify(cohort).commit();
1128 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1129 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1134 public void testReadWriteCommitWhenTransactionHasNoModifications() {
1135 testCommitWhenTransactionHasNoModifications(true);
1139 public void testWriteOnlyCommitWhenTransactionHasNoModifications() {
1140 testCommitWhenTransactionHasNoModifications(false);
1143 private void testCommitWhenTransactionHasNoModifications(final boolean readWrite){
1144 // Note that persistence is enabled which would normally result in the entry getting written to the journal
1145 // but here that need not happen
1146 new ShardTestKit(getSystem()) {
1148 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1149 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1150 "testCommitWhenTransactionHasNoModifications-" + readWrite);
1152 waitUntilLeader(shard);
1154 final String transactionID = "tx1";
1155 final MutableCompositeModification modification = new MutableCompositeModification();
1156 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1157 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1158 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1159 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1160 doReturn(mockUnmodifiedCandidate("cohort1-candidate")).when(cohort).getCandidate();
1162 final FiniteDuration duration = duration("5 seconds");
1164 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1165 expectMsgClass(duration, ReadyTransactionReply.class);
1167 // Send the CanCommitTransaction message.
1169 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1170 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1171 expectMsgClass(duration, CanCommitTransactionReply.class));
1172 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1174 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1175 expectMsgClass(duration, CommitTransactionReply.class);
1177 final InOrder inOrder = inOrder(cohort);
1178 inOrder.verify(cohort).canCommit();
1179 inOrder.verify(cohort).preCommit();
1180 inOrder.verify(cohort).commit();
1182 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1183 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1185 // Use MBean for verification
1186 // Committed transaction count should increase as usual
1187 assertEquals(1,shardStats.getCommittedTransactionsCount());
1189 // Commit index should not advance because this does not go into the journal
1190 assertEquals(-1, shardStats.getCommitIndex());
1196 public void testReadWriteCommitWhenTransactionHasModifications() {
1197 testCommitWhenTransactionHasModifications(true);
1201 public void testWriteOnlyCommitWhenTransactionHasModifications() {
1202 testCommitWhenTransactionHasModifications(false);
1205 private void testCommitWhenTransactionHasModifications(final boolean readWrite){
1206 new ShardTestKit(getSystem()) {
1208 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1209 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1210 "testCommitWhenTransactionHasModifications-" + readWrite);
1212 waitUntilLeader(shard);
1214 final String transactionID = "tx1";
1215 final MutableCompositeModification modification = new MutableCompositeModification();
1216 modification.addModification(new DeleteModification(YangInstanceIdentifier.EMPTY));
1217 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1218 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1219 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1220 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1221 doReturn(mockCandidate("cohort1-candidate")).when(cohort).getCandidate();
1223 final FiniteDuration duration = duration("5 seconds");
1225 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1226 expectMsgClass(duration, ReadyTransactionReply.class);
1228 // Send the CanCommitTransaction message.
1230 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1231 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1232 expectMsgClass(duration, CanCommitTransactionReply.class));
1233 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1235 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1236 expectMsgClass(duration, CommitTransactionReply.class);
1238 final InOrder inOrder = inOrder(cohort);
1239 inOrder.verify(cohort).canCommit();
1240 inOrder.verify(cohort).preCommit();
1241 inOrder.verify(cohort).commit();
1243 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1244 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1246 // Use MBean for verification
1247 // Committed transaction count should increase as usual
1248 assertEquals(1, shardStats.getCommittedTransactionsCount());
1250 // Commit index should advance as we do not have an empty modification
1251 assertEquals(0, shardStats.getCommitIndex());
1257 public void testCommitPhaseFailure() throws Throwable {
1258 testCommitPhaseFailure(true);
1259 testCommitPhaseFailure(false);
1262 private void testCommitPhaseFailure(final boolean readWrite) throws Throwable {
1263 new ShardTestKit(getSystem()) {{
1264 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1265 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1266 "testCommitPhaseFailure-" + readWrite);
1268 waitUntilLeader(shard);
1270 // Setup 2 simulated transactions with mock cohorts. The first one fails in the
1273 final String transactionID1 = "tx1";
1274 final MutableCompositeModification modification1 = new MutableCompositeModification();
1275 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1276 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1277 doReturn(Futures.immediateFuture(null)).when(cohort1).preCommit();
1278 doReturn(Futures.immediateFailedFuture(new RuntimeException("mock"))).when(cohort1).commit();
1279 doReturn(mockCandidate("cohort1-candidate")).when(cohort1).getCandidate();
1281 final String transactionID2 = "tx2";
1282 final MutableCompositeModification modification2 = new MutableCompositeModification();
1283 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1284 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1286 final FiniteDuration duration = duration("5 seconds");
1287 final Timeout timeout = new Timeout(duration);
1289 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1290 expectMsgClass(duration, ReadyTransactionReply.class);
1292 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1293 expectMsgClass(duration, ReadyTransactionReply.class);
1295 // Send the CanCommitTransaction message for the first Tx.
1297 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1298 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1299 expectMsgClass(duration, CanCommitTransactionReply.class));
1300 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1302 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1303 // processed after the first Tx completes.
1305 final Future<Object> canCommitFuture = Patterns.ask(shard,
1306 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1308 // Send the CommitTransaction message for the first Tx. This should send back an error
1309 // and trigger the 2nd Tx to proceed.
1311 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1312 expectMsgClass(duration, akka.actor.Status.Failure.class);
1314 // Wait for the 2nd Tx to complete the canCommit phase.
1316 final CountDownLatch latch = new CountDownLatch(1);
1317 canCommitFuture.onComplete(new OnComplete<Object>() {
1319 public void onComplete(final Throwable t, final Object resp) {
1322 }, getSystem().dispatcher());
1324 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1326 final InOrder inOrder = inOrder(cohort1, cohort2);
1327 inOrder.verify(cohort1).canCommit();
1328 inOrder.verify(cohort1).preCommit();
1329 inOrder.verify(cohort1).commit();
1330 inOrder.verify(cohort2).canCommit();
1335 public void testPreCommitPhaseFailure() throws Throwable {
1336 testPreCommitPhaseFailure(true);
1337 testPreCommitPhaseFailure(false);
1340 private void testPreCommitPhaseFailure(final boolean readWrite) throws Throwable {
1341 new ShardTestKit(getSystem()) {{
1342 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1343 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1344 "testPreCommitPhaseFailure-" + readWrite);
1346 waitUntilLeader(shard);
1348 final String transactionID1 = "tx1";
1349 final MutableCompositeModification modification1 = new MutableCompositeModification();
1350 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1351 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1352 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).preCommit();
1354 final String transactionID2 = "tx2";
1355 final MutableCompositeModification modification2 = new MutableCompositeModification();
1356 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1357 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1359 final FiniteDuration duration = duration("5 seconds");
1360 final Timeout timeout = new Timeout(duration);
1362 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1363 expectMsgClass(duration, ReadyTransactionReply.class);
1365 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1366 expectMsgClass(duration, ReadyTransactionReply.class);
1368 // Send the CanCommitTransaction message for the first Tx.
1370 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1371 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1372 expectMsgClass(duration, CanCommitTransactionReply.class));
1373 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1375 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1376 // processed after the first Tx completes.
1378 final Future<Object> canCommitFuture = Patterns.ask(shard,
1379 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1381 // Send the CommitTransaction message for the first Tx. This should send back an error
1382 // and trigger the 2nd Tx to proceed.
1384 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1385 expectMsgClass(duration, akka.actor.Status.Failure.class);
1387 // Wait for the 2nd Tx to complete the canCommit phase.
1389 final CountDownLatch latch = new CountDownLatch(1);
1390 canCommitFuture.onComplete(new OnComplete<Object>() {
1392 public void onComplete(final Throwable t, final Object resp) {
1395 }, getSystem().dispatcher());
1397 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1399 final InOrder inOrder = inOrder(cohort1, cohort2);
1400 inOrder.verify(cohort1).canCommit();
1401 inOrder.verify(cohort1).preCommit();
1402 inOrder.verify(cohort2).canCommit();
1407 public void testCanCommitPhaseFailure() throws Throwable {
1408 testCanCommitPhaseFailure(true);
1409 testCanCommitPhaseFailure(false);
1412 private void testCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1413 new ShardTestKit(getSystem()) {{
1414 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1415 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1416 "testCanCommitPhaseFailure-" + readWrite);
1418 waitUntilLeader(shard);
1420 final FiniteDuration duration = duration("5 seconds");
1422 final String transactionID1 = "tx1";
1423 final MutableCompositeModification modification = new MutableCompositeModification();
1424 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1425 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1427 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1428 expectMsgClass(duration, ReadyTransactionReply.class);
1430 // Send the CanCommitTransaction message.
1432 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1433 expectMsgClass(duration, akka.actor.Status.Failure.class);
1435 // Send another can commit to ensure the failed one got cleaned up.
1439 final String transactionID2 = "tx2";
1440 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1442 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1443 expectMsgClass(duration, ReadyTransactionReply.class);
1445 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1446 final CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1447 expectMsgClass(CanCommitTransactionReply.class));
1448 assertEquals("getCanCommit", true, reply.getCanCommit());
1453 public void testCanCommitPhaseFalseResponse() throws Throwable {
1454 testCanCommitPhaseFalseResponse(true);
1455 testCanCommitPhaseFalseResponse(false);
1458 private void testCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1459 new ShardTestKit(getSystem()) {{
1460 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1461 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1462 "testCanCommitPhaseFalseResponse-" + readWrite);
1464 waitUntilLeader(shard);
1466 final FiniteDuration duration = duration("5 seconds");
1468 final String transactionID1 = "tx1";
1469 final MutableCompositeModification modification = new MutableCompositeModification();
1470 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1471 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1473 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1474 expectMsgClass(duration, ReadyTransactionReply.class);
1476 // Send the CanCommitTransaction message.
1478 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1479 CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1480 expectMsgClass(CanCommitTransactionReply.class));
1481 assertEquals("getCanCommit", false, reply.getCanCommit());
1483 // Send another can commit to ensure the failed one got cleaned up.
1487 final String transactionID2 = "tx2";
1488 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1490 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1491 expectMsgClass(duration, ReadyTransactionReply.class);
1493 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1494 reply = CanCommitTransactionReply.fromSerializable(
1495 expectMsgClass(CanCommitTransactionReply.class));
1496 assertEquals("getCanCommit", true, reply.getCanCommit());
1501 public void testImmediateCommitWithCanCommitPhaseFailure() throws Throwable {
1502 testImmediateCommitWithCanCommitPhaseFailure(true);
1503 testImmediateCommitWithCanCommitPhaseFailure(false);
1506 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1507 new ShardTestKit(getSystem()) {{
1508 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1509 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1510 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1512 waitUntilLeader(shard);
1514 final FiniteDuration duration = duration("5 seconds");
1516 final String transactionID1 = "tx1";
1517 final MutableCompositeModification modification = new MutableCompositeModification();
1518 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1519 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1521 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification, true), getRef());
1523 expectMsgClass(duration, akka.actor.Status.Failure.class);
1525 // Send another can commit to ensure the failed one got cleaned up.
1529 final String transactionID2 = "tx2";
1530 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1531 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1532 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1533 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1534 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1535 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1536 doReturn(candidateRoot).when(candidate).getRootNode();
1537 doReturn(YangInstanceIdentifier.EMPTY).when(candidate).getRootPath();
1538 doReturn(candidate).when(cohort).getCandidate();
1540 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1542 expectMsgClass(duration, CommitTransactionReply.class);
1547 public void testImmediateCommitWithCanCommitPhaseFalseResponse() throws Throwable {
1548 testImmediateCommitWithCanCommitPhaseFalseResponse(true);
1549 testImmediateCommitWithCanCommitPhaseFalseResponse(false);
1552 private void testImmediateCommitWithCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1553 new ShardTestKit(getSystem()) {{
1554 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1555 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1556 "testImmediateCommitWithCanCommitPhaseFalseResponse-" + readWrite);
1558 waitUntilLeader(shard);
1560 final FiniteDuration duration = duration("5 seconds");
1562 final String transactionID = "tx1";
1563 final MutableCompositeModification modification = new MutableCompositeModification();
1564 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1565 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1567 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
1569 expectMsgClass(duration, akka.actor.Status.Failure.class);
1571 // Send another can commit to ensure the failed one got cleaned up.
1575 final String transactionID2 = "tx2";
1576 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1577 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1578 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1579 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1580 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1581 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1582 doReturn(candidateRoot).when(candidate).getRootNode();
1583 doReturn(YangInstanceIdentifier.EMPTY).when(candidate).getRootPath();
1584 doReturn(candidate).when(cohort).getCandidate();
1586 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1588 expectMsgClass(duration, CommitTransactionReply.class);
1593 public void testAbortBeforeFinishCommit() throws Throwable {
1594 testAbortBeforeFinishCommit(true);
1595 testAbortBeforeFinishCommit(false);
1598 private void testAbortBeforeFinishCommit(final boolean readWrite) throws Throwable {
1599 new ShardTestKit(getSystem()) {{
1600 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1601 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1602 "testAbortBeforeFinishCommit-" + readWrite);
1604 waitUntilLeader(shard);
1606 final FiniteDuration duration = duration("5 seconds");
1607 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1609 final String transactionID = "tx1";
1610 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit =
1612 final ListenableFuture<Void> preCommitFuture = cohort.preCommit();
1614 // Simulate an AbortTransaction message occurring during replication, after
1615 // persisting and before finishing the commit to the in-memory store.
1616 // We have no followers so due to optimizations in the RaftActor, it does not
1617 // attempt replication and thus we can't send an AbortTransaction message b/c
1618 // it would be processed too late after CommitTransaction completes. So we'll
1619 // simulate an AbortTransaction message occurring during replication by calling
1620 // the shard directly.
1622 shard.underlyingActor().doAbortTransaction(transactionID, null);
1624 return preCommitFuture;
1627 final MutableCompositeModification modification = new MutableCompositeModification();
1628 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort1", dataStore,
1629 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME),
1630 modification, preCommit);
1632 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1633 expectMsgClass(duration, ReadyTransactionReply.class);
1635 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1636 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1637 expectMsgClass(duration, CanCommitTransactionReply.class));
1638 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1640 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1641 expectMsgClass(duration, CommitTransactionReply.class);
1643 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1645 // Since we're simulating an abort occurring during replication and before finish commit,
1646 // the data should still get written to the in-memory store since we've gotten past
1647 // canCommit and preCommit and persisted the data.
1648 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1653 public void testTransactionCommitTimeout() throws Throwable {
1654 testTransactionCommitTimeout(true);
1655 testTransactionCommitTimeout(false);
1658 private void testTransactionCommitTimeout(final boolean readWrite) throws Throwable {
1659 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1661 new ShardTestKit(getSystem()) {{
1662 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1663 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1664 "testTransactionCommitTimeout-" + readWrite);
1666 waitUntilLeader(shard);
1668 final FiniteDuration duration = duration("5 seconds");
1670 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1672 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1673 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1674 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1676 // Create 1st Tx - will timeout
1678 final String transactionID1 = "tx1";
1679 final MutableCompositeModification modification1 = new MutableCompositeModification();
1680 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1681 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1682 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1683 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
1688 final String transactionID2 = "tx3";
1689 final MutableCompositeModification modification2 = new MutableCompositeModification();
1690 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1691 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1692 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort3", dataStore,
1694 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2),
1699 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1700 expectMsgClass(duration, ReadyTransactionReply.class);
1702 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1703 expectMsgClass(duration, ReadyTransactionReply.class);
1705 // canCommit 1st Tx. We don't send the commit so it should timeout.
1707 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1708 expectMsgClass(duration, CanCommitTransactionReply.class);
1710 // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1712 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1713 expectMsgClass(duration, CanCommitTransactionReply.class);
1715 // Try to commit the 1st Tx - should fail as it's not the current Tx.
1717 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1718 expectMsgClass(duration, akka.actor.Status.Failure.class);
1720 // Commit the 2nd Tx.
1722 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1723 expectMsgClass(duration, CommitTransactionReply.class);
1725 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1726 assertNotNull(listNodePath + " not found", node);
1731 public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1732 dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1734 new ShardTestKit(getSystem()) {{
1735 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1736 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1737 "testTransactionCommitQueueCapacityExceeded");
1739 waitUntilLeader(shard);
1741 final FiniteDuration duration = duration("5 seconds");
1743 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1745 final String transactionID1 = "tx1";
1746 final MutableCompositeModification modification1 = new MutableCompositeModification();
1747 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1748 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1750 final String transactionID2 = "tx2";
1751 final MutableCompositeModification modification2 = new MutableCompositeModification();
1752 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1753 TestModel.OUTER_LIST_PATH,
1754 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
1757 final String transactionID3 = "tx3";
1758 final MutableCompositeModification modification3 = new MutableCompositeModification();
1759 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1760 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification3);
1764 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1765 expectMsgClass(duration, ReadyTransactionReply.class);
1767 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1768 expectMsgClass(duration, ReadyTransactionReply.class);
1770 // The 3rd Tx should exceed queue capacity and fail.
1772 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1773 expectMsgClass(duration, akka.actor.Status.Failure.class);
1775 // canCommit 1st Tx.
1777 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1778 expectMsgClass(duration, CanCommitTransactionReply.class);
1780 // canCommit the 2nd Tx - it should get queued.
1782 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1784 // canCommit the 3rd Tx - should exceed queue capacity and fail.
1786 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1787 expectMsgClass(duration, akka.actor.Status.Failure.class);
1792 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Throwable {
1793 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1795 new ShardTestKit(getSystem()) {{
1796 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1797 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1798 "testTransactionCommitWithPriorExpiredCohortEntries");
1800 waitUntilLeader(shard);
1802 final FiniteDuration duration = duration("5 seconds");
1804 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1806 final String transactionID1 = "tx1";
1807 final MutableCompositeModification modification1 = new MutableCompositeModification();
1808 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1809 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1811 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1812 expectMsgClass(duration, ReadyTransactionReply.class);
1814 final String transactionID2 = "tx2";
1815 final MutableCompositeModification modification2 = new MutableCompositeModification();
1816 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1817 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1819 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1820 expectMsgClass(duration, ReadyTransactionReply.class);
1822 final String transactionID3 = "tx3";
1823 final MutableCompositeModification modification3 = new MutableCompositeModification();
1824 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1825 TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME), modification3);
1827 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1828 expectMsgClass(duration, ReadyTransactionReply.class);
1830 // All Tx's are readied. We'll send canCommit for the last one but not the others. The others
1831 // should expire from the queue and the last one should be processed.
1833 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1834 expectMsgClass(duration, CanCommitTransactionReply.class);
1839 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Throwable {
1840 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1842 new ShardTestKit(getSystem()) {{
1843 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1844 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1845 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1847 waitUntilLeader(shard);
1849 final FiniteDuration duration = duration("5 seconds");
1851 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1853 final String transactionID1 = "tx1";
1854 final MutableCompositeModification modification1 = new MutableCompositeModification();
1855 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1856 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1858 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1859 expectMsgClass(duration, ReadyTransactionReply.class);
1861 // CanCommit the first one so it's the current in-progress CohortEntry.
1863 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1864 expectMsgClass(duration, CanCommitTransactionReply.class);
1866 // Ready the second Tx.
1868 final String transactionID2 = "tx2";
1869 final MutableCompositeModification modification2 = new MutableCompositeModification();
1870 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1871 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1873 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1874 expectMsgClass(duration, ReadyTransactionReply.class);
1876 // Ready the third Tx.
1878 final String transactionID3 = "tx3";
1879 final DataTreeModification modification3 = dataStore.newModification();
1880 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1881 .apply(modification3);
1882 modification3.ready();
1883 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3, true);
1885 shard.tell(readyMessage, getRef());
1887 // Commit the first Tx. After completing, the second should expire from the queue and the third
1890 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1891 expectMsgClass(duration, CommitTransactionReply.class);
1893 // Expect commit reply from the third Tx.
1895 expectMsgClass(duration, CommitTransactionReply.class);
1897 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1898 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1903 public void testCanCommitBeforeReadyFailure() throws Throwable {
1904 new ShardTestKit(getSystem()) {{
1905 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1906 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1907 "testCanCommitBeforeReadyFailure");
1909 shard.tell(new CanCommitTransaction("tx", CURRENT_VERSION).toSerializable(), getRef());
1910 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1915 public void testAbortCurrentTransaction() throws Throwable {
1916 testAbortCurrentTransaction(true);
1917 testAbortCurrentTransaction(false);
1920 private void testAbortCurrentTransaction(final boolean readWrite) throws Throwable {
1921 new ShardTestKit(getSystem()) {{
1922 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1923 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1924 "testAbortCurrentTransaction-" + readWrite);
1926 waitUntilLeader(shard);
1928 // Setup 2 simulated transactions with mock cohorts. The first one will be aborted.
1930 final String transactionID1 = "tx1";
1931 final MutableCompositeModification modification1 = new MutableCompositeModification();
1932 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1933 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1934 doReturn(Futures.immediateFuture(null)).when(cohort1).abort();
1936 final String transactionID2 = "tx2";
1937 final MutableCompositeModification modification2 = new MutableCompositeModification();
1938 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1939 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1941 final FiniteDuration duration = duration("5 seconds");
1942 final Timeout timeout = new Timeout(duration);
1944 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1945 expectMsgClass(duration, ReadyTransactionReply.class);
1947 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1948 expectMsgClass(duration, ReadyTransactionReply.class);
1950 // Send the CanCommitTransaction message for the first Tx.
1952 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1953 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1954 expectMsgClass(duration, CanCommitTransactionReply.class));
1955 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1957 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1958 // processed after the first Tx completes.
1960 final Future<Object> canCommitFuture = Patterns.ask(shard,
1961 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1963 // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1966 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1967 expectMsgClass(duration, AbortTransactionReply.class);
1969 // Wait for the 2nd Tx to complete the canCommit phase.
1971 Await.ready(canCommitFuture, duration);
1973 final InOrder inOrder = inOrder(cohort1, cohort2);
1974 inOrder.verify(cohort1).canCommit();
1975 inOrder.verify(cohort2).canCommit();
1980 public void testAbortQueuedTransaction() throws Throwable {
1981 testAbortQueuedTransaction(true);
1982 testAbortQueuedTransaction(false);
1985 private void testAbortQueuedTransaction(final boolean readWrite) throws Throwable {
1986 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1987 new ShardTestKit(getSystem()) {{
1988 final AtomicReference<CountDownLatch> cleaupCheckLatch = new AtomicReference<>();
1989 @SuppressWarnings("serial")
1990 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
1992 public void handleCommand(final Object message) {
1993 super.handleCommand(message);
1994 if(TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
1995 if(cleaupCheckLatch.get() != null) {
1996 cleaupCheckLatch.get().countDown();
2002 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2003 Props.create(new DelegatingShardCreator(creator)).withDispatcher(
2004 Dispatchers.DefaultDispatcherId()), "testAbortQueuedTransaction-" + readWrite);
2006 waitUntilLeader(shard);
2008 final String transactionID = "tx1";
2010 final MutableCompositeModification modification = new MutableCompositeModification();
2011 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort");
2012 doReturn(Futures.immediateFuture(null)).when(cohort).abort();
2014 final FiniteDuration duration = duration("5 seconds");
2018 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
2019 expectMsgClass(duration, ReadyTransactionReply.class);
2021 assertEquals("getPendingTxCommitQueueSize", 1, shard.underlyingActor().getPendingTxCommitQueueSize());
2023 // Send the AbortTransaction message.
2025 shard.tell(new AbortTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2026 expectMsgClass(duration, AbortTransactionReply.class);
2028 verify(cohort).abort();
2030 // Verify the tx cohort is removed from queue at the cleanup check interval.
2032 cleaupCheckLatch.set(new CountDownLatch(1));
2033 assertEquals("TX_COMMIT_TIMEOUT_CHECK_MESSAGE received", true,
2034 cleaupCheckLatch.get().await(5, TimeUnit.SECONDS));
2036 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
2038 // Now send CanCommitTransaction - should fail.
2040 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2042 Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
2043 assertTrue("Failure type", failure instanceof IllegalStateException);
2048 public void testCreateSnapshot() throws Exception {
2049 testCreateSnapshot(true, "testCreateSnapshot");
2053 public void testCreateSnapshotWithNonPersistentData() throws Exception {
2054 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
2057 @SuppressWarnings("serial")
2058 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
2060 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
2062 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
2063 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
2064 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
2069 public void saveSnapshot(final Object o) {
2070 savedSnapshot.set(o);
2071 super.saveSnapshot(o);
2075 dataStoreContextBuilder.persistent(persistent);
2077 new ShardTestKit(getSystem()) {{
2078 class TestShard extends Shard {
2080 protected TestShard(AbstractBuilder<?, ?> builder) {
2082 setPersistence(new TestPersistentDataProvider(super.persistence()));
2086 public void handleCommand(final Object message) {
2087 super.handleCommand(message);
2089 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
2090 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
2091 latch.get().countDown();
2096 public RaftActorContext getRaftActorContext() {
2097 return super.getRaftActorContext();
2101 final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
2103 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2104 Props.create(new DelegatingShardCreator(creator)), shardActorName);
2106 waitUntilLeader(shard);
2107 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2109 final NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
2111 // Trigger creation of a snapshot by ensuring
2112 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
2113 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2114 awaitAndValidateSnapshot(expectedRoot);
2116 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2117 awaitAndValidateSnapshot(expectedRoot);
2120 private void awaitAndValidateSnapshot(NormalizedNode<?,?> expectedRoot) throws InterruptedException {
2121 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
2123 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
2124 savedSnapshot.get() instanceof Snapshot);
2126 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
2128 latch.set(new CountDownLatch(1));
2129 savedSnapshot.set(null);
2132 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?,?> expectedRoot) {
2134 final NormalizedNode<?, ?> actual = SerializationUtils.deserializeNormalizedNode(snapshot.getState());
2135 assertEquals("Root node", expectedRoot, actual);
2141 * This test simply verifies that the applySnapShot logic will work
2142 * @throws ReadFailedException
2143 * @throws DataValidationFailedException
2146 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
2147 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
2148 store.setSchemaContext(SCHEMA_CONTEXT);
2150 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
2151 putTransaction.write(TestModel.TEST_PATH,
2152 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2153 commitTransaction(store, putTransaction);
2156 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
2158 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2160 writeTransaction.delete(YangInstanceIdentifier.EMPTY);
2161 writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
2163 commitTransaction(store, writeTransaction);
2165 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
2167 assertEquals(expected, actual);
2171 public void testRecoveryApplicable(){
2173 final DatastoreContext persistentContext = DatastoreContext.newBuilder().
2174 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2176 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext).
2177 schemaContext(SCHEMA_CONTEXT).props();
2179 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
2180 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2182 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext).
2183 schemaContext(SCHEMA_CONTEXT).props();
2185 new ShardTestKit(getSystem()) {{
2186 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2188 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2190 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2192 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2197 public void testOnDatastoreContext() {
2198 new ShardTestKit(getSystem()) {{
2199 dataStoreContextBuilder.persistent(true);
2201 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
2203 assertEquals("isRecoveryApplicable", true,
2204 shard.underlyingActor().persistence().isRecoveryApplicable());
2206 waitUntilLeader(shard);
2208 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2210 assertEquals("isRecoveryApplicable", false,
2211 shard.underlyingActor().persistence().isRecoveryApplicable());
2213 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2215 assertEquals("isRecoveryApplicable", true,
2216 shard.underlyingActor().persistence().isRecoveryApplicable());
2221 public void testRegisterRoleChangeListener() throws Exception {
2222 new ShardTestKit(getSystem()) {
2224 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2225 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2226 "testRegisterRoleChangeListener");
2228 waitUntilLeader(shard);
2230 final TestActorRef<MessageCollectorActor> listener =
2231 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2233 shard.tell(new RegisterRoleChangeListener(), listener);
2235 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2237 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2238 ShardLeaderStateChanged.class);
2239 assertEquals("getLocalShardDataTree present", true,
2240 leaderStateChanged.getLocalShardDataTree().isPresent());
2241 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2242 leaderStateChanged.getLocalShardDataTree().get());
2244 MessageCollectorActor.clearMessages(listener);
2246 // Force a leader change
2248 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2250 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2251 ShardLeaderStateChanged.class);
2252 assertEquals("getLocalShardDataTree present", false,
2253 leaderStateChanged.getLocalShardDataTree().isPresent());
2259 public void testFollowerInitialSyncStatus() throws Exception {
2260 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2261 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2262 "testFollowerInitialSyncStatus");
2264 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
2266 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2268 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
2270 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2274 public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
2275 new ShardTestKit(getSystem()) {{
2276 String testName = "testClusteredDataChangeListenerDelayedRegistration";
2277 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2278 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2280 final MockDataChangeListener listener = new MockDataChangeListener(1);
2281 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2282 actorFactory.generateActorId(testName + "-DataChangeListener"));
2284 setupInMemorySnapshotStore();
2286 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2287 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2288 actorFactory.generateActorId(testName + "-shard"));
2290 waitUntilNoLeader(shard);
2292 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2294 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2295 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2296 RegisterChangeListenerReply.class);
2297 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2299 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2300 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2302 listener.waitForChangeEvents();
2307 public void testClusteredDataChangeListenerRegistration() throws Exception {
2308 new ShardTestKit(getSystem()) {{
2309 String testName = "testClusteredDataChangeListenerRegistration";
2310 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2311 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2313 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2314 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2316 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2317 Shard.builder().id(followerShardID).
2318 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2319 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2320 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2321 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2323 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2324 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2325 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2326 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2327 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2329 leaderShard.tell(ElectionTimeout.INSTANCE, ActorRef.noSender());
2330 String leaderPath = waitUntilLeader(followerShard);
2331 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2333 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2334 final MockDataChangeListener listener = new MockDataChangeListener(1);
2335 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2336 actorFactory.generateActorId(testName + "-DataChangeListener"));
2338 followerShard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2339 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2340 RegisterChangeListenerReply.class);
2341 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2343 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2345 listener.waitForChangeEvents();
2350 public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
2351 new ShardTestKit(getSystem()) {{
2352 String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
2353 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2354 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2356 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2357 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2358 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2360 setupInMemorySnapshotStore();
2362 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2363 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2364 actorFactory.generateActorId(testName + "-shard"));
2366 waitUntilNoLeader(shard);
2368 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2370 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2371 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2372 RegisterDataTreeChangeListenerReply.class);
2373 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2375 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2376 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2378 listener.waitForChangeEvents();
2383 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2384 new ShardTestKit(getSystem()) {{
2385 String testName = "testClusteredDataTreeChangeListenerRegistration";
2386 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2387 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2389 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2390 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2392 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2393 Shard.builder().id(followerShardID).
2394 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2395 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2396 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2397 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2399 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2400 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2401 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2402 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2403 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2405 leaderShard.tell(ElectionTimeout.INSTANCE, ActorRef.noSender());
2406 String leaderPath = waitUntilLeader(followerShard);
2407 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2409 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2410 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2411 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2412 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2414 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2415 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2416 RegisterDataTreeChangeListenerReply.class);
2417 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2419 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2421 listener.waitForChangeEvents();
2426 public void testServerRemoved() throws Exception {
2427 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2429 final ActorRef shard = parent.underlyingActor().context().actorOf(
2430 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2431 "testServerRemoved");
2433 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2435 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);