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.io.IOException;
40 import java.util.Collections;
41 import java.util.HashSet;
43 import java.util.concurrent.CountDownLatch;
44 import java.util.concurrent.TimeUnit;
45 import java.util.concurrent.atomic.AtomicBoolean;
46 import java.util.concurrent.atomic.AtomicReference;
47 import org.junit.Test;
48 import org.mockito.InOrder;
49 import org.opendaylight.controller.cluster.DataPersistenceProvider;
50 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
51 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
52 import org.opendaylight.controller.cluster.access.concepts.MemberName;
53 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
54 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
55 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
56 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
57 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
58 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
59 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
60 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
61 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
62 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
63 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
65 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
67 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
68 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
70 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
71 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
72 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
73 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
74 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListenerReply;
76 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
77 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
78 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
79 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
80 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
81 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
82 import org.opendaylight.controller.cluster.datastore.persisted.PreBoronShardDataTreeSnapshot;
83 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
84 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
85 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
86 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
87 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
88 import org.opendaylight.controller.cluster.raft.RaftActorContext;
89 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
90 import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry;
91 import org.opendaylight.controller.cluster.raft.Snapshot;
92 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
93 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
94 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
95 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
96 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
97 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
98 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
99 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
100 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
101 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
102 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
103 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
104 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
105 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
106 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
107 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
108 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
109 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
110 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
114 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
117 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
118 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
119 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
120 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
121 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
122 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
123 import scala.concurrent.Await;
124 import scala.concurrent.Future;
125 import scala.concurrent.duration.FiniteDuration;
127 public class ShardTest extends AbstractShardTest {
128 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";
131 public void testRegisterChangeListener() throws Exception {
132 new ShardTestKit(getSystem()) {{
133 final TestActorRef<Shard> shard = actorFactory.createTestActor(
134 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterChangeListener");
136 waitUntilLeader(shard);
138 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
140 final MockDataChangeListener listener = new MockDataChangeListener(1);
141 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
142 "testRegisterChangeListener-DataChangeListener");
144 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
145 dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
147 final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
148 RegisterChangeListenerReply.class);
149 final String replyPath = reply.getListenerRegistrationPath().toString();
150 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
151 "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
153 final YangInstanceIdentifier path = TestModel.TEST_PATH;
154 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
156 listener.waitForChangeEvents(path);
160 @SuppressWarnings("serial")
162 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
163 // This test tests the timing window in which a change listener is registered before the
164 // shard becomes the leader. We verify that the listener is registered and notified of the
165 // existing data when the shard becomes the leader.
166 new ShardTestKit(getSystem()) {{
167 // For this test, we want to send the RegisterChangeListener message after the shard
168 // has recovered from persistence and before it becomes the leader. So we subclass
169 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
170 // we know that the shard has been initialized to a follower and has started the
171 // election process. The following 2 CountDownLatches are used to coordinate the
172 // ElectionTimeout with the sending of the RegisterChangeListener message.
173 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
174 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
175 final Creator<Shard> creator = new Creator<Shard>() {
176 boolean firstElectionTimeout = true;
179 public Shard create() throws Exception {
180 // Use a non persistent provider because this test actually invokes persist on the journal
181 // this will cause all other messages to not be queued properly after that.
182 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
183 // it does do a persist)
184 return new Shard(newShardBuilder()) {
186 public void handleCommand(final Object message) {
187 if(message instanceof ElectionTimeout && firstElectionTimeout) {
188 // Got the first ElectionTimeout. We don't forward it to the
189 // base Shard yet until we've sent the RegisterChangeListener
190 // message. So we signal the onFirstElectionTimeout latch to tell
191 // the main thread to send the RegisterChangeListener message and
192 // start a thread to wait on the onChangeListenerRegistered latch,
193 // which the main thread signals after it has sent the message.
194 // After the onChangeListenerRegistered is triggered, we send the
195 // original ElectionTimeout message to proceed with the election.
196 firstElectionTimeout = false;
197 final ActorRef self = getSelf();
201 Uninterruptibles.awaitUninterruptibly(
202 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
203 self.tell(message, self);
207 onFirstElectionTimeout.countDown();
209 super.handleCommand(message);
216 setupInMemorySnapshotStore();
218 final MockDataChangeListener listener = new MockDataChangeListener(1);
219 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
220 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
222 final TestActorRef<Shard> shard = actorFactory.createTestActor(
223 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
224 "testRegisterChangeListenerWhenNotLeaderInitially");
226 final YangInstanceIdentifier path = TestModel.TEST_PATH;
228 // Wait until the shard receives the first ElectionTimeout message.
229 assertEquals("Got first ElectionTimeout", true,
230 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
232 // Now send the RegisterChangeListener and wait for the reply.
233 shard.tell(new RegisterChangeListener(path, dclActor,
234 AsyncDataBroker.DataChangeScope.SUBTREE, false), getRef());
236 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
237 RegisterChangeListenerReply.class);
238 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
240 // Sanity check - verify the shard is not the leader yet.
241 shard.tell(FindLeader.INSTANCE, getRef());
242 final FindLeaderReply findLeadeReply =
243 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
244 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
246 // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
247 // with the election process.
248 onChangeListenerRegistered.countDown();
250 // Wait for the shard to become the leader and notify our listener with the existing
251 // data in the store.
252 listener.waitForChangeEvents(path);
257 public void testRegisterDataTreeChangeListener() throws Exception {
258 new ShardTestKit(getSystem()) {{
259 final TestActorRef<Shard> shard = actorFactory.createTestActor(
260 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterDataTreeChangeListener");
262 waitUntilLeader(shard);
264 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
266 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
267 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
268 "testRegisterDataTreeChangeListener-DataTreeChangeListener");
270 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
272 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
273 RegisterDataTreeChangeListenerReply.class);
274 final String replyPath = reply.getListenerRegistrationPath().toString();
275 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
276 "akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
278 final YangInstanceIdentifier path = TestModel.TEST_PATH;
279 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
281 listener.waitForChangeEvents();
285 @SuppressWarnings("serial")
287 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
288 new ShardTestKit(getSystem()) {{
289 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
290 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
291 final Creator<Shard> creator = new Creator<Shard>() {
292 boolean firstElectionTimeout = true;
295 public Shard create() throws Exception {
296 return new Shard(newShardBuilder()) {
298 public void handleCommand(final Object message) {
299 if(message instanceof ElectionTimeout && firstElectionTimeout) {
300 firstElectionTimeout = false;
301 final ActorRef self = getSelf();
305 Uninterruptibles.awaitUninterruptibly(
306 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
307 self.tell(message, self);
311 onFirstElectionTimeout.countDown();
313 super.handleCommand(message);
320 setupInMemorySnapshotStore();
322 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
323 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
324 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
326 final TestActorRef<Shard> shard = actorFactory.createTestActor(
327 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
328 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
330 final YangInstanceIdentifier path = TestModel.TEST_PATH;
332 assertEquals("Got first ElectionTimeout", true,
333 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
335 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
336 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
337 RegisterDataTreeChangeListenerReply.class);
338 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
340 shard.tell(FindLeader.INSTANCE, getRef());
341 final FindLeaderReply findLeadeReply =
342 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
343 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
346 onChangeListenerRegistered.countDown();
348 // TODO: investigate why we do not receive data chage events
349 listener.waitForChangeEvents();
354 public void testCreateTransaction(){
355 new ShardTestKit(getSystem()) {{
356 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
358 waitUntilLeader(shard);
360 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
362 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
363 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
365 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
366 CreateTransactionReply.class);
368 final String path = reply.getTransactionPath().toString();
369 assertTrue("Unexpected transaction path " + path,
370 path.startsWith("akka://test/user/testCreateTransaction/shard-member-1:ShardTransactionTest@0:"));
375 public void testCreateTransactionOnChain(){
376 new ShardTestKit(getSystem()) {{
377 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
379 waitUntilLeader(shard);
381 shard.tell(new CreateTransaction(nextTransactionId(),TransactionType.READ_ONLY.ordinal(),
382 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
384 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
385 CreateTransactionReply.class);
387 final String path = reply.getTransactionPath().toString();
388 assertTrue("Unexpected transaction path " + path,
389 path.startsWith("akka://test/user/testCreateTransactionOnChain/shard-member-1:ShardTransactionTest@0:"));
394 public void testPeerAddressResolved() throws Exception {
395 new ShardTestKit(getSystem()) {{
396 ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"), "config");
397 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder().
398 peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null)).props().
399 withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
401 final String address = "akka://foobar";
402 shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
404 shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
405 OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
406 assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
411 public void testApplySnapshot() throws Exception {
413 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testApplySnapshot");
415 ShardTestKit.waitUntilLeader(shard);
417 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
418 store.setSchemaContext(SCHEMA_CONTEXT);
420 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
421 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
422 withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
423 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
425 writeToStore(store, TestModel.TEST_PATH, container);
427 final YangInstanceIdentifier root = YangInstanceIdentifier.EMPTY;
428 final NormalizedNode<?,?> expected = readStore(store, root);
430 final Snapshot snapshot = Snapshot.create(new PreBoronShardDataTreeSnapshot(expected).serialize(),
431 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
433 shard.underlyingActor().getRaftActorSnapshotCohort().applySnapshot(snapshot.getState());
435 final NormalizedNode<?,?> actual = readStore(shard, root);
437 assertEquals("Root node", expected, actual);
441 public void testApplyState() throws Exception {
442 final TestActorRef<Shard> shard = actorFactory.createTestActor(
443 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");
445 ShardTestKit.waitUntilLeader(shard);
447 final DataTree source = setupInMemorySnapshotStore();
448 final DataTreeModification writeMod = source.takeSnapshot().newModification();
449 ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
450 writeMod.write(TestModel.TEST_PATH, node);
453 final TransactionIdentifier tx = nextTransactionId();
454 final ApplyState applyState = new ApplyState(null, tx,
455 new ReplicatedLogImplEntry(1, 2, payloadForModification(source, writeMod, tx)));
457 shard.tell(applyState, shard);
459 Stopwatch sw = Stopwatch.createStarted();
460 while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
461 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
463 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
465 assertEquals("Applied state", node, actual);
470 fail("State was not applied");
474 public void testDataTreeCandidateRecovery() throws Exception {
475 // Set up the InMemorySnapshotStore.
476 final DataTree source = setupInMemorySnapshotStore();
478 final DataTreeModification writeMod = source.takeSnapshot().newModification();
479 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
481 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
483 // Set up the InMemoryJournal.
484 InMemoryJournal.addEntry(shardID.toString(), 1, new ReplicatedLogImplEntry(0, 1,
485 payloadForModification(source, writeMod, nextTransactionId())));
487 final int nListEntries = 16;
488 final Set<Integer> listEntryKeys = new HashSet<>();
490 // Add some ModificationPayload entries
491 for (int i = 1; i <= nListEntries; i++) {
492 listEntryKeys.add(Integer.valueOf(i));
494 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
495 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
497 final DataTreeModification mod = source.takeSnapshot().newModification();
498 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
501 InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
502 payloadForModification(source, mod, nextTransactionId())));
505 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
506 new ApplyJournalEntries(nListEntries));
508 testRecovery(listEntryKeys);
512 public void testConcurrentThreePhaseCommits() throws Throwable {
513 new ShardTestKit(getSystem()) {{
514 final TestActorRef<Shard> shard = actorFactory.createTestActor(
515 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
516 "testConcurrentThreePhaseCommits");
518 waitUntilLeader(shard);
520 // Setup 3 simulated transactions with mock cohorts backed by real cohorts.
522 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
524 final TransactionIdentifier transactionID1 = nextTransactionId();
525 final MutableCompositeModification modification1 = new MutableCompositeModification();
526 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
527 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
529 final TransactionIdentifier transactionID2 = nextTransactionId();
530 final MutableCompositeModification modification2 = new MutableCompositeModification();
531 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
532 TestModel.OUTER_LIST_PATH,
533 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
536 final TransactionIdentifier transactionID3 = nextTransactionId();
537 final MutableCompositeModification modification3 = new MutableCompositeModification();
538 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
539 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
540 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
541 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
544 final long timeoutSec = 5;
545 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
546 final Timeout timeout = new Timeout(duration);
548 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
549 final ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
550 expectMsgClass(duration, ReadyTransactionReply.class));
551 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
553 // Send the CanCommitTransaction message for the first Tx.
555 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
556 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
557 expectMsgClass(duration, CanCommitTransactionReply.class));
558 assertEquals("Can commit", true, canCommitReply.getCanCommit());
560 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
561 expectMsgClass(duration, ReadyTransactionReply.class);
563 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
564 expectMsgClass(duration, ReadyTransactionReply.class);
566 // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
567 // processed after the first Tx completes.
569 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
570 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
572 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
573 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
575 // Send the CommitTransaction message for the first Tx. After it completes, it should
576 // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
578 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
579 expectMsgClass(duration, CommitTransactionReply.class);
581 // Wait for the next 2 Tx's to complete.
583 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
584 final CountDownLatch commitLatch = new CountDownLatch(2);
586 class OnFutureComplete extends OnComplete<Object> {
587 private final Class<?> expRespType;
589 OnFutureComplete(final Class<?> expRespType) {
590 this.expRespType = expRespType;
594 public void onComplete(final Throwable error, final Object resp) {
596 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
599 assertEquals("Commit response type", expRespType, resp.getClass());
601 } catch (final Exception e) {
607 void onSuccess(final Object resp) throws Exception {
611 class OnCommitFutureComplete extends OnFutureComplete {
612 OnCommitFutureComplete() {
613 super(CommitTransactionReply.class);
617 public void onComplete(final Throwable error, final Object resp) {
618 super.onComplete(error, resp);
619 commitLatch.countDown();
623 class OnCanCommitFutureComplete extends OnFutureComplete {
624 private final TransactionIdentifier transactionID;
626 OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
627 super(CanCommitTransactionReply.class);
628 this.transactionID = transactionID;
632 void onSuccess(final Object resp) throws Exception {
633 final CanCommitTransactionReply canCommitReply =
634 CanCommitTransactionReply.fromSerializable(resp);
635 assertEquals("Can commit", true, canCommitReply.getCanCommit());
637 final Future<Object> commitFuture = Patterns.ask(shard,
638 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
639 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
643 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
644 getSystem().dispatcher());
646 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
647 getSystem().dispatcher());
649 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
651 if(caughtEx.get() != null) {
652 throw caughtEx.get();
655 assertEquals("Commits complete", true, done);
657 final InOrder inOrder = inOrder(cohort1, cohort2, cohort3);
658 inOrder.verify(cohort1).canCommit();
659 inOrder.verify(cohort1).preCommit();
660 inOrder.verify(cohort1).commit();
661 inOrder.verify(cohort2).canCommit();
662 inOrder.verify(cohort2).preCommit();
663 inOrder.verify(cohort2).commit();
664 inOrder.verify(cohort3).canCommit();
665 inOrder.verify(cohort3).preCommit();
666 inOrder.verify(cohort3).commit();
668 // Verify data in the data store.
670 verifyOuterListEntry(shard, 1);
672 verifyLastApplied(shard, 2);
677 public void testBatchedModificationsWithNoCommitOnReady() throws Throwable {
678 new ShardTestKit(getSystem()) {{
679 final TestActorRef<Shard> shard = actorFactory.createTestActor(
680 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
681 "testBatchedModificationsWithNoCommitOnReady");
683 waitUntilLeader(shard);
685 final TransactionIdentifier transactionID = nextTransactionId();
686 final FiniteDuration duration = duration("5 seconds");
688 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
689 final ShardCommitCoordinator.CohortDecorator cohortDecorator = (txID, actual) -> {
690 if(mockCohort.get() == null) {
691 mockCohort.set(createDelegatingMockCohort("cohort", actual));
694 return mockCohort.get();
697 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
699 // Send a BatchedModifications to start a transaction.
701 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
702 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
703 expectMsgClass(duration, BatchedModificationsReply.class);
705 // Send a couple more BatchedModifications.
707 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
708 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
709 expectMsgClass(duration, BatchedModificationsReply.class);
711 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
712 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
713 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3), getRef());
714 expectMsgClass(duration, ReadyTransactionReply.class);
716 // Send the CanCommitTransaction message.
718 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
719 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
720 expectMsgClass(duration, CanCommitTransactionReply.class));
721 assertEquals("Can commit", true, canCommitReply.getCanCommit());
723 // Send the CanCommitTransaction message.
725 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
726 expectMsgClass(duration, CommitTransactionReply.class);
728 final InOrder inOrder = inOrder(mockCohort.get());
729 inOrder.verify(mockCohort.get()).canCommit();
730 inOrder.verify(mockCohort.get()).preCommit();
731 inOrder.verify(mockCohort.get()).commit();
733 // Verify data in the data store.
735 verifyOuterListEntry(shard, 1);
740 public void testBatchedModificationsWithCommitOnReady() throws Throwable {
741 new ShardTestKit(getSystem()) {{
742 final TestActorRef<Shard> shard = actorFactory.createTestActor(
743 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
744 "testBatchedModificationsWithCommitOnReady");
746 waitUntilLeader(shard);
748 final TransactionIdentifier transactionID = nextTransactionId();
749 final FiniteDuration duration = duration("5 seconds");
751 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
752 final ShardCommitCoordinator.CohortDecorator cohortDecorator = (txID, actual) -> {
753 if(mockCohort.get() == null) {
754 mockCohort.set(createDelegatingMockCohort("cohort", actual));
757 return mockCohort.get();
760 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
762 // Send a BatchedModifications to start a transaction.
764 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
765 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
766 expectMsgClass(duration, BatchedModificationsReply.class);
768 // Send a couple more BatchedModifications.
770 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
771 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
772 expectMsgClass(duration, BatchedModificationsReply.class);
774 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
775 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
776 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3), getRef());
778 expectMsgClass(duration, CommitTransactionReply.class);
780 final InOrder inOrder = inOrder(mockCohort.get());
781 inOrder.verify(mockCohort.get()).canCommit();
782 inOrder.verify(mockCohort.get()).preCommit();
783 inOrder.verify(mockCohort.get()).commit();
785 // Verify data in the data store.
787 verifyOuterListEntry(shard, 1);
791 @Test(expected=IllegalStateException.class)
792 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Throwable {
793 new ShardTestKit(getSystem()) {{
794 final TestActorRef<Shard> shard = actorFactory.createTestActor(
795 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
796 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
798 waitUntilLeader(shard);
800 final TransactionIdentifier transactionID = nextTransactionId();
801 final BatchedModifications batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
802 batched.setReady(true);
803 batched.setTotalMessagesSent(2);
805 shard.tell(batched, getRef());
807 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
809 if(failure != null) {
810 throw failure.cause();
816 public void testBatchedModificationsWithOperationFailure() throws Throwable {
817 new ShardTestKit(getSystem()) {{
818 final TestActorRef<Shard> shard = actorFactory.createTestActor(
819 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
820 "testBatchedModificationsWithOperationFailure");
822 waitUntilLeader(shard);
824 // Test merge with invalid data. An exception should occur when the merge is applied. Note that
825 // write will not validate the children for performance reasons.
827 TransactionIdentifier transactionID = nextTransactionId();
829 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
830 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
831 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
833 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
834 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
835 shard.tell(batched, getRef());
836 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
838 Throwable cause = failure.cause();
840 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
841 batched.setReady(true);
842 batched.setTotalMessagesSent(2);
844 shard.tell(batched, getRef());
846 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
847 assertEquals("Failure cause", cause, failure.cause());
852 public void testBatchedModificationsOnTransactionChain() throws Throwable {
853 new ShardTestKit(getSystem()) {{
854 final TestActorRef<Shard> shard = actorFactory.createTestActor(
855 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
856 "testBatchedModificationsOnTransactionChain");
858 waitUntilLeader(shard);
860 final LocalHistoryIdentifier historyId = nextHistoryId();
861 final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
862 final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
864 final FiniteDuration duration = duration("5 seconds");
866 // Send a BatchedModifications to start a chained write transaction and ready it.
868 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
869 final YangInstanceIdentifier path = TestModel.TEST_PATH;
870 shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
871 expectMsgClass(duration, ReadyTransactionReply.class);
873 // Create a read Tx on the same chain.
875 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
876 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
878 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
880 getSystem().actorSelection(createReply.getTransactionPath()).tell(
881 new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
882 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
883 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
885 // Commit the write transaction.
887 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
888 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
889 expectMsgClass(duration, CanCommitTransactionReply.class));
890 assertEquals("Can commit", true, canCommitReply.getCanCommit());
892 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
893 expectMsgClass(duration, CommitTransactionReply.class);
895 // Verify data in the data store.
897 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
898 assertEquals("Stored node", containerNode, actualNode);
903 public void testOnBatchedModificationsWhenNotLeader() {
904 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
905 new ShardTestKit(getSystem()) {{
906 final Creator<Shard> creator = new Creator<Shard>() {
907 private static final long serialVersionUID = 1L;
910 public Shard create() throws Exception {
911 return new Shard(newShardBuilder()) {
913 protected boolean isLeader() {
914 return overrideLeaderCalls.get() ? false : super.isLeader();
918 protected ActorSelection getLeader() {
919 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
926 final TestActorRef<Shard> shard = actorFactory.createTestActor(
927 Props.create(new DelegatingShardCreator(creator)).
928 withDispatcher(Dispatchers.DefaultDispatcherId()), "testOnBatchedModificationsWhenNotLeader");
930 waitUntilLeader(shard);
932 overrideLeaderCalls.set(true);
934 final BatchedModifications batched = new BatchedModifications(nextTransactionId(), DataStoreVersions.CURRENT_VERSION);
936 shard.tell(batched, ActorRef.noSender());
938 expectMsgEquals(batched);
943 public void testTransactionMessagesWithNoLeader() {
944 new ShardTestKit(getSystem()) {{
945 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
946 shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
947 final TestActorRef<Shard> shard = actorFactory.createTestActor(
948 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
949 "testTransactionMessagesWithNoLeader");
951 waitUntilNoLeader(shard);
953 final TransactionIdentifier txId = nextTransactionId();
954 shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
955 Failure failure = expectMsgClass(Failure.class);
956 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
958 shard.tell(prepareForwardedReadyTransaction(mock(ShardDataTreeCohort.class), txId,
959 DataStoreVersions.CURRENT_VERSION, true), getRef());
960 failure = expectMsgClass(Failure.class);
961 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
963 shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
964 failure = expectMsgClass(Failure.class);
965 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
970 public void testReadyWithReadWriteImmediateCommit() throws Exception{
971 testReadyWithImmediateCommit(true);
975 public void testReadyWithWriteOnlyImmediateCommit() throws Exception{
976 testReadyWithImmediateCommit(false);
979 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception{
980 new ShardTestKit(getSystem()) {{
981 final TestActorRef<Shard> shard = actorFactory.createTestActor(
982 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
983 "testReadyWithImmediateCommit-" + readWrite);
985 waitUntilLeader(shard);
987 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
989 final TransactionIdentifier transactionID = nextTransactionId();
990 final MutableCompositeModification modification = new MutableCompositeModification();
991 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
992 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
993 TestModel.TEST_PATH, containerNode, modification);
995 final FiniteDuration duration = duration("5 seconds");
997 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
999 expectMsgClass(duration, CommitTransactionReply.class);
1001 final InOrder inOrder = inOrder(cohort);
1002 inOrder.verify(cohort).canCommit();
1003 inOrder.verify(cohort).preCommit();
1004 inOrder.verify(cohort).commit();
1006 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1007 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1012 public void testReadyLocalTransactionWithImmediateCommit() throws Exception{
1013 new ShardTestKit(getSystem()) {{
1014 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1015 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1016 "testReadyLocalTransactionWithImmediateCommit");
1018 waitUntilLeader(shard);
1020 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1022 final DataTreeModification modification = dataStore.newModification();
1024 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1025 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1026 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1027 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1029 final TransactionIdentifier txId = nextTransactionId();
1030 modification.ready();
1031 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1033 shard.tell(readyMessage, getRef());
1035 expectMsgClass(CommitTransactionReply.class);
1037 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1038 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1043 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception{
1044 new ShardTestKit(getSystem()) {{
1045 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1046 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1047 "testReadyLocalTransactionWithThreePhaseCommit");
1049 waitUntilLeader(shard);
1051 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1053 final DataTreeModification modification = dataStore.newModification();
1055 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1056 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1057 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1058 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1060 final TransactionIdentifier txId = nextTransactionId();
1061 modification.ready();
1062 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1064 shard.tell(readyMessage, getRef());
1066 expectMsgClass(ReadyTransactionReply.class);
1068 // Send the CanCommitTransaction message.
1070 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1071 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1072 expectMsgClass(CanCommitTransactionReply.class));
1073 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1075 // Send the CanCommitTransaction message.
1077 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1078 expectMsgClass(CommitTransactionReply.class);
1080 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1081 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1086 public void testReadWriteCommitWithPersistenceDisabled() throws Throwable {
1087 testCommitWithPersistenceDisabled(true);
1091 public void testWriteOnlyCommitWithPersistenceDisabled() throws Throwable {
1092 testCommitWithPersistenceDisabled(true);
1095 private void testCommitWithPersistenceDisabled(final boolean readWrite) throws Throwable {
1096 dataStoreContextBuilder.persistent(false);
1097 new ShardTestKit(getSystem()) {{
1098 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1099 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1100 "testCommitWithPersistenceDisabled-" + readWrite);
1102 waitUntilLeader(shard);
1104 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1106 // Setup a simulated transactions with a mock cohort.
1108 final TransactionIdentifier transactionID = nextTransactionId();
1109 final MutableCompositeModification modification = new MutableCompositeModification();
1110 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1111 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
1112 TestModel.TEST_PATH, containerNode, modification);
1114 final FiniteDuration duration = duration("5 seconds");
1116 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1117 expectMsgClass(duration, ReadyTransactionReply.class);
1119 // Send the CanCommitTransaction message.
1121 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1122 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1123 expectMsgClass(duration, CanCommitTransactionReply.class));
1124 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1126 // Send the CanCommitTransaction message.
1128 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1129 expectMsgClass(duration, CommitTransactionReply.class);
1131 final InOrder inOrder = inOrder(cohort);
1132 inOrder.verify(cohort).canCommit();
1133 inOrder.verify(cohort).preCommit();
1134 inOrder.verify(cohort).commit();
1136 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1137 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1142 public void testReadWriteCommitWhenTransactionHasNoModifications() {
1143 testCommitWhenTransactionHasNoModifications(true);
1147 public void testWriteOnlyCommitWhenTransactionHasNoModifications() {
1148 testCommitWhenTransactionHasNoModifications(false);
1151 private void testCommitWhenTransactionHasNoModifications(final boolean readWrite){
1152 // Note that persistence is enabled which would normally result in the entry getting written to the journal
1153 // but here that need not happen
1154 new ShardTestKit(getSystem()) {
1156 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1157 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1158 "testCommitWhenTransactionHasNoModifications-" + readWrite);
1160 waitUntilLeader(shard);
1162 final TransactionIdentifier transactionID = nextTransactionId();
1163 final MutableCompositeModification modification = new MutableCompositeModification();
1164 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1165 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1166 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1167 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1168 doReturn(mockUnmodifiedCandidate("cohort1-candidate")).when(cohort).getCandidate();
1170 final FiniteDuration duration = duration("5 seconds");
1172 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1173 expectMsgClass(duration, ReadyTransactionReply.class);
1175 // Send the CanCommitTransaction message.
1177 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1178 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1179 expectMsgClass(duration, CanCommitTransactionReply.class));
1180 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1182 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1183 expectMsgClass(duration, CommitTransactionReply.class);
1185 final InOrder inOrder = inOrder(cohort);
1186 inOrder.verify(cohort).canCommit();
1187 inOrder.verify(cohort).preCommit();
1188 inOrder.verify(cohort).commit();
1190 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1191 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1193 // Use MBean for verification
1194 // Committed transaction count should increase as usual
1195 assertEquals(1,shardStats.getCommittedTransactionsCount());
1197 // Commit index should not advance because this does not go into the journal
1198 assertEquals(-1, shardStats.getCommitIndex());
1204 public void testReadWriteCommitWhenTransactionHasModifications() {
1205 testCommitWhenTransactionHasModifications(true);
1209 public void testWriteOnlyCommitWhenTransactionHasModifications() {
1210 testCommitWhenTransactionHasModifications(false);
1213 private void testCommitWhenTransactionHasModifications(final boolean readWrite){
1214 new ShardTestKit(getSystem()) {
1216 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1217 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1218 "testCommitWhenTransactionHasModifications-" + readWrite);
1220 waitUntilLeader(shard);
1222 final TransactionIdentifier transactionID = nextTransactionId();
1223 final MutableCompositeModification modification = new MutableCompositeModification();
1224 modification.addModification(new DeleteModification(YangInstanceIdentifier.EMPTY));
1225 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1226 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1227 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1228 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1229 doReturn(mockCandidate("cohort1-candidate")).when(cohort).getCandidate();
1231 final FiniteDuration duration = duration("5 seconds");
1233 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1234 expectMsgClass(duration, ReadyTransactionReply.class);
1236 // Send the CanCommitTransaction message.
1238 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1239 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1240 expectMsgClass(duration, CanCommitTransactionReply.class));
1241 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1243 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1244 expectMsgClass(duration, CommitTransactionReply.class);
1246 final InOrder inOrder = inOrder(cohort);
1247 inOrder.verify(cohort).canCommit();
1248 inOrder.verify(cohort).preCommit();
1249 inOrder.verify(cohort).commit();
1251 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1252 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1254 // Use MBean for verification
1255 // Committed transaction count should increase as usual
1256 assertEquals(1, shardStats.getCommittedTransactionsCount());
1258 // Commit index should advance as we do not have an empty modification
1259 assertEquals(0, shardStats.getCommitIndex());
1265 public void testCommitPhaseFailure() throws Throwable {
1266 testCommitPhaseFailure(true);
1267 testCommitPhaseFailure(false);
1270 private void testCommitPhaseFailure(final boolean readWrite) throws Throwable {
1271 new ShardTestKit(getSystem()) {{
1272 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1273 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1274 "testCommitPhaseFailure-" + readWrite);
1276 waitUntilLeader(shard);
1278 // Setup 2 simulated transactions with mock cohorts. The first one fails in the
1281 final TransactionIdentifier transactionID1 = nextTransactionId();
1282 final MutableCompositeModification modification1 = new MutableCompositeModification();
1283 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1284 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1285 doReturn(Futures.immediateFuture(null)).when(cohort1).preCommit();
1286 doReturn(Futures.immediateFailedFuture(new RuntimeException("mock"))).when(cohort1).commit();
1287 doReturn(mockCandidate("cohort1-candidate")).when(cohort1).getCandidate();
1289 final TransactionIdentifier transactionID2 = nextTransactionId();
1290 final MutableCompositeModification modification2 = new MutableCompositeModification();
1291 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1292 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1294 final FiniteDuration duration = duration("5 seconds");
1295 final Timeout timeout = new Timeout(duration);
1297 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1298 expectMsgClass(duration, ReadyTransactionReply.class);
1300 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1301 expectMsgClass(duration, ReadyTransactionReply.class);
1303 // Send the CanCommitTransaction message for the first Tx.
1305 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1306 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1307 expectMsgClass(duration, CanCommitTransactionReply.class));
1308 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1310 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1311 // processed after the first Tx completes.
1313 final Future<Object> canCommitFuture = Patterns.ask(shard,
1314 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1316 // Send the CommitTransaction message for the first Tx. This should send back an error
1317 // and trigger the 2nd Tx to proceed.
1319 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1320 expectMsgClass(duration, akka.actor.Status.Failure.class);
1322 // Wait for the 2nd Tx to complete the canCommit phase.
1324 final CountDownLatch latch = new CountDownLatch(1);
1325 canCommitFuture.onComplete(new OnComplete<Object>() {
1327 public void onComplete(final Throwable t, final Object resp) {
1330 }, getSystem().dispatcher());
1332 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1334 final InOrder inOrder = inOrder(cohort1, cohort2);
1335 inOrder.verify(cohort1).canCommit();
1336 inOrder.verify(cohort1).preCommit();
1337 inOrder.verify(cohort1).commit();
1338 inOrder.verify(cohort2).canCommit();
1343 public void testPreCommitPhaseFailure() throws Throwable {
1344 testPreCommitPhaseFailure(true);
1345 testPreCommitPhaseFailure(false);
1348 private void testPreCommitPhaseFailure(final boolean readWrite) throws Throwable {
1349 new ShardTestKit(getSystem()) {{
1350 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1351 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1352 "testPreCommitPhaseFailure-" + readWrite);
1354 waitUntilLeader(shard);
1356 final TransactionIdentifier transactionID1 = nextTransactionId();
1357 final MutableCompositeModification modification1 = new MutableCompositeModification();
1358 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1359 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1360 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).preCommit();
1362 final TransactionIdentifier transactionID2 = nextTransactionId();
1363 final MutableCompositeModification modification2 = new MutableCompositeModification();
1364 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1365 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1367 final FiniteDuration duration = duration("5 seconds");
1368 final Timeout timeout = new Timeout(duration);
1370 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1371 expectMsgClass(duration, ReadyTransactionReply.class);
1373 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1374 expectMsgClass(duration, ReadyTransactionReply.class);
1376 // Send the CanCommitTransaction message for the first Tx.
1378 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1379 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1380 expectMsgClass(duration, CanCommitTransactionReply.class));
1381 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1383 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1384 // processed after the first Tx completes.
1386 final Future<Object> canCommitFuture = Patterns.ask(shard,
1387 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1389 // Send the CommitTransaction message for the first Tx. This should send back an error
1390 // and trigger the 2nd Tx to proceed.
1392 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1393 expectMsgClass(duration, akka.actor.Status.Failure.class);
1395 // Wait for the 2nd Tx to complete the canCommit phase.
1397 final CountDownLatch latch = new CountDownLatch(1);
1398 canCommitFuture.onComplete(new OnComplete<Object>() {
1400 public void onComplete(final Throwable t, final Object resp) {
1403 }, getSystem().dispatcher());
1405 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1407 final InOrder inOrder = inOrder(cohort1, cohort2);
1408 inOrder.verify(cohort1).canCommit();
1409 inOrder.verify(cohort1).preCommit();
1410 inOrder.verify(cohort2).canCommit();
1415 public void testCanCommitPhaseFailure() throws Throwable {
1416 testCanCommitPhaseFailure(true);
1417 testCanCommitPhaseFailure(false);
1420 private void testCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1421 new ShardTestKit(getSystem()) {{
1422 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1423 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1424 "testCanCommitPhaseFailure-" + readWrite);
1426 waitUntilLeader(shard);
1428 final FiniteDuration duration = duration("5 seconds");
1430 final TransactionIdentifier transactionID1 = nextTransactionId();
1431 final MutableCompositeModification modification = new MutableCompositeModification();
1432 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1433 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1435 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1436 expectMsgClass(duration, ReadyTransactionReply.class);
1438 // Send the CanCommitTransaction message.
1440 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1441 expectMsgClass(duration, akka.actor.Status.Failure.class);
1443 // Send another can commit to ensure the failed one got cleaned up.
1447 final TransactionIdentifier transactionID2 = nextTransactionId();
1448 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1450 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1451 expectMsgClass(duration, ReadyTransactionReply.class);
1453 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1454 final CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1455 expectMsgClass(CanCommitTransactionReply.class));
1456 assertEquals("getCanCommit", true, reply.getCanCommit());
1461 public void testCanCommitPhaseFalseResponse() throws Throwable {
1462 testCanCommitPhaseFalseResponse(true);
1463 testCanCommitPhaseFalseResponse(false);
1466 private void testCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1467 new ShardTestKit(getSystem()) {{
1468 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1469 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1470 "testCanCommitPhaseFalseResponse-" + readWrite);
1472 waitUntilLeader(shard);
1474 final FiniteDuration duration = duration("5 seconds");
1476 final TransactionIdentifier transactionID1 = nextTransactionId();
1477 final MutableCompositeModification modification = new MutableCompositeModification();
1478 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1479 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1481 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1482 expectMsgClass(duration, ReadyTransactionReply.class);
1484 // Send the CanCommitTransaction message.
1486 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1487 CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1488 expectMsgClass(CanCommitTransactionReply.class));
1489 assertEquals("getCanCommit", false, reply.getCanCommit());
1491 // Send another can commit to ensure the failed one got cleaned up.
1495 final TransactionIdentifier transactionID2 = nextTransactionId();
1496 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1498 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1499 expectMsgClass(duration, ReadyTransactionReply.class);
1501 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1502 reply = CanCommitTransactionReply.fromSerializable(
1503 expectMsgClass(CanCommitTransactionReply.class));
1504 assertEquals("getCanCommit", true, reply.getCanCommit());
1509 public void testImmediateCommitWithCanCommitPhaseFailure() throws Throwable {
1510 testImmediateCommitWithCanCommitPhaseFailure(true);
1511 testImmediateCommitWithCanCommitPhaseFailure(false);
1514 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1515 new ShardTestKit(getSystem()) {{
1516 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1517 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1518 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1520 waitUntilLeader(shard);
1522 final FiniteDuration duration = duration("5 seconds");
1524 final TransactionIdentifier transactionID1 = nextTransactionId();
1525 final MutableCompositeModification modification = new MutableCompositeModification();
1526 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1527 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1529 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification, true), getRef());
1531 expectMsgClass(duration, akka.actor.Status.Failure.class);
1533 // Send another can commit to ensure the failed one got cleaned up.
1537 final TransactionIdentifier transactionID2 = nextTransactionId();
1538 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1539 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1540 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1541 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1542 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1543 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1544 doReturn(candidateRoot).when(candidate).getRootNode();
1545 doReturn(YangInstanceIdentifier.EMPTY).when(candidate).getRootPath();
1546 doReturn(candidate).when(cohort).getCandidate();
1548 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1550 expectMsgClass(duration, CommitTransactionReply.class);
1555 public void testImmediateCommitWithCanCommitPhaseFalseResponse() throws Throwable {
1556 testImmediateCommitWithCanCommitPhaseFalseResponse(true);
1557 testImmediateCommitWithCanCommitPhaseFalseResponse(false);
1560 private void testImmediateCommitWithCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1561 new ShardTestKit(getSystem()) {{
1562 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1563 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1564 "testImmediateCommitWithCanCommitPhaseFalseResponse-" + readWrite);
1566 waitUntilLeader(shard);
1568 final FiniteDuration duration = duration("5 seconds");
1570 final TransactionIdentifier transactionID1 = nextTransactionId();
1571 final MutableCompositeModification modification = new MutableCompositeModification();
1572 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1573 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1575 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification, true), getRef());
1577 expectMsgClass(duration, akka.actor.Status.Failure.class);
1579 // Send another can commit to ensure the failed one got cleaned up.
1583 final TransactionIdentifier transactionID2 = nextTransactionId();
1584 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1585 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1586 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1587 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1588 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1589 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1590 doReturn(candidateRoot).when(candidate).getRootNode();
1591 doReturn(YangInstanceIdentifier.EMPTY).when(candidate).getRootPath();
1592 doReturn(candidate).when(cohort).getCandidate();
1594 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1596 expectMsgClass(duration, CommitTransactionReply.class);
1601 public void testAbortBeforeFinishCommit() throws Throwable {
1602 testAbortBeforeFinishCommit(true);
1603 testAbortBeforeFinishCommit(false);
1606 private void testAbortBeforeFinishCommit(final boolean readWrite) throws Throwable {
1607 new ShardTestKit(getSystem()) {{
1608 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1609 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1610 "testAbortBeforeFinishCommit-" + readWrite);
1612 waitUntilLeader(shard);
1614 final FiniteDuration duration = duration("5 seconds");
1615 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1617 final TransactionIdentifier transactionID = nextTransactionId();
1618 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit =
1620 final ListenableFuture<Void> preCommitFuture = cohort.preCommit();
1622 // Simulate an AbortTransaction message occurring during replication, after
1623 // persisting and before finishing the commit to the in-memory store.
1624 // We have no followers so due to optimizations in the RaftActor, it does not
1625 // attempt replication and thus we can't send an AbortTransaction message b/c
1626 // it would be processed too late after CommitTransaction completes. So we'll
1627 // simulate an AbortTransaction message occurring during replication by calling
1628 // the shard directly.
1630 shard.underlyingActor().doAbortTransaction(transactionID, null);
1632 return preCommitFuture;
1635 final MutableCompositeModification modification = new MutableCompositeModification();
1636 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort1", dataStore,
1637 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME),
1638 modification, preCommit);
1640 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1641 expectMsgClass(duration, ReadyTransactionReply.class);
1643 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1644 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1645 expectMsgClass(duration, CanCommitTransactionReply.class));
1646 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1648 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1649 expectMsgClass(duration, CommitTransactionReply.class);
1651 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1653 // Since we're simulating an abort occurring during replication and before finish commit,
1654 // the data should still get written to the in-memory store since we've gotten past
1655 // canCommit and preCommit and persisted the data.
1656 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1661 public void testTransactionCommitTimeout() throws Throwable {
1662 testTransactionCommitTimeout(true);
1663 testTransactionCommitTimeout(false);
1666 private void testTransactionCommitTimeout(final boolean readWrite) throws Throwable {
1667 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1669 new ShardTestKit(getSystem()) {{
1670 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1671 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1672 "testTransactionCommitTimeout-" + readWrite);
1674 waitUntilLeader(shard);
1676 final FiniteDuration duration = duration("5 seconds");
1678 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1680 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1681 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1682 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1684 // Create 1st Tx - will timeout
1686 final TransactionIdentifier transactionID1 = nextTransactionId();
1687 final MutableCompositeModification modification1 = new MutableCompositeModification();
1688 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1689 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1690 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1691 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
1696 final TransactionIdentifier transactionID2 = nextTransactionId();
1697 final MutableCompositeModification modification2 = new MutableCompositeModification();
1698 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1699 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1700 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort3", dataStore,
1702 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2),
1707 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1708 expectMsgClass(duration, ReadyTransactionReply.class);
1710 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1711 expectMsgClass(duration, ReadyTransactionReply.class);
1713 // canCommit 1st Tx. We don't send the commit so it should timeout.
1715 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1716 expectMsgClass(duration, CanCommitTransactionReply.class);
1718 // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1720 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1721 expectMsgClass(duration, CanCommitTransactionReply.class);
1723 // Try to commit the 1st Tx - should fail as it's not the current Tx.
1725 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1726 expectMsgClass(duration, akka.actor.Status.Failure.class);
1728 // Commit the 2nd Tx.
1730 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1731 expectMsgClass(duration, CommitTransactionReply.class);
1733 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1734 assertNotNull(listNodePath + " not found", node);
1739 public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1740 dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1742 new ShardTestKit(getSystem()) {{
1743 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1744 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1745 "testTransactionCommitQueueCapacityExceeded");
1747 waitUntilLeader(shard);
1749 final FiniteDuration duration = duration("5 seconds");
1751 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1753 final TransactionIdentifier transactionID1 = nextTransactionId();
1754 final MutableCompositeModification modification1 = new MutableCompositeModification();
1755 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1756 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1758 final TransactionIdentifier transactionID2 = nextTransactionId();
1759 final MutableCompositeModification modification2 = new MutableCompositeModification();
1760 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1761 TestModel.OUTER_LIST_PATH,
1762 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
1765 final TransactionIdentifier transactionID3 = nextTransactionId();
1766 final MutableCompositeModification modification3 = new MutableCompositeModification();
1767 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1768 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification3);
1772 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1773 expectMsgClass(duration, ReadyTransactionReply.class);
1775 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1776 expectMsgClass(duration, ReadyTransactionReply.class);
1778 // The 3rd Tx should exceed queue capacity and fail.
1780 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1781 expectMsgClass(duration, akka.actor.Status.Failure.class);
1783 // canCommit 1st Tx.
1785 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1786 expectMsgClass(duration, CanCommitTransactionReply.class);
1788 // canCommit the 2nd Tx - it should get queued.
1790 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1792 // canCommit the 3rd Tx - should exceed queue capacity and fail.
1794 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1795 expectMsgClass(duration, akka.actor.Status.Failure.class);
1800 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Throwable {
1801 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1803 new ShardTestKit(getSystem()) {{
1804 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1805 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1806 "testTransactionCommitWithPriorExpiredCohortEntries");
1808 waitUntilLeader(shard);
1810 final FiniteDuration duration = duration("5 seconds");
1812 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1814 final TransactionIdentifier transactionID1 = nextTransactionId();
1815 final MutableCompositeModification modification1 = new MutableCompositeModification();
1816 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1817 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1819 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1820 expectMsgClass(duration, ReadyTransactionReply.class);
1822 final TransactionIdentifier transactionID2 = nextTransactionId();
1823 final MutableCompositeModification modification2 = new MutableCompositeModification();
1824 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1825 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1827 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1828 expectMsgClass(duration, ReadyTransactionReply.class);
1830 final TransactionIdentifier transactionID3 = nextTransactionId();
1831 final MutableCompositeModification modification3 = new MutableCompositeModification();
1832 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1833 TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME), modification3);
1835 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1836 expectMsgClass(duration, ReadyTransactionReply.class);
1838 // All Tx's are readied. We'll send canCommit for the last one but not the others. The others
1839 // should expire from the queue and the last one should be processed.
1841 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1842 expectMsgClass(duration, CanCommitTransactionReply.class);
1847 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Throwable {
1848 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1850 new ShardTestKit(getSystem()) {{
1851 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1852 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1853 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1855 waitUntilLeader(shard);
1857 final FiniteDuration duration = duration("5 seconds");
1859 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1861 final TransactionIdentifier transactionID1 = nextTransactionId();
1862 final MutableCompositeModification modification1 = new MutableCompositeModification();
1863 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1864 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1866 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1867 expectMsgClass(duration, ReadyTransactionReply.class);
1869 // CanCommit the first one so it's the current in-progress CohortEntry.
1871 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1872 expectMsgClass(duration, CanCommitTransactionReply.class);
1874 // Ready the second Tx.
1876 final TransactionIdentifier transactionID2 = nextTransactionId();
1877 final MutableCompositeModification modification2 = new MutableCompositeModification();
1878 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1879 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1881 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1882 expectMsgClass(duration, ReadyTransactionReply.class);
1884 // Ready the third Tx.
1886 final TransactionIdentifier transactionID3 = nextTransactionId();
1887 final DataTreeModification modification3 = dataStore.newModification();
1888 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1889 .apply(modification3);
1890 modification3.ready();
1891 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3, true);
1893 shard.tell(readyMessage, getRef());
1895 // Commit the first Tx. After completing, the second should expire from the queue and the third
1898 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1899 expectMsgClass(duration, CommitTransactionReply.class);
1901 // Expect commit reply from the third Tx.
1903 expectMsgClass(duration, CommitTransactionReply.class);
1905 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1906 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1911 public void testCanCommitBeforeReadyFailure() throws Throwable {
1912 new ShardTestKit(getSystem()) {{
1913 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1914 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1915 "testCanCommitBeforeReadyFailure");
1917 shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
1918 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1923 public void testAbortCurrentTransaction() throws Throwable {
1924 testAbortCurrentTransaction(true);
1925 testAbortCurrentTransaction(false);
1928 private void testAbortCurrentTransaction(final boolean readWrite) throws Throwable {
1929 new ShardTestKit(getSystem()) {{
1930 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1931 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1932 "testAbortCurrentTransaction-" + readWrite);
1934 waitUntilLeader(shard);
1936 // Setup 2 simulated transactions with mock cohorts. The first one will be aborted.
1938 final TransactionIdentifier transactionID1 = nextTransactionId();
1939 final MutableCompositeModification modification1 = new MutableCompositeModification();
1940 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1941 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1942 doReturn(Futures.immediateFuture(null)).when(cohort1).abort();
1944 final TransactionIdentifier transactionID2 = nextTransactionId();
1945 final MutableCompositeModification modification2 = new MutableCompositeModification();
1946 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1947 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1949 final FiniteDuration duration = duration("5 seconds");
1950 final Timeout timeout = new Timeout(duration);
1952 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1953 expectMsgClass(duration, ReadyTransactionReply.class);
1955 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1956 expectMsgClass(duration, ReadyTransactionReply.class);
1958 // Send the CanCommitTransaction message for the first Tx.
1960 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1961 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1962 expectMsgClass(duration, CanCommitTransactionReply.class));
1963 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1965 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1966 // processed after the first Tx completes.
1968 final Future<Object> canCommitFuture = Patterns.ask(shard,
1969 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1971 // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1974 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1975 expectMsgClass(duration, AbortTransactionReply.class);
1977 // Wait for the 2nd Tx to complete the canCommit phase.
1979 Await.ready(canCommitFuture, duration);
1981 final InOrder inOrder = inOrder(cohort1, cohort2);
1982 inOrder.verify(cohort1).canCommit();
1983 inOrder.verify(cohort2).canCommit();
1988 public void testAbortQueuedTransaction() throws Throwable {
1989 testAbortQueuedTransaction(true);
1990 testAbortQueuedTransaction(false);
1993 private void testAbortQueuedTransaction(final boolean readWrite) throws Throwable {
1994 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1995 new ShardTestKit(getSystem()) {{
1996 final AtomicReference<CountDownLatch> cleaupCheckLatch = new AtomicReference<>();
1997 @SuppressWarnings("serial")
1998 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
2000 public void handleCommand(final Object message) {
2001 super.handleCommand(message);
2002 if(TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
2003 if(cleaupCheckLatch.get() != null) {
2004 cleaupCheckLatch.get().countDown();
2010 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2011 Props.create(new DelegatingShardCreator(creator)).withDispatcher(
2012 Dispatchers.DefaultDispatcherId()), "testAbortQueuedTransaction-" + readWrite);
2014 waitUntilLeader(shard);
2016 final TransactionIdentifier transactionID = nextTransactionId();
2017 final MutableCompositeModification modification = new MutableCompositeModification();
2018 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort");
2019 doReturn(Futures.immediateFuture(null)).when(cohort).abort();
2021 final FiniteDuration duration = duration("5 seconds");
2025 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
2026 expectMsgClass(duration, ReadyTransactionReply.class);
2028 assertEquals("getPendingTxCommitQueueSize", 1, shard.underlyingActor().getPendingTxCommitQueueSize());
2030 // Send the AbortTransaction message.
2032 shard.tell(new AbortTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2033 expectMsgClass(duration, AbortTransactionReply.class);
2035 verify(cohort).abort();
2037 // Verify the tx cohort is removed from queue at the cleanup check interval.
2039 cleaupCheckLatch.set(new CountDownLatch(1));
2040 assertEquals("TX_COMMIT_TIMEOUT_CHECK_MESSAGE received", true,
2041 cleaupCheckLatch.get().await(5, TimeUnit.SECONDS));
2043 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
2045 // Now send CanCommitTransaction - should fail.
2047 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2049 Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
2050 assertTrue("Failure type", failure instanceof IllegalStateException);
2055 public void testCreateSnapshot() throws Exception {
2056 testCreateSnapshot(true, "testCreateSnapshot");
2060 public void testCreateSnapshotWithNonPersistentData() throws Exception {
2061 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
2064 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
2066 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
2068 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
2069 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
2070 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
2075 public void saveSnapshot(final Object o) {
2076 savedSnapshot.set(o);
2077 super.saveSnapshot(o);
2081 dataStoreContextBuilder.persistent(persistent);
2083 new ShardTestKit(getSystem()) {{
2084 class TestShard extends Shard {
2086 protected TestShard(AbstractBuilder<?, ?> builder) {
2088 setPersistence(new TestPersistentDataProvider(super.persistence()));
2092 public void handleCommand(final Object message) {
2093 super.handleCommand(message);
2095 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
2096 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
2097 latch.get().countDown();
2102 public RaftActorContext getRaftActorContext() {
2103 return super.getRaftActorContext();
2107 final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
2109 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2110 Props.create(new DelegatingShardCreator(creator)).
2111 withDispatcher(Dispatchers.DefaultDispatcherId()), shardActorName);
2113 waitUntilLeader(shard);
2114 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2116 final NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
2118 // Trigger creation of a snapshot by ensuring
2119 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
2120 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2121 awaitAndValidateSnapshot(expectedRoot);
2123 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2124 awaitAndValidateSnapshot(expectedRoot);
2127 private void awaitAndValidateSnapshot(NormalizedNode<?,?> expectedRoot) throws InterruptedException, IOException {
2128 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
2130 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
2131 savedSnapshot.get() instanceof Snapshot);
2133 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
2135 latch.set(new CountDownLatch(1));
2136 savedSnapshot.set(null);
2139 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?,?> expectedRoot) throws IOException {
2140 final NormalizedNode<?, ?> actual = ShardDataTreeSnapshot.deserialize(snapshot.getState()).getRootNode().get();
2141 assertEquals("Root node", expectedRoot, actual);
2146 * This test simply verifies that the applySnapShot logic will work
2147 * @throws ReadFailedException
2148 * @throws DataValidationFailedException
2151 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
2152 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
2153 store.setSchemaContext(SCHEMA_CONTEXT);
2155 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
2156 putTransaction.write(TestModel.TEST_PATH,
2157 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2158 commitTransaction(store, putTransaction);
2161 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
2163 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2165 writeTransaction.delete(YangInstanceIdentifier.EMPTY);
2166 writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
2168 commitTransaction(store, writeTransaction);
2170 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
2172 assertEquals(expected, actual);
2176 public void testRecoveryApplicable(){
2178 final DatastoreContext persistentContext = DatastoreContext.newBuilder().
2179 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2181 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext).
2182 schemaContext(SCHEMA_CONTEXT).props();
2184 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
2185 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2187 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext).
2188 schemaContext(SCHEMA_CONTEXT).props();
2190 new ShardTestKit(getSystem()) {{
2191 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2193 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2195 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2197 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2202 public void testOnDatastoreContext() {
2203 new ShardTestKit(getSystem()) {{
2204 dataStoreContextBuilder.persistent(true);
2206 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
2208 assertEquals("isRecoveryApplicable", true,
2209 shard.underlyingActor().persistence().isRecoveryApplicable());
2211 waitUntilLeader(shard);
2213 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2215 assertEquals("isRecoveryApplicable", false,
2216 shard.underlyingActor().persistence().isRecoveryApplicable());
2218 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2220 assertEquals("isRecoveryApplicable", true,
2221 shard.underlyingActor().persistence().isRecoveryApplicable());
2226 public void testRegisterRoleChangeListener() throws Exception {
2227 new ShardTestKit(getSystem()) {
2229 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2230 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2231 "testRegisterRoleChangeListener");
2233 waitUntilLeader(shard);
2235 final TestActorRef<MessageCollectorActor> listener =
2236 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2238 shard.tell(new RegisterRoleChangeListener(), listener);
2240 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2242 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2243 ShardLeaderStateChanged.class);
2244 assertEquals("getLocalShardDataTree present", true,
2245 leaderStateChanged.getLocalShardDataTree().isPresent());
2246 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2247 leaderStateChanged.getLocalShardDataTree().get());
2249 MessageCollectorActor.clearMessages(listener);
2251 // Force a leader change
2253 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2255 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2256 ShardLeaderStateChanged.class);
2257 assertEquals("getLocalShardDataTree present", false,
2258 leaderStateChanged.getLocalShardDataTree().isPresent());
2264 public void testFollowerInitialSyncStatus() throws Exception {
2265 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2266 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2267 "testFollowerInitialSyncStatus");
2269 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
2271 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2273 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
2275 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2279 public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
2280 new ShardTestKit(getSystem()) {{
2281 String testName = "testClusteredDataChangeListenerDelayedRegistration";
2282 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2283 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2285 final MockDataChangeListener listener = new MockDataChangeListener(1);
2286 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2287 actorFactory.generateActorId(testName + "-DataChangeListener"));
2289 setupInMemorySnapshotStore();
2291 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2292 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2293 actorFactory.generateActorId(testName + "-shard"));
2295 waitUntilNoLeader(shard);
2297 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2299 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2300 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2301 RegisterChangeListenerReply.class);
2302 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2304 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2305 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2307 listener.waitForChangeEvents();
2312 public void testClusteredDataChangeListenerRegistration() throws Exception {
2313 new ShardTestKit(getSystem()) {{
2314 String testName = "testClusteredDataChangeListenerRegistration";
2315 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2316 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2318 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2319 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2321 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2322 Shard.builder().id(followerShardID).
2323 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2324 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2325 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2326 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2328 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2329 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2330 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2331 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2332 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2334 leaderShard.tell(ElectionTimeout.INSTANCE, ActorRef.noSender());
2335 String leaderPath = waitUntilLeader(followerShard);
2336 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2338 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2339 final MockDataChangeListener listener = new MockDataChangeListener(1);
2340 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2341 actorFactory.generateActorId(testName + "-DataChangeListener"));
2343 followerShard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2344 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2345 RegisterChangeListenerReply.class);
2346 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2348 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2350 listener.waitForChangeEvents();
2355 public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
2356 new ShardTestKit(getSystem()) {{
2357 String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
2358 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2359 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2361 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2362 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2363 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2365 setupInMemorySnapshotStore();
2367 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2368 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2369 actorFactory.generateActorId(testName + "-shard"));
2371 waitUntilNoLeader(shard);
2373 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2375 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2376 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2377 RegisterDataTreeChangeListenerReply.class);
2378 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2380 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2381 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2383 listener.waitForChangeEvents();
2388 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2389 new ShardTestKit(getSystem()) {{
2390 String testName = "testClusteredDataTreeChangeListenerRegistration";
2391 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2392 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2394 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2395 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2397 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2398 Shard.builder().id(followerShardID).
2399 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2400 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2401 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2402 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2404 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2405 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2406 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2407 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2408 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2410 leaderShard.tell(ElectionTimeout.INSTANCE, ActorRef.noSender());
2411 String leaderPath = waitUntilLeader(followerShard);
2412 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2414 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2415 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2416 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2417 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2419 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2420 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2421 RegisterDataTreeChangeListenerReply.class);
2422 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2424 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2426 listener.waitForChangeEvents();
2431 public void testServerRemoved() throws Exception {
2432 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2434 final ActorRef shard = parent.underlyingActor().context().actorOf(
2435 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2436 "testServerRemoved");
2438 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2440 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);