Alleviate premature elections in followers
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / ShardTest.java
1 /*
2  * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.datastore;
10
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;
42 import java.util.Set;
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.base.messages.TimeoutNow;
97 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
98 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
99 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
100 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
101 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
102 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
103 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
104 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
105 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
106 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
107 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
108 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
109 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
110 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
111 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
117 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
118 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
119 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
120 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
121 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
122 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
123 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
124 import scala.concurrent.Await;
125 import scala.concurrent.Future;
126 import scala.concurrent.duration.FiniteDuration;
127
128 public class ShardTest extends AbstractShardTest {
129     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";
130
131     @Test
132     public void testRegisterChangeListener() throws Exception {
133         new ShardTestKit(getSystem()) {{
134             final TestActorRef<Shard> shard = actorFactory.createTestActor(
135                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterChangeListener");
136
137             waitUntilLeader(shard);
138
139             shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
140
141             final MockDataChangeListener listener = new MockDataChangeListener(1);
142             final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
143                     "testRegisterChangeListener-DataChangeListener");
144
145             shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
146                     dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
147
148             final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
149                     RegisterChangeListenerReply.class);
150             final String replyPath = reply.getListenerRegistrationPath().toString();
151             assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
152                     "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
153
154             final YangInstanceIdentifier path = TestModel.TEST_PATH;
155             writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
156
157             listener.waitForChangeEvents(path);
158         }};
159     }
160
161     @SuppressWarnings("serial")
162     @Test
163     public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
164         // This test tests the timing window in which a change listener is registered before the
165         // shard becomes the leader. We verify that the listener is registered and notified of the
166         // existing data when the shard becomes the leader.
167         new ShardTestKit(getSystem()) {{
168             // For this test, we want to send the RegisterChangeListener message after the shard
169             // has recovered from persistence and before it becomes the leader. So we subclass
170             // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
171             // we know that the shard has been initialized to a follower and has started the
172             // election process. The following 2 CountDownLatches are used to coordinate the
173             // ElectionTimeout with the sending of the RegisterChangeListener message.
174             final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
175             final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
176             final Creator<Shard> creator = new Creator<Shard>() {
177                 boolean firstElectionTimeout = true;
178
179                 @Override
180                 public Shard create() throws Exception {
181                     // Use a non persistent provider because this test actually invokes persist on the journal
182                     // this will cause all other messages to not be queued properly after that.
183                     // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
184                     // it does do a persist)
185                     return new Shard(newShardBuilder()) {
186                         @Override
187                         public void handleCommand(final Object message) {
188                             if(message instanceof ElectionTimeout && firstElectionTimeout) {
189                                 // Got the first ElectionTimeout. We don't forward it to the
190                                 // base Shard yet until we've sent the RegisterChangeListener
191                                 // message. So we signal the onFirstElectionTimeout latch to tell
192                                 // the main thread to send the RegisterChangeListener message and
193                                 // start a thread to wait on the onChangeListenerRegistered latch,
194                                 // which the main thread signals after it has sent the message.
195                                 // After the onChangeListenerRegistered is triggered, we send the
196                                 // original ElectionTimeout message to proceed with the election.
197                                 firstElectionTimeout = false;
198                                 final ActorRef self = getSelf();
199                                 new Thread() {
200                                     @Override
201                                     public void run() {
202                                         Uninterruptibles.awaitUninterruptibly(
203                                                 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
204                                         self.tell(message, self);
205                                     }
206                                 }.start();
207
208                                 onFirstElectionTimeout.countDown();
209                             } else {
210                                 super.handleCommand(message);
211                             }
212                         }
213                     };
214                 }
215             };
216
217             setupInMemorySnapshotStore();
218
219             final MockDataChangeListener listener = new MockDataChangeListener(1);
220             final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
221                     "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
222
223             final TestActorRef<Shard> shard = actorFactory.createTestActor(
224                     Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
225                     "testRegisterChangeListenerWhenNotLeaderInitially");
226
227             final YangInstanceIdentifier path = TestModel.TEST_PATH;
228
229             // Wait until the shard receives the first ElectionTimeout message.
230             assertEquals("Got first ElectionTimeout", true,
231                     onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
232
233             // Now send the RegisterChangeListener and wait for the reply.
234             shard.tell(new RegisterChangeListener(path, dclActor,
235                     AsyncDataBroker.DataChangeScope.SUBTREE, false), getRef());
236
237             final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
238                     RegisterChangeListenerReply.class);
239             assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
240
241             // Sanity check - verify the shard is not the leader yet.
242             shard.tell(FindLeader.INSTANCE, getRef());
243             final FindLeaderReply findLeadeReply =
244                     expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
245             assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
246
247             // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
248             // with the election process.
249             onChangeListenerRegistered.countDown();
250
251             // Wait for the shard to become the leader and notify our listener with the existing
252             // data in the store.
253             listener.waitForChangeEvents(path);
254         }};
255     }
256
257     @Test
258     public void testRegisterDataTreeChangeListener() throws Exception {
259         new ShardTestKit(getSystem()) {{
260             final TestActorRef<Shard> shard = actorFactory.createTestActor(
261                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterDataTreeChangeListener");
262
263             waitUntilLeader(shard);
264
265             shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
266
267             final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
268             final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
269                     "testRegisterDataTreeChangeListener-DataTreeChangeListener");
270
271             shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
272
273             final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
274                     RegisterDataTreeChangeListenerReply.class);
275             final String replyPath = reply.getListenerRegistrationPath().toString();
276             assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
277                     "akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
278
279             final YangInstanceIdentifier path = TestModel.TEST_PATH;
280             writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
281
282             listener.waitForChangeEvents();
283         }};
284     }
285
286     @SuppressWarnings("serial")
287     @Test
288     public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
289         new ShardTestKit(getSystem()) {{
290             final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
291             final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
292             final Creator<Shard> creator = new Creator<Shard>() {
293                 boolean firstElectionTimeout = true;
294
295                 @Override
296                 public Shard create() throws Exception {
297                     return new Shard(newShardBuilder()) {
298                         @Override
299                         public void handleCommand(final Object message) {
300                             if(message instanceof ElectionTimeout && firstElectionTimeout) {
301                                 firstElectionTimeout = false;
302                                 final ActorRef self = getSelf();
303                                 new Thread() {
304                                     @Override
305                                     public void run() {
306                                         Uninterruptibles.awaitUninterruptibly(
307                                                 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
308                                         self.tell(message, self);
309                                     }
310                                 }.start();
311
312                                 onFirstElectionTimeout.countDown();
313                             } else {
314                                 super.handleCommand(message);
315                             }
316                         }
317                     };
318                 }
319             };
320
321             setupInMemorySnapshotStore();
322
323             final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
324             final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
325                     "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
326
327             final TestActorRef<Shard> shard = actorFactory.createTestActor(
328                     Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
329                     "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
330
331             final YangInstanceIdentifier path = TestModel.TEST_PATH;
332
333             assertEquals("Got first ElectionTimeout", true,
334                 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
335
336             shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
337             final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
338                 RegisterDataTreeChangeListenerReply.class);
339             assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
340
341             shard.tell(FindLeader.INSTANCE, getRef());
342             final FindLeaderReply findLeadeReply =
343                     expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
344             assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
345
346
347             onChangeListenerRegistered.countDown();
348
349             // TODO: investigate why we do not receive data chage events
350             listener.waitForChangeEvents();
351         }};
352     }
353
354     @Test
355     public void testCreateTransaction(){
356         new ShardTestKit(getSystem()) {{
357             final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
358
359             waitUntilLeader(shard);
360
361             shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
362
363             shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
364                     DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
365
366             final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
367                     CreateTransactionReply.class);
368
369             final String path = reply.getTransactionPath().toString();
370             assertTrue("Unexpected transaction path " + path,
371                     path.startsWith("akka://test/user/testCreateTransaction/shard-member-1:ShardTransactionTest@0:"));
372         }};
373     }
374
375     @Test
376     public void testCreateTransactionOnChain(){
377         new ShardTestKit(getSystem()) {{
378             final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
379
380             waitUntilLeader(shard);
381
382             shard.tell(new CreateTransaction(nextTransactionId(),TransactionType.READ_ONLY.ordinal(),
383                     DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
384
385             final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
386                     CreateTransactionReply.class);
387
388             final String path = reply.getTransactionPath().toString();
389             assertTrue("Unexpected transaction path " + path,
390                     path.startsWith("akka://test/user/testCreateTransactionOnChain/shard-member-1:ShardTransactionTest@0:"));
391         }};
392     }
393
394     @Test
395     public void testPeerAddressResolved() throws Exception {
396         new ShardTestKit(getSystem()) {{
397             ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"), "config");
398             final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder().
399                     peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null)).props().
400                         withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
401
402             final String address = "akka://foobar";
403             shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
404
405             shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
406             OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
407             assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
408         }};
409     }
410
411     @Test
412     public void testApplySnapshot() throws Exception {
413
414         final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testApplySnapshot");
415
416         ShardTestKit.waitUntilLeader(shard);
417
418         final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
419         store.setSchemaContext(SCHEMA_CONTEXT);
420
421         final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
422                 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
423                     withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
424                         ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
425
426         writeToStore(store, TestModel.TEST_PATH, container);
427
428         final YangInstanceIdentifier root = YangInstanceIdentifier.EMPTY;
429         final NormalizedNode<?,?> expected = readStore(store, root);
430
431         final Snapshot snapshot = Snapshot.create(new PreBoronShardDataTreeSnapshot(expected).serialize(),
432                 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
433
434         shard.underlyingActor().getRaftActorSnapshotCohort().applySnapshot(snapshot.getState());
435
436         final NormalizedNode<?,?> actual = readStore(shard, root);
437
438         assertEquals("Root node", expected, actual);
439     }
440
441     @Test
442     public void testApplyState() throws Exception {
443         final TestActorRef<Shard> shard = actorFactory.createTestActor(
444                 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");
445
446         ShardTestKit.waitUntilLeader(shard);
447
448         final DataTree source = setupInMemorySnapshotStore();
449         final DataTreeModification writeMod = source.takeSnapshot().newModification();
450         ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
451         writeMod.write(TestModel.TEST_PATH, node);
452         writeMod.ready();
453
454         final TransactionIdentifier tx = nextTransactionId();
455         final ApplyState applyState = new ApplyState(null, tx,
456             new ReplicatedLogImplEntry(1, 2, payloadForModification(source, writeMod, tx)));
457
458         shard.tell(applyState, shard);
459
460         Stopwatch sw = Stopwatch.createStarted();
461         while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
462             Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
463
464             final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
465             if(actual != null) {
466                 assertEquals("Applied state", node, actual);
467                 return;
468             }
469         }
470
471         fail("State was not applied");
472     }
473
474     @Test
475     public void testDataTreeCandidateRecovery() throws Exception {
476         // Set up the InMemorySnapshotStore.
477         final DataTree source = setupInMemorySnapshotStore();
478
479         final DataTreeModification writeMod = source.takeSnapshot().newModification();
480         writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
481         writeMod.ready();
482         InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
483
484         // Set up the InMemoryJournal.
485         InMemoryJournal.addEntry(shardID.toString(), 1, new ReplicatedLogImplEntry(0, 1,
486             payloadForModification(source, writeMod, nextTransactionId())));
487
488         final int nListEntries = 16;
489         final Set<Integer> listEntryKeys = new HashSet<>();
490
491         // Add some ModificationPayload entries
492         for (int i = 1; i <= nListEntries; i++) {
493             listEntryKeys.add(Integer.valueOf(i));
494
495             final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
496                     .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
497
498             final DataTreeModification mod = source.takeSnapshot().newModification();
499             mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
500             mod.ready();
501
502             InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
503                 payloadForModification(source, mod, nextTransactionId())));
504         }
505
506         InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
507             new ApplyJournalEntries(nListEntries));
508
509         testRecovery(listEntryKeys);
510     }
511
512     @Test
513     public void testConcurrentThreePhaseCommits() throws Throwable {
514         new ShardTestKit(getSystem()) {{
515             final TestActorRef<Shard> shard = actorFactory.createTestActor(
516                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
517                     "testConcurrentThreePhaseCommits");
518
519             waitUntilLeader(shard);
520
521             // Setup 3 simulated transactions with mock cohorts backed by real cohorts.
522
523             final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
524
525             final TransactionIdentifier transactionID1 = nextTransactionId();
526             final MutableCompositeModification modification1 = new MutableCompositeModification();
527             final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
528                     TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
529
530             final TransactionIdentifier transactionID2 = nextTransactionId();
531             final MutableCompositeModification modification2 = new MutableCompositeModification();
532             final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
533                     TestModel.OUTER_LIST_PATH,
534                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
535                     modification2);
536
537             final TransactionIdentifier transactionID3 = nextTransactionId();
538             final MutableCompositeModification modification3 = new MutableCompositeModification();
539             final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
540                     YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
541                         .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
542                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
543                     modification3);
544
545             final long timeoutSec = 5;
546             final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
547             final Timeout timeout = new Timeout(duration);
548
549             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
550             final ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
551                     expectMsgClass(duration, ReadyTransactionReply.class));
552             assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
553
554             // Send the CanCommitTransaction message for the first Tx.
555
556             shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
557             final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
558                     expectMsgClass(duration, CanCommitTransactionReply.class));
559             assertEquals("Can commit", true, canCommitReply.getCanCommit());
560
561             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
562             expectMsgClass(duration, ReadyTransactionReply.class);
563
564             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
565             expectMsgClass(duration, ReadyTransactionReply.class);
566
567             // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
568             // processed after the first Tx completes.
569
570             final Future<Object> canCommitFuture1 = Patterns.ask(shard,
571                     new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
572
573             final Future<Object> canCommitFuture2 = Patterns.ask(shard,
574                     new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
575
576             // Send the CommitTransaction message for the first Tx. After it completes, it should
577             // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
578
579             shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
580             expectMsgClass(duration, CommitTransactionReply.class);
581
582             // Wait for the next 2 Tx's to complete.
583
584             final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
585             final CountDownLatch commitLatch = new CountDownLatch(2);
586
587             class OnFutureComplete extends OnComplete<Object> {
588                 private final Class<?> expRespType;
589
590                 OnFutureComplete(final Class<?> expRespType) {
591                     this.expRespType = expRespType;
592                 }
593
594                 @Override
595                 public void onComplete(final Throwable error, final Object resp) {
596                     if(error != null) {
597                         caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
598                     } else {
599                         try {
600                             assertEquals("Commit response type", expRespType, resp.getClass());
601                             onSuccess(resp);
602                         } catch (final Exception e) {
603                             caughtEx.set(e);
604                         }
605                     }
606                 }
607
608                 void onSuccess(final Object resp) throws Exception {
609                 }
610             }
611
612             class OnCommitFutureComplete extends OnFutureComplete {
613                 OnCommitFutureComplete() {
614                     super(CommitTransactionReply.class);
615                 }
616
617                 @Override
618                 public void onComplete(final Throwable error, final Object resp) {
619                     super.onComplete(error, resp);
620                     commitLatch.countDown();
621                 }
622             }
623
624             class OnCanCommitFutureComplete extends OnFutureComplete {
625                 private final TransactionIdentifier transactionID;
626
627                 OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
628                     super(CanCommitTransactionReply.class);
629                     this.transactionID = transactionID;
630                 }
631
632                 @Override
633                 void onSuccess(final Object resp) throws Exception {
634                     final CanCommitTransactionReply canCommitReply =
635                             CanCommitTransactionReply.fromSerializable(resp);
636                     assertEquals("Can commit", true, canCommitReply.getCanCommit());
637
638                     final Future<Object> commitFuture = Patterns.ask(shard,
639                             new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
640                     commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
641                 }
642             }
643
644             canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
645                     getSystem().dispatcher());
646
647             canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
648                     getSystem().dispatcher());
649
650             final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
651
652             if(caughtEx.get() != null) {
653                 throw caughtEx.get();
654             }
655
656             assertEquals("Commits complete", true, done);
657
658             final InOrder inOrder = inOrder(cohort1, cohort2, cohort3);
659             inOrder.verify(cohort1).canCommit();
660             inOrder.verify(cohort1).preCommit();
661             inOrder.verify(cohort1).commit();
662             inOrder.verify(cohort2).canCommit();
663             inOrder.verify(cohort2).preCommit();
664             inOrder.verify(cohort2).commit();
665             inOrder.verify(cohort3).canCommit();
666             inOrder.verify(cohort3).preCommit();
667             inOrder.verify(cohort3).commit();
668
669             // Verify data in the data store.
670
671             verifyOuterListEntry(shard, 1);
672
673             verifyLastApplied(shard, 2);
674         }};
675     }
676
677     @Test
678     public void testBatchedModificationsWithNoCommitOnReady() throws Throwable {
679         new ShardTestKit(getSystem()) {{
680             final TestActorRef<Shard> shard = actorFactory.createTestActor(
681                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
682                     "testBatchedModificationsWithNoCommitOnReady");
683
684             waitUntilLeader(shard);
685
686             final TransactionIdentifier transactionID = nextTransactionId();
687             final FiniteDuration duration = duration("5 seconds");
688
689             final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
690             final ShardCommitCoordinator.CohortDecorator cohortDecorator = (txID, actual) -> {
691                 if(mockCohort.get() == null) {
692                     mockCohort.set(createDelegatingMockCohort("cohort", actual));
693                 }
694
695                 return mockCohort.get();
696             };
697
698             shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
699
700             // Send a BatchedModifications to start a transaction.
701
702             shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
703                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
704             expectMsgClass(duration, BatchedModificationsReply.class);
705
706             // Send a couple more BatchedModifications.
707
708             shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
709                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
710             expectMsgClass(duration, BatchedModificationsReply.class);
711
712             shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
713                     TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
714                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3), getRef());
715             expectMsgClass(duration, ReadyTransactionReply.class);
716
717             // Send the CanCommitTransaction message.
718
719             shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
720             final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
721                     expectMsgClass(duration, CanCommitTransactionReply.class));
722             assertEquals("Can commit", true, canCommitReply.getCanCommit());
723
724             // Send the CanCommitTransaction message.
725
726             shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
727             expectMsgClass(duration, CommitTransactionReply.class);
728
729             final InOrder inOrder = inOrder(mockCohort.get());
730             inOrder.verify(mockCohort.get()).canCommit();
731             inOrder.verify(mockCohort.get()).preCommit();
732             inOrder.verify(mockCohort.get()).commit();
733
734             // Verify data in the data store.
735
736             verifyOuterListEntry(shard, 1);
737         }};
738     }
739
740     @Test
741     public void testBatchedModificationsWithCommitOnReady() throws Throwable {
742         new ShardTestKit(getSystem()) {{
743             final TestActorRef<Shard> shard = actorFactory.createTestActor(
744                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
745                     "testBatchedModificationsWithCommitOnReady");
746
747             waitUntilLeader(shard);
748
749             final TransactionIdentifier transactionID = nextTransactionId();
750             final FiniteDuration duration = duration("5 seconds");
751
752             final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
753             final ShardCommitCoordinator.CohortDecorator cohortDecorator = (txID, actual) -> {
754                 if(mockCohort.get() == null) {
755                     mockCohort.set(createDelegatingMockCohort("cohort", actual));
756                 }
757
758                 return mockCohort.get();
759             };
760
761             shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
762
763             // Send a BatchedModifications to start a transaction.
764
765             shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
766                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
767             expectMsgClass(duration, BatchedModificationsReply.class);
768
769             // Send a couple more BatchedModifications.
770
771             shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
772                 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
773             expectMsgClass(duration, BatchedModificationsReply.class);
774
775             shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
776                     TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
777                 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3), getRef());
778
779             expectMsgClass(duration, CommitTransactionReply.class);
780
781             final InOrder inOrder = inOrder(mockCohort.get());
782             inOrder.verify(mockCohort.get()).canCommit();
783             inOrder.verify(mockCohort.get()).preCommit();
784             inOrder.verify(mockCohort.get()).commit();
785
786             // Verify data in the data store.
787
788             verifyOuterListEntry(shard, 1);
789         }};
790     }
791
792     @Test(expected=IllegalStateException.class)
793     public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Throwable {
794         new ShardTestKit(getSystem()) {{
795             final TestActorRef<Shard> shard = actorFactory.createTestActor(
796                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
797                     "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
798
799             waitUntilLeader(shard);
800
801             final TransactionIdentifier transactionID = nextTransactionId();
802             final BatchedModifications batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
803             batched.setReady(true);
804             batched.setTotalMessagesSent(2);
805
806             shard.tell(batched, getRef());
807
808             final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
809
810             if(failure != null) {
811                 throw failure.cause();
812             }
813         }};
814     }
815
816     @Test
817     public void testBatchedModificationsWithOperationFailure() throws Throwable {
818         new ShardTestKit(getSystem()) {{
819             final TestActorRef<Shard> shard = actorFactory.createTestActor(
820                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
821                     "testBatchedModificationsWithOperationFailure");
822
823             waitUntilLeader(shard);
824
825             // Test merge with invalid data. An exception should occur when the merge is applied. Note that
826             // write will not validate the children for performance reasons.
827
828             TransactionIdentifier transactionID = nextTransactionId();
829
830             ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
831                     new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
832                         withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
833
834             BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
835             batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
836             shard.tell(batched, getRef());
837             Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
838
839             Throwable cause = failure.cause();
840
841             batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
842             batched.setReady(true);
843             batched.setTotalMessagesSent(2);
844
845             shard.tell(batched, getRef());
846
847             failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
848             assertEquals("Failure cause", cause, failure.cause());
849         }};
850     }
851
852     @Test
853     public void testBatchedModificationsOnTransactionChain() throws Throwable {
854         new ShardTestKit(getSystem()) {{
855             final TestActorRef<Shard> shard = actorFactory.createTestActor(
856                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
857                     "testBatchedModificationsOnTransactionChain");
858
859             waitUntilLeader(shard);
860
861             final LocalHistoryIdentifier historyId = nextHistoryId();
862             final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
863             final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
864
865             final FiniteDuration duration = duration("5 seconds");
866
867             // Send a BatchedModifications to start a chained write transaction and ready it.
868
869             final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
870             final YangInstanceIdentifier path = TestModel.TEST_PATH;
871             shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
872             expectMsgClass(duration, ReadyTransactionReply.class);
873
874             // Create a read Tx on the same chain.
875
876             shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
877                     DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
878
879             final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
880
881             getSystem().actorSelection(createReply.getTransactionPath()).tell(
882                     new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
883             final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
884             assertEquals("Read node", containerNode, readReply.getNormalizedNode());
885
886             // Commit the write transaction.
887
888             shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
889             final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
890                     expectMsgClass(duration, CanCommitTransactionReply.class));
891             assertEquals("Can commit", true, canCommitReply.getCanCommit());
892
893             shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
894             expectMsgClass(duration, CommitTransactionReply.class);
895
896             // Verify data in the data store.
897
898             final NormalizedNode<?, ?> actualNode = readStore(shard, path);
899             assertEquals("Stored node", containerNode, actualNode);
900         }};
901     }
902
903     @Test
904     public void testOnBatchedModificationsWhenNotLeader() {
905         final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
906         new ShardTestKit(getSystem()) {{
907             final Creator<Shard> creator = new Creator<Shard>() {
908                 private static final long serialVersionUID = 1L;
909
910                 @Override
911                 public Shard create() throws Exception {
912                     return new Shard(newShardBuilder()) {
913                         @Override
914                         protected boolean isLeader() {
915                             return overrideLeaderCalls.get() ? false : super.isLeader();
916                         }
917
918                         @Override
919                         protected ActorSelection getLeader() {
920                             return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
921                                 super.getLeader();
922                         }
923                     };
924                 }
925             };
926
927             final TestActorRef<Shard> shard = actorFactory.createTestActor(
928                     Props.create(new DelegatingShardCreator(creator)).
929                         withDispatcher(Dispatchers.DefaultDispatcherId()), "testOnBatchedModificationsWhenNotLeader");
930
931             waitUntilLeader(shard);
932
933             overrideLeaderCalls.set(true);
934
935             final BatchedModifications batched = new BatchedModifications(nextTransactionId(), DataStoreVersions.CURRENT_VERSION);
936
937             shard.tell(batched, ActorRef.noSender());
938
939             expectMsgEquals(batched);
940         }};
941     }
942
943     @Test
944     public void testTransactionMessagesWithNoLeader() {
945         new ShardTestKit(getSystem()) {{
946             dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
947                 shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
948             final TestActorRef<Shard> shard = actorFactory.createTestActor(
949                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
950                     "testTransactionMessagesWithNoLeader");
951
952             waitUntilNoLeader(shard);
953
954             final TransactionIdentifier txId = nextTransactionId();
955             shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
956             Failure failure = expectMsgClass(Failure.class);
957             assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
958
959             shard.tell(prepareForwardedReadyTransaction(mock(ShardDataTreeCohort.class), txId,
960                     DataStoreVersions.CURRENT_VERSION, true), getRef());
961             failure = expectMsgClass(Failure.class);
962             assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
963
964             shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
965             failure = expectMsgClass(Failure.class);
966             assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
967         }};
968     }
969
970     @Test
971     public void testReadyWithReadWriteImmediateCommit() throws Exception{
972         testReadyWithImmediateCommit(true);
973     }
974
975     @Test
976     public void testReadyWithWriteOnlyImmediateCommit() throws Exception{
977         testReadyWithImmediateCommit(false);
978     }
979
980     private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception{
981         new ShardTestKit(getSystem()) {{
982             final TestActorRef<Shard> shard = actorFactory.createTestActor(
983                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
984                     "testReadyWithImmediateCommit-" + readWrite);
985
986             waitUntilLeader(shard);
987
988             final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
989
990             final TransactionIdentifier transactionID = nextTransactionId();
991             final MutableCompositeModification modification = new MutableCompositeModification();
992             final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
993             final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
994                     TestModel.TEST_PATH, containerNode, modification);
995
996             final FiniteDuration duration = duration("5 seconds");
997
998             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
999
1000             expectMsgClass(duration, CommitTransactionReply.class);
1001
1002             final InOrder inOrder = inOrder(cohort);
1003             inOrder.verify(cohort).canCommit();
1004             inOrder.verify(cohort).preCommit();
1005             inOrder.verify(cohort).commit();
1006
1007             final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1008             assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1009         }};
1010     }
1011
1012     @Test
1013     public void testReadyLocalTransactionWithImmediateCommit() throws Exception{
1014         new ShardTestKit(getSystem()) {{
1015             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1016                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1017                     "testReadyLocalTransactionWithImmediateCommit");
1018
1019             waitUntilLeader(shard);
1020
1021             final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1022
1023             final DataTreeModification modification = dataStore.newModification();
1024
1025             final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1026             new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1027             final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1028             new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1029
1030             final TransactionIdentifier txId = nextTransactionId();
1031             modification.ready();
1032             final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1033
1034             shard.tell(readyMessage, getRef());
1035
1036             expectMsgClass(CommitTransactionReply.class);
1037
1038             final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1039             assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1040         }};
1041     }
1042
1043     @Test
1044     public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception{
1045         new ShardTestKit(getSystem()) {{
1046             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1047                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1048                     "testReadyLocalTransactionWithThreePhaseCommit");
1049
1050             waitUntilLeader(shard);
1051
1052             final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1053
1054             final DataTreeModification modification = dataStore.newModification();
1055
1056             final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1057             new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1058             final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1059             new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1060
1061             final TransactionIdentifier txId = nextTransactionId();
1062             modification.ready();
1063             final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1064
1065             shard.tell(readyMessage, getRef());
1066
1067             expectMsgClass(ReadyTransactionReply.class);
1068
1069             // Send the CanCommitTransaction message.
1070
1071             shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1072             final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1073                     expectMsgClass(CanCommitTransactionReply.class));
1074             assertEquals("Can commit", true, canCommitReply.getCanCommit());
1075
1076             // Send the CanCommitTransaction message.
1077
1078             shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1079             expectMsgClass(CommitTransactionReply.class);
1080
1081             final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1082             assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1083         }};
1084     }
1085
1086     @Test
1087     public void testReadWriteCommitWithPersistenceDisabled() throws Throwable {
1088         testCommitWithPersistenceDisabled(true);
1089     }
1090
1091     @Test
1092     public void testWriteOnlyCommitWithPersistenceDisabled() throws Throwable {
1093         testCommitWithPersistenceDisabled(true);
1094     }
1095
1096     private void testCommitWithPersistenceDisabled(final boolean readWrite) throws Throwable {
1097         dataStoreContextBuilder.persistent(false);
1098         new ShardTestKit(getSystem()) {{
1099             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1100                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1101                     "testCommitWithPersistenceDisabled-" + readWrite);
1102
1103             waitUntilLeader(shard);
1104
1105             final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1106
1107             // Setup a simulated transactions with a mock cohort.
1108
1109             final TransactionIdentifier transactionID = nextTransactionId();
1110             final MutableCompositeModification modification = new MutableCompositeModification();
1111             final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1112             final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
1113                 TestModel.TEST_PATH, containerNode, modification);
1114
1115             final FiniteDuration duration = duration("5 seconds");
1116
1117             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1118             expectMsgClass(duration, ReadyTransactionReply.class);
1119
1120             // Send the CanCommitTransaction message.
1121
1122             shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1123             final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1124                     expectMsgClass(duration, CanCommitTransactionReply.class));
1125             assertEquals("Can commit", true, canCommitReply.getCanCommit());
1126
1127             // Send the CanCommitTransaction message.
1128
1129             shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1130             expectMsgClass(duration, CommitTransactionReply.class);
1131
1132             final InOrder inOrder = inOrder(cohort);
1133             inOrder.verify(cohort).canCommit();
1134             inOrder.verify(cohort).preCommit();
1135             inOrder.verify(cohort).commit();
1136
1137             final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1138             assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1139         }};
1140     }
1141
1142     @Test
1143     public void testReadWriteCommitWhenTransactionHasNoModifications() {
1144         testCommitWhenTransactionHasNoModifications(true);
1145     }
1146
1147     @Test
1148     public void testWriteOnlyCommitWhenTransactionHasNoModifications() {
1149         testCommitWhenTransactionHasNoModifications(false);
1150     }
1151
1152     private void testCommitWhenTransactionHasNoModifications(final boolean readWrite){
1153         // Note that persistence is enabled which would normally result in the entry getting written to the journal
1154         // but here that need not happen
1155         new ShardTestKit(getSystem()) {
1156             {
1157                 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1158                         newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1159                         "testCommitWhenTransactionHasNoModifications-" + readWrite);
1160
1161                 waitUntilLeader(shard);
1162
1163                 final TransactionIdentifier transactionID = nextTransactionId();
1164                 final MutableCompositeModification modification = new MutableCompositeModification();
1165                 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1166                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1167                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1168                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1169                 doReturn(mockUnmodifiedCandidate("cohort1-candidate")).when(cohort).getCandidate();
1170
1171                 final FiniteDuration duration = duration("5 seconds");
1172
1173                 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1174                 expectMsgClass(duration, ReadyTransactionReply.class);
1175
1176                 // Send the CanCommitTransaction message.
1177
1178                 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1179                 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1180                         expectMsgClass(duration, CanCommitTransactionReply.class));
1181                 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1182
1183                 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1184                 expectMsgClass(duration, CommitTransactionReply.class);
1185
1186                 final InOrder inOrder = inOrder(cohort);
1187                 inOrder.verify(cohort).canCommit();
1188                 inOrder.verify(cohort).preCommit();
1189                 inOrder.verify(cohort).commit();
1190
1191                 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1192                 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1193
1194                 // Use MBean for verification
1195                 // Committed transaction count should increase as usual
1196                 assertEquals(1,shardStats.getCommittedTransactionsCount());
1197
1198                 // Commit index should not advance because this does not go into the journal
1199                 assertEquals(-1, shardStats.getCommitIndex());
1200             }
1201         };
1202     }
1203
1204     @Test
1205     public void testReadWriteCommitWhenTransactionHasModifications() {
1206         testCommitWhenTransactionHasModifications(true);
1207     }
1208
1209     @Test
1210     public void testWriteOnlyCommitWhenTransactionHasModifications() {
1211         testCommitWhenTransactionHasModifications(false);
1212     }
1213
1214     private void testCommitWhenTransactionHasModifications(final boolean readWrite){
1215         new ShardTestKit(getSystem()) {
1216             {
1217                 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1218                         newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1219                         "testCommitWhenTransactionHasModifications-" + readWrite);
1220
1221                 waitUntilLeader(shard);
1222
1223                 final TransactionIdentifier transactionID = nextTransactionId();
1224                 final MutableCompositeModification modification = new MutableCompositeModification();
1225                 modification.addModification(new DeleteModification(YangInstanceIdentifier.EMPTY));
1226                 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1227                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1228                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1229                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1230                 doReturn(mockCandidate("cohort1-candidate")).when(cohort).getCandidate();
1231
1232                 final FiniteDuration duration = duration("5 seconds");
1233
1234                 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1235                 expectMsgClass(duration, ReadyTransactionReply.class);
1236
1237                 // Send the CanCommitTransaction message.
1238
1239                 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1240                 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1241                         expectMsgClass(duration, CanCommitTransactionReply.class));
1242                 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1243
1244                 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1245                 expectMsgClass(duration, CommitTransactionReply.class);
1246
1247                 final InOrder inOrder = inOrder(cohort);
1248                 inOrder.verify(cohort).canCommit();
1249                 inOrder.verify(cohort).preCommit();
1250                 inOrder.verify(cohort).commit();
1251
1252                 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1253                 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1254
1255                 // Use MBean for verification
1256                 // Committed transaction count should increase as usual
1257                 assertEquals(1, shardStats.getCommittedTransactionsCount());
1258
1259                 // Commit index should advance as we do not have an empty modification
1260                 assertEquals(0, shardStats.getCommitIndex());
1261             }
1262         };
1263     }
1264
1265     @Test
1266     public void testCommitPhaseFailure() throws Throwable {
1267         testCommitPhaseFailure(true);
1268         testCommitPhaseFailure(false);
1269     }
1270
1271     private void testCommitPhaseFailure(final boolean readWrite) throws Throwable {
1272         new ShardTestKit(getSystem()) {{
1273             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1274                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1275                     "testCommitPhaseFailure-" + readWrite);
1276
1277             waitUntilLeader(shard);
1278
1279             // Setup 2 simulated transactions with mock cohorts. The first one fails in the
1280             // commit phase.
1281
1282             final TransactionIdentifier transactionID1 = nextTransactionId();
1283             final MutableCompositeModification modification1 = new MutableCompositeModification();
1284             final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1285             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1286             doReturn(Futures.immediateFuture(null)).when(cohort1).preCommit();
1287             doReturn(Futures.immediateFailedFuture(new RuntimeException("mock"))).when(cohort1).commit();
1288             doReturn(mockCandidate("cohort1-candidate")).when(cohort1).getCandidate();
1289
1290             final TransactionIdentifier transactionID2 = nextTransactionId();
1291             final MutableCompositeModification modification2 = new MutableCompositeModification();
1292             final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1293             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1294
1295             final FiniteDuration duration = duration("5 seconds");
1296             final Timeout timeout = new Timeout(duration);
1297
1298             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1299             expectMsgClass(duration, ReadyTransactionReply.class);
1300
1301             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1302             expectMsgClass(duration, ReadyTransactionReply.class);
1303
1304             // Send the CanCommitTransaction message for the first Tx.
1305
1306             shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1307             final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1308                     expectMsgClass(duration, CanCommitTransactionReply.class));
1309             assertEquals("Can commit", true, canCommitReply.getCanCommit());
1310
1311             // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1312             // processed after the first Tx completes.
1313
1314             final Future<Object> canCommitFuture = Patterns.ask(shard,
1315                     new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1316
1317             // Send the CommitTransaction message for the first Tx. This should send back an error
1318             // and trigger the 2nd Tx to proceed.
1319
1320             shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1321             expectMsgClass(duration, akka.actor.Status.Failure.class);
1322
1323             // Wait for the 2nd Tx to complete the canCommit phase.
1324
1325             final CountDownLatch latch = new CountDownLatch(1);
1326             canCommitFuture.onComplete(new OnComplete<Object>() {
1327                 @Override
1328                 public void onComplete(final Throwable t, final Object resp) {
1329                     latch.countDown();
1330                 }
1331             }, getSystem().dispatcher());
1332
1333             assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1334
1335             final InOrder inOrder = inOrder(cohort1, cohort2);
1336             inOrder.verify(cohort1).canCommit();
1337             inOrder.verify(cohort1).preCommit();
1338             inOrder.verify(cohort1).commit();
1339             inOrder.verify(cohort2).canCommit();
1340         }};
1341     }
1342
1343     @Test
1344     public void testPreCommitPhaseFailure() throws Throwable {
1345         testPreCommitPhaseFailure(true);
1346         testPreCommitPhaseFailure(false);
1347     }
1348
1349     private void testPreCommitPhaseFailure(final boolean readWrite) throws Throwable {
1350         new ShardTestKit(getSystem()) {{
1351             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1352                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1353                     "testPreCommitPhaseFailure-" + readWrite);
1354
1355             waitUntilLeader(shard);
1356
1357             final TransactionIdentifier transactionID1 = nextTransactionId();
1358             final MutableCompositeModification modification1 = new MutableCompositeModification();
1359             final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1360             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1361             doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).preCommit();
1362
1363             final TransactionIdentifier transactionID2 = nextTransactionId();
1364             final MutableCompositeModification modification2 = new MutableCompositeModification();
1365             final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1366             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1367
1368             final FiniteDuration duration = duration("5 seconds");
1369             final Timeout timeout = new Timeout(duration);
1370
1371             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1372             expectMsgClass(duration, ReadyTransactionReply.class);
1373
1374             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1375             expectMsgClass(duration, ReadyTransactionReply.class);
1376
1377             // Send the CanCommitTransaction message for the first Tx.
1378
1379             shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1380             final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1381                 expectMsgClass(duration, CanCommitTransactionReply.class));
1382             assertEquals("Can commit", true, canCommitReply.getCanCommit());
1383
1384             // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1385             // processed after the first Tx completes.
1386
1387             final Future<Object> canCommitFuture = Patterns.ask(shard,
1388                     new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1389
1390             // Send the CommitTransaction message for the first Tx. This should send back an error
1391             // and trigger the 2nd Tx to proceed.
1392
1393             shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1394             expectMsgClass(duration, akka.actor.Status.Failure.class);
1395
1396             // Wait for the 2nd Tx to complete the canCommit phase.
1397
1398             final CountDownLatch latch = new CountDownLatch(1);
1399             canCommitFuture.onComplete(new OnComplete<Object>() {
1400                 @Override
1401                 public void onComplete(final Throwable t, final Object resp) {
1402                     latch.countDown();
1403                 }
1404             }, getSystem().dispatcher());
1405
1406             assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1407
1408             final InOrder inOrder = inOrder(cohort1, cohort2);
1409             inOrder.verify(cohort1).canCommit();
1410             inOrder.verify(cohort1).preCommit();
1411             inOrder.verify(cohort2).canCommit();
1412         }};
1413     }
1414
1415     @Test
1416     public void testCanCommitPhaseFailure() throws Throwable {
1417         testCanCommitPhaseFailure(true);
1418         testCanCommitPhaseFailure(false);
1419     }
1420
1421     private void testCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1422         new ShardTestKit(getSystem()) {{
1423             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1424                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1425                     "testCanCommitPhaseFailure-" + readWrite);
1426
1427             waitUntilLeader(shard);
1428
1429             final FiniteDuration duration = duration("5 seconds");
1430
1431             final TransactionIdentifier transactionID1 = nextTransactionId();
1432             final MutableCompositeModification modification = new MutableCompositeModification();
1433             final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1434             doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1435
1436             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1437             expectMsgClass(duration, ReadyTransactionReply.class);
1438
1439             // Send the CanCommitTransaction message.
1440
1441             shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1442             expectMsgClass(duration, akka.actor.Status.Failure.class);
1443
1444             // Send another can commit to ensure the failed one got cleaned up.
1445
1446             reset(cohort);
1447
1448             final TransactionIdentifier transactionID2 = nextTransactionId();
1449             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1450
1451             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1452             expectMsgClass(duration, ReadyTransactionReply.class);
1453
1454             shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1455             final CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1456                     expectMsgClass(CanCommitTransactionReply.class));
1457             assertEquals("getCanCommit", true, reply.getCanCommit());
1458         }};
1459     }
1460
1461     @Test
1462     public void testCanCommitPhaseFalseResponse() throws Throwable {
1463         testCanCommitPhaseFalseResponse(true);
1464         testCanCommitPhaseFalseResponse(false);
1465     }
1466
1467     private void testCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1468         new ShardTestKit(getSystem()) {{
1469             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1470                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1471                     "testCanCommitPhaseFalseResponse-" + readWrite);
1472
1473             waitUntilLeader(shard);
1474
1475             final FiniteDuration duration = duration("5 seconds");
1476
1477             final TransactionIdentifier transactionID1 = nextTransactionId();
1478             final MutableCompositeModification modification = new MutableCompositeModification();
1479             final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1480             doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1481
1482             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1483             expectMsgClass(duration, ReadyTransactionReply.class);
1484
1485             // Send the CanCommitTransaction message.
1486
1487             shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1488             CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1489                     expectMsgClass(CanCommitTransactionReply.class));
1490             assertEquals("getCanCommit", false, reply.getCanCommit());
1491
1492             // Send another can commit to ensure the failed one got cleaned up.
1493
1494             reset(cohort);
1495
1496             final TransactionIdentifier transactionID2 = nextTransactionId();
1497             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1498
1499             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1500             expectMsgClass(duration, ReadyTransactionReply.class);
1501
1502             shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1503             reply = CanCommitTransactionReply.fromSerializable(
1504                     expectMsgClass(CanCommitTransactionReply.class));
1505             assertEquals("getCanCommit", true, reply.getCanCommit());
1506         }};
1507     }
1508
1509     @Test
1510     public void testImmediateCommitWithCanCommitPhaseFailure() throws Throwable {
1511         testImmediateCommitWithCanCommitPhaseFailure(true);
1512         testImmediateCommitWithCanCommitPhaseFailure(false);
1513     }
1514
1515     private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1516         new ShardTestKit(getSystem()) {{
1517             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1518                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1519                     "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1520
1521             waitUntilLeader(shard);
1522
1523             final FiniteDuration duration = duration("5 seconds");
1524
1525             final TransactionIdentifier transactionID1 = nextTransactionId();
1526             final MutableCompositeModification modification = new MutableCompositeModification();
1527             final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1528             doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1529
1530             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification, true), getRef());
1531
1532             expectMsgClass(duration, akka.actor.Status.Failure.class);
1533
1534             // Send another can commit to ensure the failed one got cleaned up.
1535
1536             reset(cohort);
1537
1538             final TransactionIdentifier transactionID2 = nextTransactionId();
1539             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1540             doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1541             doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1542             final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1543             final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1544             doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1545             doReturn(candidateRoot).when(candidate).getRootNode();
1546             doReturn(YangInstanceIdentifier.EMPTY).when(candidate).getRootPath();
1547             doReturn(candidate).when(cohort).getCandidate();
1548
1549             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1550
1551             expectMsgClass(duration, CommitTransactionReply.class);
1552         }};
1553     }
1554
1555     @Test
1556     public void testImmediateCommitWithCanCommitPhaseFalseResponse() throws Throwable {
1557         testImmediateCommitWithCanCommitPhaseFalseResponse(true);
1558         testImmediateCommitWithCanCommitPhaseFalseResponse(false);
1559     }
1560
1561     private void testImmediateCommitWithCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1562         new ShardTestKit(getSystem()) {{
1563             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1564                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1565                     "testImmediateCommitWithCanCommitPhaseFalseResponse-" + readWrite);
1566
1567             waitUntilLeader(shard);
1568
1569             final FiniteDuration duration = duration("5 seconds");
1570
1571             final TransactionIdentifier transactionID1 = nextTransactionId();
1572             final MutableCompositeModification modification = new MutableCompositeModification();
1573             final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1574             doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1575
1576             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification, true), getRef());
1577
1578             expectMsgClass(duration, akka.actor.Status.Failure.class);
1579
1580             // Send another can commit to ensure the failed one got cleaned up.
1581
1582             reset(cohort);
1583
1584             final TransactionIdentifier transactionID2 = nextTransactionId();
1585             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1586             doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1587             doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1588             final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1589             final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1590             doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1591             doReturn(candidateRoot).when(candidate).getRootNode();
1592             doReturn(YangInstanceIdentifier.EMPTY).when(candidate).getRootPath();
1593             doReturn(candidate).when(cohort).getCandidate();
1594
1595             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1596
1597             expectMsgClass(duration, CommitTransactionReply.class);
1598         }};
1599     }
1600
1601     @Test
1602     public void testAbortBeforeFinishCommit() throws Throwable {
1603         testAbortBeforeFinishCommit(true);
1604         testAbortBeforeFinishCommit(false);
1605     }
1606
1607     private void testAbortBeforeFinishCommit(final boolean readWrite) throws Throwable {
1608         new ShardTestKit(getSystem()) {{
1609             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1610                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1611                     "testAbortBeforeFinishCommit-" + readWrite);
1612
1613             waitUntilLeader(shard);
1614
1615             final FiniteDuration duration = duration("5 seconds");
1616             final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1617
1618             final TransactionIdentifier transactionID = nextTransactionId();
1619             final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit =
1620                           cohort -> {
1621                 final ListenableFuture<Void> preCommitFuture = cohort.preCommit();
1622
1623                 // Simulate an AbortTransaction message occurring during replication, after
1624                 // persisting and before finishing the commit to the in-memory store.
1625                 // We have no followers so due to optimizations in the RaftActor, it does not
1626                 // attempt replication and thus we can't send an AbortTransaction message b/c
1627                 // it would be processed too late after CommitTransaction completes. So we'll
1628                 // simulate an AbortTransaction message occurring during replication by calling
1629                 // the shard directly.
1630                 //
1631                 shard.underlyingActor().doAbortTransaction(transactionID, null);
1632
1633                 return preCommitFuture;
1634             };
1635
1636             final MutableCompositeModification modification = new MutableCompositeModification();
1637             final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort1", dataStore,
1638                     TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME),
1639                     modification, preCommit);
1640
1641             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1642             expectMsgClass(duration, ReadyTransactionReply.class);
1643
1644             shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1645             final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1646                 expectMsgClass(duration, CanCommitTransactionReply.class));
1647             assertEquals("Can commit", true, canCommitReply.getCanCommit());
1648
1649             shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1650             expectMsgClass(duration, CommitTransactionReply.class);
1651
1652             final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1653
1654             // Since we're simulating an abort occurring during replication and before finish commit,
1655             // the data should still get written to the in-memory store since we've gotten past
1656             // canCommit and preCommit and persisted the data.
1657             assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1658         }};
1659     }
1660
1661     @Test
1662     public void testTransactionCommitTimeout() throws Throwable {
1663         testTransactionCommitTimeout(true);
1664         testTransactionCommitTimeout(false);
1665     }
1666
1667     private void testTransactionCommitTimeout(final boolean readWrite) throws Throwable {
1668         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1669
1670         new ShardTestKit(getSystem()) {{
1671             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1672                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1673                     "testTransactionCommitTimeout-" + readWrite);
1674
1675             waitUntilLeader(shard);
1676
1677             final FiniteDuration duration = duration("5 seconds");
1678
1679             final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1680
1681             writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1682             writeToStore(shard, TestModel.OUTER_LIST_PATH,
1683                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1684
1685             // Create 1st Tx - will timeout
1686
1687             final TransactionIdentifier transactionID1 = nextTransactionId();
1688             final MutableCompositeModification modification1 = new MutableCompositeModification();
1689             final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1690                     YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1691                         .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1692                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
1693                     modification1);
1694
1695             // Create 2nd Tx
1696
1697             final TransactionIdentifier transactionID2 = nextTransactionId();
1698             final MutableCompositeModification modification2 = new MutableCompositeModification();
1699             final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1700                 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1701             final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort3", dataStore,
1702                     listNodePath,
1703                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2),
1704                     modification2);
1705
1706             // Ready the Tx's
1707
1708             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1709             expectMsgClass(duration, ReadyTransactionReply.class);
1710
1711             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1712             expectMsgClass(duration, ReadyTransactionReply.class);
1713
1714             // canCommit 1st Tx. We don't send the commit so it should timeout.
1715
1716             shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1717             expectMsgClass(duration, CanCommitTransactionReply.class);
1718
1719             // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1720
1721             shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1722             expectMsgClass(duration, CanCommitTransactionReply.class);
1723
1724             // Try to commit the 1st Tx - should fail as it's not the current Tx.
1725
1726             shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1727             expectMsgClass(duration, akka.actor.Status.Failure.class);
1728
1729             // Commit the 2nd Tx.
1730
1731             shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1732             expectMsgClass(duration, CommitTransactionReply.class);
1733
1734             final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1735             assertNotNull(listNodePath + " not found", node);
1736         }};
1737     }
1738
1739     @Test
1740     public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1741         dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1742
1743         new ShardTestKit(getSystem()) {{
1744             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1745                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1746                     "testTransactionCommitQueueCapacityExceeded");
1747
1748             waitUntilLeader(shard);
1749
1750             final FiniteDuration duration = duration("5 seconds");
1751
1752             final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1753
1754             final TransactionIdentifier transactionID1 = nextTransactionId();
1755             final MutableCompositeModification modification1 = new MutableCompositeModification();
1756             final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1757                     TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1758
1759             final TransactionIdentifier transactionID2 = nextTransactionId();
1760             final MutableCompositeModification modification2 = new MutableCompositeModification();
1761             final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1762                     TestModel.OUTER_LIST_PATH,
1763                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
1764                     modification2);
1765
1766             final TransactionIdentifier transactionID3 = nextTransactionId();
1767             final MutableCompositeModification modification3 = new MutableCompositeModification();
1768             final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1769                     TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification3);
1770
1771             // Ready the Tx's
1772
1773             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1774             expectMsgClass(duration, ReadyTransactionReply.class);
1775
1776             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1777             expectMsgClass(duration, ReadyTransactionReply.class);
1778
1779             // The 3rd Tx should exceed queue capacity and fail.
1780
1781             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1782             expectMsgClass(duration, akka.actor.Status.Failure.class);
1783
1784             // canCommit 1st Tx.
1785
1786             shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1787             expectMsgClass(duration, CanCommitTransactionReply.class);
1788
1789             // canCommit the 2nd Tx - it should get queued.
1790
1791             shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1792
1793             // canCommit the 3rd Tx - should exceed queue capacity and fail.
1794
1795             shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1796             expectMsgClass(duration, akka.actor.Status.Failure.class);
1797         }};
1798     }
1799
1800     @Test
1801     public void testTransactionCommitWithPriorExpiredCohortEntries() throws Throwable {
1802         dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1803
1804         new ShardTestKit(getSystem()) {{
1805             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1806                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1807                     "testTransactionCommitWithPriorExpiredCohortEntries");
1808
1809             waitUntilLeader(shard);
1810
1811             final FiniteDuration duration = duration("5 seconds");
1812
1813             final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1814
1815             final TransactionIdentifier transactionID1 = nextTransactionId();
1816             final MutableCompositeModification modification1 = new MutableCompositeModification();
1817             final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1818                     TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1819
1820             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1821             expectMsgClass(duration, ReadyTransactionReply.class);
1822
1823             final TransactionIdentifier transactionID2 = nextTransactionId();
1824             final MutableCompositeModification modification2 = new MutableCompositeModification();
1825             final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1826                     TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1827
1828             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1829             expectMsgClass(duration, ReadyTransactionReply.class);
1830
1831             final TransactionIdentifier transactionID3 = nextTransactionId();
1832             final MutableCompositeModification modification3 = new MutableCompositeModification();
1833             final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1834                     TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME), modification3);
1835
1836             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1837             expectMsgClass(duration, ReadyTransactionReply.class);
1838
1839             // All Tx's are readied. We'll send canCommit for the last one but not the others. The others
1840             // should expire from the queue and the last one should be processed.
1841
1842             shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1843             expectMsgClass(duration, CanCommitTransactionReply.class);
1844         }};
1845     }
1846
1847     @Test
1848     public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Throwable {
1849         dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1850
1851         new ShardTestKit(getSystem()) {{
1852             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1853                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1854                     "testTransactionCommitWithSubsequentExpiredCohortEntry");
1855
1856             waitUntilLeader(shard);
1857
1858             final FiniteDuration duration = duration("5 seconds");
1859
1860             final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1861
1862             final TransactionIdentifier transactionID1 = nextTransactionId();
1863             final MutableCompositeModification modification1 = new MutableCompositeModification();
1864             final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1865                     TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1866
1867             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1868             expectMsgClass(duration, ReadyTransactionReply.class);
1869
1870             // CanCommit the first one so it's the current in-progress CohortEntry.
1871
1872             shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1873             expectMsgClass(duration, CanCommitTransactionReply.class);
1874
1875             // Ready the second Tx.
1876
1877             final TransactionIdentifier transactionID2 = nextTransactionId();
1878             final MutableCompositeModification modification2 = new MutableCompositeModification();
1879             final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1880                     TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1881
1882             shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1883             expectMsgClass(duration, ReadyTransactionReply.class);
1884
1885             // Ready the third Tx.
1886
1887             final TransactionIdentifier transactionID3 = nextTransactionId();
1888             final DataTreeModification modification3 = dataStore.newModification();
1889             new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1890                     .apply(modification3);
1891                 modification3.ready();
1892             final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3, true);
1893
1894             shard.tell(readyMessage, getRef());
1895
1896             // Commit the first Tx. After completing, the second should expire from the queue and the third
1897             // Tx committed.
1898
1899             shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1900             expectMsgClass(duration, CommitTransactionReply.class);
1901
1902             // Expect commit reply from the third Tx.
1903
1904             expectMsgClass(duration, CommitTransactionReply.class);
1905
1906             final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1907             assertNotNull(TestModel.TEST2_PATH + " not found", node);
1908         }};
1909     }
1910
1911     @Test
1912     public void testCanCommitBeforeReadyFailure() throws Throwable {
1913         new ShardTestKit(getSystem()) {{
1914             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1915                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1916                     "testCanCommitBeforeReadyFailure");
1917
1918             shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
1919             expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1920         }};
1921     }
1922
1923     @Test
1924     public void testAbortCurrentTransaction() throws Throwable {
1925         testAbortCurrentTransaction(true);
1926         testAbortCurrentTransaction(false);
1927     }
1928
1929     private void testAbortCurrentTransaction(final boolean readWrite) throws Throwable {
1930         new ShardTestKit(getSystem()) {{
1931             final TestActorRef<Shard> shard = actorFactory.createTestActor(
1932                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1933                     "testAbortCurrentTransaction-" + readWrite);
1934
1935             waitUntilLeader(shard);
1936
1937             // Setup 2 simulated transactions with mock cohorts. The first one will be aborted.
1938
1939             final TransactionIdentifier transactionID1 = nextTransactionId();
1940             final MutableCompositeModification modification1 = new MutableCompositeModification();
1941             final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1942             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1943             doReturn(Futures.immediateFuture(null)).when(cohort1).abort();
1944
1945             final TransactionIdentifier transactionID2 = nextTransactionId();
1946             final MutableCompositeModification modification2 = new MutableCompositeModification();
1947             final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1948             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1949
1950             final FiniteDuration duration = duration("5 seconds");
1951             final Timeout timeout = new Timeout(duration);
1952
1953             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1954             expectMsgClass(duration, ReadyTransactionReply.class);
1955
1956             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1957             expectMsgClass(duration, ReadyTransactionReply.class);
1958
1959             // Send the CanCommitTransaction message for the first Tx.
1960
1961             shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1962             final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1963                     expectMsgClass(duration, CanCommitTransactionReply.class));
1964             assertEquals("Can commit", true, canCommitReply.getCanCommit());
1965
1966             // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1967             // processed after the first Tx completes.
1968
1969             final Future<Object> canCommitFuture = Patterns.ask(shard,
1970                     new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1971
1972             // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1973             // Tx to proceed.
1974
1975             shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1976             expectMsgClass(duration, AbortTransactionReply.class);
1977
1978             // Wait for the 2nd Tx to complete the canCommit phase.
1979
1980             Await.ready(canCommitFuture, duration);
1981
1982             final InOrder inOrder = inOrder(cohort1, cohort2);
1983             inOrder.verify(cohort1).canCommit();
1984             inOrder.verify(cohort2).canCommit();
1985         }};
1986     }
1987
1988     @Test
1989     public void testAbortQueuedTransaction() throws Throwable {
1990         testAbortQueuedTransaction(true);
1991         testAbortQueuedTransaction(false);
1992     }
1993
1994     private void testAbortQueuedTransaction(final boolean readWrite) throws Throwable {
1995         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1996         new ShardTestKit(getSystem()) {{
1997             final AtomicReference<CountDownLatch> cleaupCheckLatch = new AtomicReference<>();
1998             @SuppressWarnings("serial")
1999             final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
2000                 @Override
2001                 public void handleCommand(final Object message) {
2002                     super.handleCommand(message);
2003                     if(TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
2004                         if(cleaupCheckLatch.get() != null) {
2005                             cleaupCheckLatch.get().countDown();
2006                         }
2007                     }
2008                 }
2009             };
2010
2011             final TestActorRef<Shard> shard = actorFactory.createTestActor(
2012                     Props.create(new DelegatingShardCreator(creator)).withDispatcher(
2013                             Dispatchers.DefaultDispatcherId()), "testAbortQueuedTransaction-" + readWrite);
2014
2015             waitUntilLeader(shard);
2016
2017             final TransactionIdentifier transactionID = nextTransactionId();
2018             final MutableCompositeModification modification = new MutableCompositeModification();
2019             final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort");
2020             doReturn(Futures.immediateFuture(null)).when(cohort).abort();
2021
2022             final FiniteDuration duration = duration("5 seconds");
2023
2024             // Ready the tx.
2025
2026             shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
2027             expectMsgClass(duration, ReadyTransactionReply.class);
2028
2029             assertEquals("getPendingTxCommitQueueSize", 1, shard.underlyingActor().getPendingTxCommitQueueSize());
2030
2031             // Send the AbortTransaction message.
2032
2033             shard.tell(new AbortTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2034             expectMsgClass(duration, AbortTransactionReply.class);
2035
2036             verify(cohort).abort();
2037
2038             // Verify the tx cohort is removed from queue at the cleanup check interval.
2039
2040             cleaupCheckLatch.set(new CountDownLatch(1));
2041             assertEquals("TX_COMMIT_TIMEOUT_CHECK_MESSAGE received", true,
2042                     cleaupCheckLatch.get().await(5, TimeUnit.SECONDS));
2043
2044             assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
2045
2046             // Now send CanCommitTransaction - should fail.
2047
2048             shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2049
2050             Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
2051             assertTrue("Failure type", failure instanceof IllegalStateException);
2052         }};
2053     }
2054
2055     @Test
2056     public void testCreateSnapshot() throws Exception {
2057         testCreateSnapshot(true, "testCreateSnapshot");
2058     }
2059
2060     @Test
2061     public void testCreateSnapshotWithNonPersistentData() throws Exception {
2062         testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
2063     }
2064
2065     private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
2066
2067         final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
2068
2069         final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
2070         class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
2071             TestPersistentDataProvider(final DataPersistenceProvider delegate) {
2072                 super(delegate);
2073             }
2074
2075             @Override
2076             public void saveSnapshot(final Object o) {
2077                 savedSnapshot.set(o);
2078                 super.saveSnapshot(o);
2079             }
2080         }
2081
2082         dataStoreContextBuilder.persistent(persistent);
2083
2084         new ShardTestKit(getSystem()) {{
2085             class TestShard extends Shard {
2086
2087                 protected TestShard(AbstractBuilder<?, ?> builder) {
2088                     super(builder);
2089                     setPersistence(new TestPersistentDataProvider(super.persistence()));
2090                 }
2091
2092                 @Override
2093                 public void handleCommand(final Object message) {
2094                     super.handleCommand(message);
2095
2096                     // XXX:  commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
2097                     if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
2098                         latch.get().countDown();
2099                     }
2100                 }
2101
2102                 @Override
2103                 public RaftActorContext getRaftActorContext() {
2104                     return super.getRaftActorContext();
2105                 }
2106             }
2107
2108             final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
2109
2110             final TestActorRef<Shard> shard = actorFactory.createTestActor(
2111                     Props.create(new DelegatingShardCreator(creator)).
2112                         withDispatcher(Dispatchers.DefaultDispatcherId()), shardActorName);
2113
2114             waitUntilLeader(shard);
2115             writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2116
2117             final NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
2118
2119             // Trigger creation of a snapshot by ensuring
2120             final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
2121             raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2122             awaitAndValidateSnapshot(expectedRoot);
2123
2124             raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2125             awaitAndValidateSnapshot(expectedRoot);
2126         }
2127
2128         private void awaitAndValidateSnapshot(NormalizedNode<?,?> expectedRoot) throws InterruptedException, IOException {
2129             assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
2130
2131             assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
2132                     savedSnapshot.get() instanceof Snapshot);
2133
2134             verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
2135
2136             latch.set(new CountDownLatch(1));
2137             savedSnapshot.set(null);
2138         }
2139
2140         private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?,?> expectedRoot) throws IOException {
2141             final NormalizedNode<?, ?> actual = ShardDataTreeSnapshot.deserialize(snapshot.getState()).getRootNode().get();
2142             assertEquals("Root node", expectedRoot, actual);
2143         }};
2144     }
2145
2146     /**
2147      * This test simply verifies that the applySnapShot logic will work
2148      * @throws ReadFailedException
2149      * @throws DataValidationFailedException
2150      */
2151     @Test
2152     public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
2153         final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
2154         store.setSchemaContext(SCHEMA_CONTEXT);
2155
2156         final DataTreeModification putTransaction = store.takeSnapshot().newModification();
2157         putTransaction.write(TestModel.TEST_PATH,
2158             ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2159         commitTransaction(store, putTransaction);
2160
2161
2162         final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
2163
2164         final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2165
2166         writeTransaction.delete(YangInstanceIdentifier.EMPTY);
2167         writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
2168
2169         commitTransaction(store, writeTransaction);
2170
2171         final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
2172
2173         assertEquals(expected, actual);
2174     }
2175
2176     @Test
2177     public void testRecoveryApplicable(){
2178
2179         final DatastoreContext persistentContext = DatastoreContext.newBuilder().
2180                 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2181
2182         final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext).
2183                 schemaContext(SCHEMA_CONTEXT).props();
2184
2185         final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
2186                 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2187
2188         final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext).
2189                 schemaContext(SCHEMA_CONTEXT).props();
2190
2191         new ShardTestKit(getSystem()) {{
2192             final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2193
2194             assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2195
2196             final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2197
2198             assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2199         }};
2200     }
2201
2202     @Test
2203     public void testOnDatastoreContext() {
2204         new ShardTestKit(getSystem()) {{
2205             dataStoreContextBuilder.persistent(true);
2206
2207             final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
2208
2209             assertEquals("isRecoveryApplicable", true,
2210                     shard.underlyingActor().persistence().isRecoveryApplicable());
2211
2212             waitUntilLeader(shard);
2213
2214             shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2215
2216             assertEquals("isRecoveryApplicable", false,
2217                 shard.underlyingActor().persistence().isRecoveryApplicable());
2218
2219             shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2220
2221             assertEquals("isRecoveryApplicable", true,
2222                 shard.underlyingActor().persistence().isRecoveryApplicable());
2223         }};
2224     }
2225
2226     @Test
2227     public void testRegisterRoleChangeListener() throws Exception {
2228         new ShardTestKit(getSystem()) {
2229             {
2230                 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2231                         newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2232                         "testRegisterRoleChangeListener");
2233
2234                 waitUntilLeader(shard);
2235
2236                 final TestActorRef<MessageCollectorActor> listener =
2237                         TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2238
2239                 shard.tell(new RegisterRoleChangeListener(), listener);
2240
2241                 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2242
2243                 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2244                     ShardLeaderStateChanged.class);
2245                 assertEquals("getLocalShardDataTree present", true,
2246                         leaderStateChanged.getLocalShardDataTree().isPresent());
2247                 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2248                     leaderStateChanged.getLocalShardDataTree().get());
2249
2250                 MessageCollectorActor.clearMessages(listener);
2251
2252                 // Force a leader change
2253
2254                 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2255
2256                 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2257                         ShardLeaderStateChanged.class);
2258                 assertEquals("getLocalShardDataTree present", false,
2259                         leaderStateChanged.getLocalShardDataTree().isPresent());
2260             }
2261         };
2262     }
2263
2264     @Test
2265     public void testFollowerInitialSyncStatus() throws Exception {
2266         final TestActorRef<Shard> shard = actorFactory.createTestActor(
2267                 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2268                 "testFollowerInitialSyncStatus");
2269
2270         shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
2271
2272         assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2273
2274         shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
2275
2276         assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2277     }
2278
2279     @Test
2280     public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
2281         new ShardTestKit(getSystem()) {{
2282             String testName = "testClusteredDataChangeListenerDelayedRegistration";
2283             dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2284                     customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2285
2286             final MockDataChangeListener listener = new MockDataChangeListener(1);
2287             final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2288                     actorFactory.generateActorId(testName + "-DataChangeListener"));
2289
2290             setupInMemorySnapshotStore();
2291
2292             final TestActorRef<Shard> shard = actorFactory.createTestActor(
2293                     newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2294                     actorFactory.generateActorId(testName + "-shard"));
2295
2296             waitUntilNoLeader(shard);
2297
2298             final YangInstanceIdentifier path = TestModel.TEST_PATH;
2299
2300             shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2301             final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2302                 RegisterChangeListenerReply.class);
2303             assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2304
2305             shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2306                     customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2307
2308             listener.waitForChangeEvents();
2309         }};
2310     }
2311
2312     @Test
2313     public void testClusteredDataChangeListenerRegistration() throws Exception {
2314         new ShardTestKit(getSystem()) {{
2315             String testName = "testClusteredDataChangeListenerRegistration";
2316             final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2317                     MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2318
2319             final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2320                     MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2321
2322             final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2323                     Shard.builder().id(followerShardID).
2324                         datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2325                         peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2326                             "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2327                     withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2328
2329             final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2330                     Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2331                         peerAddresses(Collections.singletonMap(followerShardID.toString(),
2332                             "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2333                     withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2334
2335             leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2336             String leaderPath = waitUntilLeader(followerShard);
2337             assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2338
2339             final YangInstanceIdentifier path = TestModel.TEST_PATH;
2340             final MockDataChangeListener listener = new MockDataChangeListener(1);
2341             final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2342                     actorFactory.generateActorId(testName + "-DataChangeListener"));
2343
2344             followerShard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2345             final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2346                 RegisterChangeListenerReply.class);
2347             assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2348
2349             writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2350
2351             listener.waitForChangeEvents();
2352         }};
2353     }
2354
2355     @Test
2356     public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
2357         new ShardTestKit(getSystem()) {{
2358             String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
2359             dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2360                     customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2361
2362             final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2363             final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2364                     actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2365
2366             setupInMemorySnapshotStore();
2367
2368             final TestActorRef<Shard> shard = actorFactory.createTestActor(
2369                     newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2370                     actorFactory.generateActorId(testName + "-shard"));
2371
2372             waitUntilNoLeader(shard);
2373
2374             final YangInstanceIdentifier path = TestModel.TEST_PATH;
2375
2376             shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2377             final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2378                     RegisterDataTreeChangeListenerReply.class);
2379             assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2380
2381             shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2382                     customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2383
2384             listener.waitForChangeEvents();
2385         }};
2386     }
2387
2388     @Test
2389     public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2390         new ShardTestKit(getSystem()) {{
2391             String testName = "testClusteredDataTreeChangeListenerRegistration";
2392             final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2393                     MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2394
2395             final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2396                     MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2397
2398             final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2399                     Shard.builder().id(followerShardID).
2400                         datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2401                         peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2402                             "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2403                     withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2404
2405             final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2406                     Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2407                         peerAddresses(Collections.singletonMap(followerShardID.toString(),
2408                             "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2409                     withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2410
2411             leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2412             String leaderPath = waitUntilLeader(followerShard);
2413             assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2414
2415             final YangInstanceIdentifier path = TestModel.TEST_PATH;
2416             final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2417             final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2418                     actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2419
2420             followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2421             final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2422                     RegisterDataTreeChangeListenerReply.class);
2423             assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2424
2425             writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2426
2427             listener.waitForChangeEvents();
2428         }};
2429     }
2430
2431     @Test
2432     public void testServerRemoved() throws Exception {
2433         final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2434
2435         final ActorRef shard = parent.underlyingActor().context().actorOf(
2436                 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2437                 "testServerRemoved");
2438
2439         shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2440
2441         MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);
2442     }
2443 }