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