Integrate MRI projects for Neon
[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 package org.opendaylight.controller.cluster.datastore;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertSame;
14 import static org.junit.Assert.assertTrue;
15 import static org.junit.Assert.fail;
16 import static org.mockito.Matchers.any;
17 import static org.mockito.Mockito.doThrow;
18 import static org.mockito.Mockito.inOrder;
19 import static org.mockito.Mockito.mock;
20 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
21
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.Stopwatch;
34 import com.google.common.base.Throwables;
35 import com.google.common.util.concurrent.Uninterruptibles;
36 import java.util.Collections;
37 import java.util.HashSet;
38 import java.util.Map;
39 import java.util.Optional;
40 import java.util.Set;
41 import java.util.concurrent.CountDownLatch;
42 import java.util.concurrent.TimeUnit;
43 import java.util.concurrent.atomic.AtomicBoolean;
44 import java.util.concurrent.atomic.AtomicReference;
45 import org.junit.Test;
46 import org.mockito.InOrder;
47 import org.opendaylight.controller.cluster.DataPersistenceProvider;
48 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
49 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
50 import org.opendaylight.controller.cluster.access.concepts.MemberName;
51 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
52 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
53 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
54 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
55 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
56 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
57 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
58 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
59 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
61 import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistration;
62 import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistrationReply;
63 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
65 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
67 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
68 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
70 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
71 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
72 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
73 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply;
74 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
75 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
76 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
77 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
78 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
79 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
80 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
81 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
82 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
83 import org.opendaylight.controller.cluster.raft.RaftActorContext;
84 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
85 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
86 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
87 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
88 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
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.client.messages.GetOnDemandRaftState;
92 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
93 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
94 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
95 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
96 import org.opendaylight.controller.cluster.raft.persisted.SimpleReplicatedLogEntry;
97 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
98 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
99 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
100 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
101 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
102 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
103 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
104 import org.opendaylight.yangtools.concepts.Identifier;
105 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
106 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
107 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
108 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
109 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
110 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
111 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
112 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
113 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
114 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
115 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
116 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
117 import scala.concurrent.Await;
118 import scala.concurrent.Future;
119 import scala.concurrent.duration.FiniteDuration;
120
121 public class ShardTest extends AbstractShardTest {
122     private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in "
123             + "InMemorySnapshotStore and journal recovery seq number will start from 1";
124
125     @Test
126     public void testRegisterDataTreeChangeListener() throws Exception {
127         final ShardTestKit testKit = new ShardTestKit(getSystem());
128         final TestActorRef<Shard> shard = actorFactory.createTestActor(
129             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
130             "testRegisterDataTreeChangeListener");
131
132         ShardTestKit.waitUntilLeader(shard);
133
134         shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
135
136         final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
137         final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
138             TestModel.TEST_PATH), "testRegisterDataTreeChangeListener-DataTreeChangeListener");
139
140         shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), testKit.getRef());
141
142         final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(testKit.duration("3 seconds"),
143             RegisterDataTreeNotificationListenerReply.class);
144         final String replyPath = reply.getListenerRegistrationPath().toString();
145         assertTrue("Incorrect reply path: " + replyPath,
146             replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
147
148         final YangInstanceIdentifier path = TestModel.TEST_PATH;
149         writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
150
151         listener.waitForChangeEvents();
152     }
153
154     @SuppressWarnings("serial")
155     @Test
156     public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
157         final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
158         final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
159         final Creator<Shard> creator = new Creator<Shard>() {
160             boolean firstElectionTimeout = true;
161
162             @Override
163             public Shard create() {
164                 return new Shard(newShardBuilder()) {
165                     @Override
166                     public void handleCommand(final Object message) {
167                         if (message instanceof ElectionTimeout && firstElectionTimeout) {
168                             firstElectionTimeout = false;
169                             final ActorRef self = getSelf();
170                             new Thread(() -> {
171                                 Uninterruptibles.awaitUninterruptibly(
172                                         onChangeListenerRegistered, 5, TimeUnit.SECONDS);
173                                 self.tell(message, self);
174                             }).start();
175
176                             onFirstElectionTimeout.countDown();
177                         } else {
178                             super.handleCommand(message);
179                         }
180                     }
181                 };
182             }
183         };
184
185         setupInMemorySnapshotStore();
186
187         final YangInstanceIdentifier path = TestModel.TEST_PATH;
188         final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
189         final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
190                 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
191
192         final TestActorRef<Shard> shard = actorFactory.createTestActor(
193                 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
194                 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
195
196         final ShardTestKit testKit = new ShardTestKit(getSystem());
197         assertTrue("Got first ElectionTimeout", onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
198
199         shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), testKit.getRef());
200         final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(testKit.duration("5 seconds"),
201             RegisterDataTreeNotificationListenerReply.class);
202         assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
203
204         shard.tell(FindLeader.INSTANCE, testKit.getRef());
205         final FindLeaderReply findLeadeReply = testKit.expectMsgClass(testKit.duration("5 seconds"),
206             FindLeaderReply.class);
207         assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
208
209         onChangeListenerRegistered.countDown();
210
211         // TODO: investigate why we do not receive data chage events
212         listener.waitForChangeEvents();
213     }
214
215     @Test
216     public void testCreateTransaction() {
217         final ShardTestKit testKit = new ShardTestKit(getSystem());
218         final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
219
220         ShardTestKit.waitUntilLeader(shard);
221
222         shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), testKit.getRef());
223
224         shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
225             DataStoreVersions.CURRENT_VERSION).toSerializable(), testKit.getRef());
226
227         final CreateTransactionReply reply = testKit.expectMsgClass(testKit.duration("3 seconds"),
228             CreateTransactionReply.class);
229
230         final String path = reply.getTransactionPath().toString();
231         assertTrue("Unexpected transaction path " + path, path.startsWith(String.format(
232             "akka://test/user/testCreateTransaction/shard-%s-%s:ShardTransactionTest@0:",
233             shardID.getShardName(), shardID.getMemberName().getName())));
234     }
235
236     @Test
237     public void testCreateTransactionOnChain() {
238         final ShardTestKit testKit = new ShardTestKit(getSystem());
239         final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
240
241         ShardTestKit.waitUntilLeader(shard);
242
243         shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
244             DataStoreVersions.CURRENT_VERSION).toSerializable(), testKit.getRef());
245
246         final CreateTransactionReply reply = testKit.expectMsgClass(testKit.duration("3 seconds"),
247             CreateTransactionReply.class);
248
249         final String path = reply.getTransactionPath().toString();
250         assertTrue("Unexpected transaction path " + path, path.startsWith(String.format(
251             "akka://test/user/testCreateTransactionOnChain/shard-%s-%s:ShardTransactionTest@0:",
252             shardID.getShardName(), shardID.getMemberName().getName())));
253     }
254
255     @Test
256     public void testPeerAddressResolved() {
257         final ShardTestKit testKit = new ShardTestKit(getSystem());
258         final ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"),
259                 "config");
260         final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder()
261             .peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null))
262             .props().withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
263
264         final String address = "akka://foobar";
265         shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
266
267         shard.tell(GetOnDemandRaftState.INSTANCE, testKit.getRef());
268         final OnDemandRaftState state = testKit.expectMsgClass(OnDemandRaftState.class);
269         assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
270     }
271
272     @Test
273     public void testApplySnapshot() throws Exception {
274
275         final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps()
276                 .withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplySnapshot");
277
278         ShardTestKit.waitUntilLeader(shard);
279
280         final DataTree store = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL,
281             SCHEMA_CONTEXT);
282
283         final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
284                 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
285                     .withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
286                         ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
287
288         writeToStore(store, TestModel.TEST_PATH, container);
289
290         final YangInstanceIdentifier root = YangInstanceIdentifier.EMPTY;
291         final NormalizedNode<?,?> expected = readStore(store, root);
292
293         final Snapshot snapshot = Snapshot.create(new ShardSnapshotState(new MetadataShardDataTreeSnapshot(expected)),
294                 Collections.emptyList(), 1, 2, 3, 4, -1, null, null);
295
296         shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
297
298         final Stopwatch sw = Stopwatch.createStarted();
299         while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
300             Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
301
302             try {
303                 assertEquals("Root node", expected, readStore(shard, root));
304                 return;
305             } catch (final AssertionError e) {
306                 // try again
307             }
308         }
309
310         fail("Snapshot was not applied");
311     }
312
313     @Test
314     public void testApplyState() throws Exception {
315         final TestActorRef<Shard> shard = actorFactory.createTestActor(
316                 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");
317
318         ShardTestKit.waitUntilLeader(shard);
319
320         final DataTree store = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL,
321             SCHEMA_CONTEXT);
322
323         final DataTreeModification writeMod = store.takeSnapshot().newModification();
324         final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
325         writeMod.write(TestModel.TEST_PATH, node);
326         writeMod.ready();
327
328         final TransactionIdentifier tx = nextTransactionId();
329         shard.underlyingActor().applyState(null, null, payloadForModification(store, writeMod, tx));
330
331         final Stopwatch sw = Stopwatch.createStarted();
332         while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
333             Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
334
335             final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
336             if (actual != null) {
337                 assertEquals("Applied state", node, actual);
338                 return;
339             }
340         }
341
342         fail("State was not applied");
343     }
344
345     @Test
346     public void testDataTreeCandidateRecovery() throws Exception {
347         // Set up the InMemorySnapshotStore.
348         final DataTree source = setupInMemorySnapshotStore();
349
350         final DataTreeModification writeMod = source.takeSnapshot().newModification();
351         writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
352         writeMod.ready();
353         InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
354
355         // Set up the InMemoryJournal.
356         InMemoryJournal.addEntry(shardID.toString(), 1, new SimpleReplicatedLogEntry(0, 1,
357             payloadForModification(source, writeMod, nextTransactionId())));
358
359         final int nListEntries = 16;
360         final Set<Integer> listEntryKeys = new HashSet<>();
361
362         // Add some ModificationPayload entries
363         for (int i = 1; i <= nListEntries; i++) {
364             listEntryKeys.add(Integer.valueOf(i));
365
366             final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
367                     .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
368
369             final DataTreeModification mod = source.takeSnapshot().newModification();
370             mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
371             mod.ready();
372
373             InMemoryJournal.addEntry(shardID.toString(), i + 1, new SimpleReplicatedLogEntry(i, 1,
374                 payloadForModification(source, mod, nextTransactionId())));
375         }
376
377         InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
378             new ApplyJournalEntries(nListEntries));
379
380         testRecovery(listEntryKeys);
381     }
382
383     @Test
384     @SuppressWarnings("checkstyle:IllegalCatch")
385     public void testConcurrentThreePhaseCommits() throws Exception {
386         final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
387         final CountDownLatch commitLatch = new CountDownLatch(2);
388
389         final long timeoutSec = 5;
390         final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
391         final Timeout timeout = new Timeout(duration);
392
393         final TestActorRef<Shard> shard = actorFactory.createTestActor(
394                 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
395                 "testConcurrentThreePhaseCommits");
396
397         class OnFutureComplete extends OnComplete<Object> {
398             private final Class<?> expRespType;
399
400             OnFutureComplete(final Class<?> expRespType) {
401                 this.expRespType = expRespType;
402             }
403
404             @Override
405             public void onComplete(final Throwable error, final Object resp) {
406                 if (error != null) {
407                     caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
408                 } else {
409                     try {
410                         assertEquals("Commit response type", expRespType, resp.getClass());
411                         onSuccess(resp);
412                     } catch (final Exception e) {
413                         caughtEx.set(e);
414                     }
415                 }
416             }
417
418             void onSuccess(final Object resp) {
419             }
420         }
421
422         class OnCommitFutureComplete extends OnFutureComplete {
423             OnCommitFutureComplete() {
424                 super(CommitTransactionReply.class);
425             }
426
427             @Override
428             public void onComplete(final Throwable error, final Object resp) {
429                 super.onComplete(error, resp);
430                 commitLatch.countDown();
431             }
432         }
433
434         class OnCanCommitFutureComplete extends OnFutureComplete {
435             private final TransactionIdentifier transactionID;
436
437             OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
438                 super(CanCommitTransactionReply.class);
439                 this.transactionID = transactionID;
440             }
441
442             @Override
443             void onSuccess(final Object resp) {
444                 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(resp);
445                 assertTrue("Can commit", canCommitReply.getCanCommit());
446
447                 final Future<Object> commitFuture = Patterns.ask(shard,
448                         new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
449                 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
450             }
451         }
452
453         final ShardTestKit testKit = new ShardTestKit(getSystem());
454         ShardTestKit.waitUntilLeader(shard);
455
456         final TransactionIdentifier transactionID1 = nextTransactionId();
457         final TransactionIdentifier transactionID2 = nextTransactionId();
458         final TransactionIdentifier transactionID3 = nextTransactionId();
459
460         final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
461             shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
462         final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
463         final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
464         final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
465
466         shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
467             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
468         final ReadyTransactionReply readyReply = ReadyTransactionReply
469                 .fromSerializable(testKit.expectMsgClass(duration, ReadyTransactionReply.class));
470         assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
471         // Send the CanCommitTransaction message for the first Tx.
472
473         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
474         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
475                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
476         assertTrue("Can commit", canCommitReply.getCanCommit());
477
478         // Ready 2 more Tx's.
479
480         shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
481             ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), testKit.getRef());
482         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
483
484         shard.tell(
485             prepareBatchedModifications(transactionID3,
486                 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
487                 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
488                 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false), testKit.getRef());
489         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
490
491         // Send the CanCommitTransaction message for the next 2 Tx's.
492         // These should get queued and
493         // processed after the first Tx completes.
494
495         final Future<Object> canCommitFuture1 = Patterns.ask(shard,
496             new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
497
498         final Future<Object> canCommitFuture2 = Patterns.ask(shard,
499             new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
500
501         // Send the CommitTransaction message for the first Tx. After it
502         // completes, it should
503         // trigger the 2nd Tx to proceed which should in turn then
504         // trigger the 3rd.
505
506         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
507         testKit.expectMsgClass(duration, CommitTransactionReply.class);
508
509         // Wait for the next 2 Tx's to complete.
510
511         canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2), getSystem().dispatcher());
512
513         canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3), getSystem().dispatcher());
514
515         final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
516
517         final Throwable t = caughtEx.get();
518         if (t != null) {
519             Throwables.propagateIfPossible(t, Exception.class);
520             throw new RuntimeException(t);
521         }
522
523         assertTrue("Commits complete", done);
524
525 //                final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
526 //                        cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
527 //                        cohort3.getPreCommit(), cohort3.getCommit());
528 //                inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
529 //                inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
530 //                inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
531 //                inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
532 //                inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
533 //                inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
534 //                inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
535 //                inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
536 //                inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
537
538         // Verify data in the data store.
539
540         verifyOuterListEntry(shard, 1);
541
542         verifyLastApplied(shard, 5);
543     }
544
545     @Test
546     public void testBatchedModificationsWithNoCommitOnReady() {
547         final ShardTestKit testKit = new ShardTestKit(getSystem());
548         final TestActorRef<Shard> shard = actorFactory.createTestActor(
549             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
550             "testBatchedModificationsWithNoCommitOnReady");
551
552         ShardTestKit.waitUntilLeader(shard);
553
554         final TransactionIdentifier transactionID = nextTransactionId();
555         final FiniteDuration duration = testKit.duration("5 seconds");
556
557         // Send a BatchedModifications to start a transaction.
558
559         shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
560             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), testKit.getRef());
561         testKit.expectMsgClass(duration, BatchedModificationsReply.class);
562
563         // Send a couple more BatchedModifications.
564
565         shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
566                 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
567             testKit.getRef());
568         testKit.expectMsgClass(duration, BatchedModificationsReply.class);
569
570         shard.tell(newBatchedModifications(transactionID,
571             YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
572             .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
573             ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3),
574             testKit.getRef());
575         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
576
577         // Send the CanCommitTransaction message.
578
579         shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
580         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
581                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
582         assertTrue("Can commit", canCommitReply.getCanCommit());
583
584         // Send the CommitTransaction message.
585
586         shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
587         testKit.expectMsgClass(duration, CommitTransactionReply.class);
588
589         // Verify data in the data store.
590
591         verifyOuterListEntry(shard, 1);
592     }
593
594     @Test
595     public void testBatchedModificationsWithCommitOnReady() {
596         final ShardTestKit testKit = new ShardTestKit(getSystem());
597         final TestActorRef<Shard> shard = actorFactory.createTestActor(
598             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
599             "testBatchedModificationsWithCommitOnReady");
600
601         ShardTestKit.waitUntilLeader(shard);
602
603         final TransactionIdentifier transactionID = nextTransactionId();
604         final FiniteDuration duration = testKit.duration("5 seconds");
605
606         // Send a BatchedModifications to start a transaction.
607
608         shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
609             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), testKit.getRef());
610         testKit.expectMsgClass(duration, BatchedModificationsReply.class);
611
612         // Send a couple more BatchedModifications.
613
614         shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
615             ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
616             testKit.getRef());
617         testKit.expectMsgClass(duration, BatchedModificationsReply.class);
618
619         shard.tell(newBatchedModifications(transactionID,
620             YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
621             .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
622             ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3),
623             testKit.getRef());
624
625         testKit.expectMsgClass(duration, CommitTransactionReply.class);
626
627         // Verify data in the data store.
628         verifyOuterListEntry(shard, 1);
629     }
630
631     @Test(expected = IllegalStateException.class)
632     public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
633         final ShardTestKit testKit = new ShardTestKit(getSystem());
634         final TestActorRef<Shard> shard = actorFactory.createTestActor(
635             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
636             "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
637
638         ShardTestKit.waitUntilLeader(shard);
639
640         final TransactionIdentifier transactionID = nextTransactionId();
641         final BatchedModifications batched = new BatchedModifications(transactionID,
642             DataStoreVersions.CURRENT_VERSION);
643         batched.setReady();
644         batched.setTotalMessagesSent(2);
645
646         shard.tell(batched, testKit.getRef());
647
648         final Failure failure = testKit.expectMsgClass(testKit.duration("5 seconds"), Failure.class);
649
650         if (failure != null) {
651             Throwables.propagateIfPossible(failure.cause(), Exception.class);
652             throw new RuntimeException(failure.cause());
653         }
654     }
655
656     @Test
657     public void testBatchedModificationsWithOperationFailure() {
658         final ShardTestKit testKit = new ShardTestKit(getSystem());
659         final TestActorRef<Shard> shard = actorFactory.createTestActor(
660             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
661             "testBatchedModificationsWithOperationFailure");
662
663         ShardTestKit.waitUntilLeader(shard);
664
665         // Test merge with invalid data. An exception should occur when
666         // the merge is applied. Note that
667         // write will not validate the children for performance reasons.
668
669         final TransactionIdentifier transactionID = nextTransactionId();
670
671         final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
672                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
673                 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
674
675         BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
676         batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
677         shard.tell(batched, testKit.getRef());
678         Failure failure = testKit.expectMsgClass(testKit.duration("5 seconds"), akka.actor.Status.Failure.class);
679
680         final Throwable cause = failure.cause();
681
682         batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
683         batched.setReady();
684         batched.setTotalMessagesSent(2);
685
686         shard.tell(batched, testKit.getRef());
687
688         failure = testKit.expectMsgClass(testKit.duration("5 seconds"), akka.actor.Status.Failure.class);
689         assertEquals("Failure cause", cause, failure.cause());
690     }
691
692     @Test
693     public void testBatchedModificationsOnTransactionChain() {
694         final ShardTestKit testKit = new ShardTestKit(getSystem());
695         final TestActorRef<Shard> shard = actorFactory.createTestActor(
696             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
697             "testBatchedModificationsOnTransactionChain");
698
699         ShardTestKit.waitUntilLeader(shard);
700
701         final LocalHistoryIdentifier historyId = nextHistoryId();
702         final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
703         final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
704
705         final FiniteDuration duration = testKit.duration("5 seconds");
706
707         // Send a BatchedModifications to start a chained write
708         // transaction and ready it.
709
710         final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
711         final YangInstanceIdentifier path = TestModel.TEST_PATH;
712         shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), testKit.getRef());
713         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
714
715         // Create a read Tx on the same chain.
716
717         shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
718             DataStoreVersions.CURRENT_VERSION).toSerializable(), testKit.getRef());
719
720         final CreateTransactionReply createReply = testKit.expectMsgClass(testKit.duration("3 seconds"),
721             CreateTransactionReply.class);
722
723         getSystem().actorSelection(createReply.getTransactionPath())
724         .tell(new ReadData(path, DataStoreVersions.CURRENT_VERSION), testKit.getRef());
725         final ReadDataReply readReply = testKit.expectMsgClass(testKit.duration("3 seconds"), ReadDataReply.class);
726         assertEquals("Read node", containerNode, readReply.getNormalizedNode());
727
728         // Commit the write transaction.
729
730         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
731         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
732                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
733         assertTrue("Can commit", canCommitReply.getCanCommit());
734
735         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
736         testKit.expectMsgClass(duration, CommitTransactionReply.class);
737
738         // Verify data in the data store.
739
740         final NormalizedNode<?, ?> actualNode = readStore(shard, path);
741         assertEquals("Stored node", containerNode, actualNode);
742     }
743
744     @Test
745     public void testOnBatchedModificationsWhenNotLeader() {
746         final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
747         final ShardTestKit testKit = new ShardTestKit(getSystem());
748         final Creator<Shard> creator = new Creator<Shard>() {
749             private static final long serialVersionUID = 1L;
750
751             @Override
752             public Shard create() {
753                 return new Shard(newShardBuilder()) {
754                     @Override
755                     protected boolean isLeader() {
756                         return overrideLeaderCalls.get() ? false : super.isLeader();
757                     }
758
759                     @Override
760                     public ActorSelection getLeader() {
761                         return overrideLeaderCalls.get() ? getSystem().actorSelection(testKit.getRef().path())
762                                 : super.getLeader();
763                     }
764                 };
765             }
766         };
767
768         final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
769             .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
770             "testOnBatchedModificationsWhenNotLeader");
771
772         ShardTestKit.waitUntilLeader(shard);
773
774         overrideLeaderCalls.set(true);
775
776         final BatchedModifications batched = new BatchedModifications(nextTransactionId(),
777             DataStoreVersions.CURRENT_VERSION);
778
779         shard.tell(batched, ActorRef.noSender());
780
781         testKit.expectMsgEquals(batched);
782     }
783
784     @Test
785     public void testTransactionMessagesWithNoLeader() {
786         final ShardTestKit testKit = new ShardTestKit(getSystem());
787         dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
788         .shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
789         final TestActorRef<Shard> shard = actorFactory.createTestActor(
790             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
791             "testTransactionMessagesWithNoLeader");
792
793         testKit.waitUntilNoLeader(shard);
794
795         final TransactionIdentifier txId = nextTransactionId();
796         shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), testKit.getRef());
797         Failure failure = testKit.expectMsgClass(Failure.class);
798         assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
799
800         shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
801             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
802         failure = testKit.expectMsgClass(Failure.class);
803         assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
804
805         shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true, Optional.empty()),
806             testKit.getRef());
807         failure = testKit.expectMsgClass(Failure.class);
808         assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
809     }
810
811     @Test
812     public void testReadyWithReadWriteImmediateCommit() {
813         testReadyWithImmediateCommit(true);
814     }
815
816     @Test
817     public void testReadyWithWriteOnlyImmediateCommit() {
818         testReadyWithImmediateCommit(false);
819     }
820
821     private void testReadyWithImmediateCommit(final boolean readWrite) {
822         final ShardTestKit testKit = new ShardTestKit(getSystem());
823         final TestActorRef<Shard> shard = actorFactory.createTestActor(
824             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
825             "testReadyWithImmediateCommit-" + readWrite);
826
827         ShardTestKit.waitUntilLeader(shard);
828
829         final TransactionIdentifier transactionID = nextTransactionId();
830         final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
831         if (readWrite) {
832             shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH, containerNode, true),
833                 testKit.getRef());
834         } else {
835             shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true),
836                 testKit.getRef());
837         }
838
839         testKit.expectMsgClass(testKit.duration("5 seconds"), CommitTransactionReply.class);
840
841         final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
842         assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
843     }
844
845     @Test
846     public void testReadyLocalTransactionWithImmediateCommit() {
847         final ShardTestKit testKit = new ShardTestKit(getSystem());
848         final TestActorRef<Shard> shard = actorFactory.createTestActor(
849             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
850             "testReadyLocalTransactionWithImmediateCommit");
851
852         ShardTestKit.waitUntilLeader(shard);
853
854         final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
855
856         final DataTreeModification modification = dataStore.newModification();
857
858         final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
859         new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
860         final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
861                 .addChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
862                 .build();
863         new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
864
865         final TransactionIdentifier txId = nextTransactionId();
866         modification.ready();
867         final ReadyLocalTransaction readyMessage =
868                 new ReadyLocalTransaction(txId, modification, true, Optional.empty());
869
870         shard.tell(readyMessage, testKit.getRef());
871
872         testKit.expectMsgClass(CommitTransactionReply.class);
873
874         final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
875         assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
876     }
877
878     @Test
879     public void testReadyLocalTransactionWithThreePhaseCommit() {
880         final ShardTestKit testKit = new ShardTestKit(getSystem());
881         final TestActorRef<Shard> shard = actorFactory.createTestActor(
882             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
883             "testReadyLocalTransactionWithThreePhaseCommit");
884
885         ShardTestKit.waitUntilLeader(shard);
886
887         final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
888
889         final DataTreeModification modification = dataStore.newModification();
890
891         final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
892         new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
893         final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
894                 .addChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
895                 .build();
896         new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
897
898         final TransactionIdentifier txId = nextTransactionId();
899         modification.ready();
900         final ReadyLocalTransaction readyMessage =
901                 new ReadyLocalTransaction(txId, modification, false, Optional.empty());
902
903         shard.tell(readyMessage, testKit.getRef());
904
905         testKit.expectMsgClass(ReadyTransactionReply.class);
906
907         // Send the CanCommitTransaction message.
908
909         shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), testKit.getRef());
910         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
911                 .fromSerializable(testKit.expectMsgClass(CanCommitTransactionReply.class));
912         assertTrue("Can commit", canCommitReply.getCanCommit());
913
914         // Send the CanCommitTransaction message.
915
916         shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), testKit.getRef());
917         testKit.expectMsgClass(CommitTransactionReply.class);
918
919         final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
920         assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
921     }
922
923     @Test
924     public void testReadWriteCommitWithPersistenceDisabled() {
925         dataStoreContextBuilder.persistent(false);
926         final ShardTestKit testKit = new ShardTestKit(getSystem());
927         final TestActorRef<Shard> shard = actorFactory.createTestActor(
928             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
929             "testCommitWithPersistenceDisabled");
930
931         ShardTestKit.waitUntilLeader(shard);
932
933         // Setup a simulated transactions with a mock cohort.
934
935         final FiniteDuration duration = testKit.duration("5 seconds");
936
937         final TransactionIdentifier transactionID = nextTransactionId();
938         final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
939         shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false),
940             testKit.getRef());
941         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
942
943         // Send the CanCommitTransaction message.
944
945         shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
946         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
947                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
948         assertTrue("Can commit", canCommitReply.getCanCommit());
949
950         // Send the CanCommitTransaction message.
951
952         shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
953         testKit.expectMsgClass(duration, CommitTransactionReply.class);
954
955         final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
956         assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
957     }
958
959     @Test
960     public void testReadWriteCommitWhenTransactionHasModifications() throws Exception {
961         testCommitWhenTransactionHasModifications(true);
962     }
963
964     @Test
965     public void testWriteOnlyCommitWhenTransactionHasModifications() throws Exception {
966         testCommitWhenTransactionHasModifications(false);
967     }
968
969     private void testCommitWhenTransactionHasModifications(final boolean readWrite) throws Exception {
970         final ShardTestKit testKit = new ShardTestKit(getSystem());
971         final DataTree dataTree = createDelegatingMockDataTree();
972         final TestActorRef<Shard> shard = actorFactory.createTestActor(
973             newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
974             "testCommitWhenTransactionHasModifications-" + readWrite);
975
976         ShardTestKit.waitUntilLeader(shard);
977
978         final FiniteDuration duration = testKit.duration("5 seconds");
979         final TransactionIdentifier transactionID = nextTransactionId();
980
981         if (readWrite) {
982             shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
983                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
984         } else {
985             shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
986                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
987         }
988
989         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
990
991         // Send the CanCommitTransaction message.
992
993         shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
994         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
995                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
996         assertTrue("Can commit", canCommitReply.getCanCommit());
997
998         shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
999         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1000
1001         final InOrder inOrder = inOrder(dataTree);
1002         inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1003         inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1004         inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1005
1006         // Purge request is scheduled as asynchronous, wait for two heartbeats to let it propagate into
1007         // the journal
1008         Thread.sleep(HEARTBEAT_MILLIS * 2);
1009
1010         shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, testKit.getRef());
1011         final ShardStats shardStats = testKit.expectMsgClass(duration, ShardStats.class);
1012
1013         // Use MBean for verification
1014         // Committed transaction count should increase as usual
1015         assertEquals(1, shardStats.getCommittedTransactionsCount());
1016
1017         // Commit index should advance as we do not have an empty
1018         // modification
1019         assertEquals(1, shardStats.getCommitIndex());
1020     }
1021
1022     @Test
1023     public void testCommitPhaseFailure() throws Exception {
1024         final ShardTestKit testKit = new ShardTestKit(getSystem());
1025         final DataTree dataTree = createDelegatingMockDataTree();
1026         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1027             newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1028             "testCommitPhaseFailure");
1029
1030         ShardTestKit.waitUntilLeader(shard);
1031
1032         final FiniteDuration duration = testKit.duration("5 seconds");
1033         final Timeout timeout = new Timeout(duration);
1034
1035         // Setup 2 simulated transactions with mock cohorts. The first
1036         // one fails in the
1037         // commit phase.
1038
1039         doThrow(new RuntimeException("mock commit failure")).when(dataTree)
1040         .commit(any(DataTreeCandidate.class));
1041
1042         final TransactionIdentifier transactionID1 = nextTransactionId();
1043         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1044             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1045         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1046
1047         final TransactionIdentifier transactionID2 = nextTransactionId();
1048         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1049             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1050         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1051
1052         // Send the CanCommitTransaction message for the first Tx.
1053
1054         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1055         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1056                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
1057         assertTrue("Can commit", canCommitReply.getCanCommit());
1058
1059         // Send the CanCommitTransaction message for the 2nd Tx. This
1060         // should get queued and
1061         // processed after the first Tx completes.
1062
1063         final Future<Object> canCommitFuture = Patterns.ask(shard,
1064             new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1065
1066         // Send the CommitTransaction message for the first Tx. This
1067         // should send back an error
1068         // and trigger the 2nd Tx to proceed.
1069
1070         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1071         testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1072
1073         // Wait for the 2nd Tx to complete the canCommit phase.
1074
1075         final CountDownLatch latch = new CountDownLatch(1);
1076         canCommitFuture.onComplete(new OnComplete<Object>() {
1077             @Override
1078             public void onComplete(final Throwable failure, final Object resp) {
1079                 latch.countDown();
1080             }
1081         }, getSystem().dispatcher());
1082
1083         assertTrue("2nd CanCommit complete", latch.await(5, TimeUnit.SECONDS));
1084
1085         final InOrder inOrder = inOrder(dataTree);
1086         inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1087         inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1088
1089         // FIXME: this invocation is done on the result of validate(). To test it, we need to make sure mock
1090         //        validate performs wrapping and we capture that mock
1091         // inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1092
1093         inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1094     }
1095
1096     @Test
1097     public void testPreCommitPhaseFailure() throws Exception {
1098         final ShardTestKit testKit = new ShardTestKit(getSystem());
1099         final DataTree dataTree = createDelegatingMockDataTree();
1100         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1101             newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1102             "testPreCommitPhaseFailure");
1103
1104         ShardTestKit.waitUntilLeader(shard);
1105
1106         final FiniteDuration duration = testKit.duration("5 seconds");
1107         final Timeout timeout = new Timeout(duration);
1108
1109         doThrow(new RuntimeException("mock preCommit failure")).when(dataTree)
1110         .prepare(any(DataTreeModification.class));
1111
1112         final TransactionIdentifier transactionID1 = nextTransactionId();
1113         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1114             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1115         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1116
1117         final TransactionIdentifier transactionID2 = nextTransactionId();
1118         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1119             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1120         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1121
1122         // Send the CanCommitTransaction message for the first Tx.
1123
1124         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1125         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1126                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
1127         assertTrue("Can commit", canCommitReply.getCanCommit());
1128
1129         // Send the CanCommitTransaction message for the 2nd Tx. This
1130         // should get queued and
1131         // processed after the first Tx completes.
1132
1133         final Future<Object> canCommitFuture = Patterns.ask(shard,
1134             new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1135
1136         // Send the CommitTransaction message for the first Tx. This
1137         // should send back an error
1138         // and trigger the 2nd Tx to proceed.
1139
1140         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1141         testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1142
1143         // Wait for the 2nd Tx to complete the canCommit phase.
1144
1145         final CountDownLatch latch = new CountDownLatch(1);
1146         canCommitFuture.onComplete(new OnComplete<Object>() {
1147             @Override
1148             public void onComplete(final Throwable failure, final Object resp) {
1149                 latch.countDown();
1150             }
1151         }, getSystem().dispatcher());
1152
1153         assertTrue("2nd CanCommit complete", latch.await(5, TimeUnit.SECONDS));
1154
1155         final InOrder inOrder = inOrder(dataTree);
1156         inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1157         inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1158         inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1159     }
1160
1161     @Test
1162     public void testCanCommitPhaseFailure() throws Exception {
1163         final ShardTestKit testKit = new ShardTestKit(getSystem());
1164         final DataTree dataTree = createDelegatingMockDataTree();
1165         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1166             newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1167             "testCanCommitPhaseFailure");
1168
1169         ShardTestKit.waitUntilLeader(shard);
1170
1171         final FiniteDuration duration = testKit.duration("5 seconds");
1172         final TransactionIdentifier transactionID1 = nextTransactionId();
1173
1174         doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1175         .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1176
1177         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1178             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1179         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1180
1181         // Send the CanCommitTransaction message.
1182
1183         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1184         testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1185
1186         // Send another can commit to ensure the failed one got cleaned
1187         // up.
1188
1189         final TransactionIdentifier transactionID2 = nextTransactionId();
1190         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1191             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1192         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1193
1194         shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1195         final CanCommitTransactionReply reply = CanCommitTransactionReply
1196                 .fromSerializable(testKit.expectMsgClass(CanCommitTransactionReply.class));
1197         assertTrue("getCanCommit", reply.getCanCommit());
1198     }
1199
1200     @Test
1201     public void testImmediateCommitWithCanCommitPhaseFailure() throws Exception {
1202         testImmediateCommitWithCanCommitPhaseFailure(true);
1203         testImmediateCommitWithCanCommitPhaseFailure(false);
1204     }
1205
1206     private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Exception {
1207         final ShardTestKit testKit = new ShardTestKit(getSystem());
1208         final DataTree dataTree = createDelegatingMockDataTree();
1209         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1210             newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1211             "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1212
1213         ShardTestKit.waitUntilLeader(shard);
1214
1215         doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1216         .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1217
1218         final FiniteDuration duration = testKit.duration("5 seconds");
1219
1220         final TransactionIdentifier transactionID1 = nextTransactionId();
1221
1222         if (readWrite) {
1223             shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
1224                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1225         } else {
1226             shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1227                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1228         }
1229
1230         testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1231
1232         // Send another can commit to ensure the failed one got cleaned
1233         // up.
1234
1235         final TransactionIdentifier transactionID2 = nextTransactionId();
1236         if (readWrite) {
1237             shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
1238                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1239         } else {
1240             shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1241                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1242         }
1243
1244         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1245     }
1246
1247     @Test
1248     public void testAbortWithCommitPending() {
1249         final ShardTestKit testKit = new ShardTestKit(getSystem());
1250         final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
1251             @Override
1252             void persistPayload(final Identifier id, final Payload payload,
1253                     final boolean batchHint) {
1254                 // Simulate an AbortTransaction message occurring during
1255                 // replication, after
1256                 // persisting and before finishing the commit to the
1257                 // in-memory store.
1258
1259                 doAbortTransaction(id, null);
1260                 super.persistPayload(id, payload, batchHint);
1261             }
1262         };
1263
1264         final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1265             .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1266             "testAbortWithCommitPending");
1267
1268         ShardTestKit.waitUntilLeader(shard);
1269
1270         final FiniteDuration duration = testKit.duration("5 seconds");
1271
1272         final TransactionIdentifier transactionID = nextTransactionId();
1273
1274         shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1275             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1276         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1277
1278         shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
1279         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1280
1281         shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
1282         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1283
1284         final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1285
1286         // Since we're simulating an abort occurring during replication
1287         // and before finish commit,
1288         // the data should still get written to the in-memory store
1289         // since we've gotten past
1290         // canCommit and preCommit and persisted the data.
1291         assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1292     }
1293
1294     @Test
1295     public void testTransactionCommitTimeout() throws Exception {
1296         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1297         final ShardTestKit testKit = new ShardTestKit(getSystem());
1298         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1299             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1300             "testTransactionCommitTimeout");
1301
1302         ShardTestKit.waitUntilLeader(shard);
1303
1304         final FiniteDuration duration = testKit.duration("5 seconds");
1305
1306         writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1307         writeToStore(shard, TestModel.OUTER_LIST_PATH,
1308             ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1309
1310         // Ready 2 Tx's - the first will timeout
1311
1312         final TransactionIdentifier transactionID1 = nextTransactionId();
1313         shard.tell(
1314             prepareBatchedModifications(transactionID1,
1315                 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1316                 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1317                 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
1318             testKit.getRef());
1319         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1320
1321         final TransactionIdentifier transactionID2 = nextTransactionId();
1322         final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1323                 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1324         shard.tell(
1325             prepareBatchedModifications(transactionID2, listNodePath,
1326                 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false), testKit.getRef());
1327         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1328
1329         // canCommit 1st Tx. We don't send the commit so it should
1330         // timeout.
1331
1332         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1333         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1334
1335         // canCommit the 2nd Tx - it should complete after the 1st Tx
1336         // times out.
1337
1338         shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1339         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1340
1341         // Try to commit the 1st Tx - should fail as it's not the
1342         // current Tx.
1343
1344         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1345         testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1346
1347         // Commit the 2nd Tx.
1348
1349         shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1350         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1351
1352         final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1353         assertNotNull(listNodePath + " not found", node);
1354     }
1355
1356 //    @Test
1357 //    @Ignore
1358 //    public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1359 //        dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1360 //
1361 //        new ShardTestKit(getSystem()) {{
1362 //            final TestActorRef<Shard> shard = actorFactory.createTestActor(
1363 //                    newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1364 //                    "testTransactionCommitQueueCapacityExceeded");
1365 //
1366 //            waitUntilLeader(shard);
1367 //
1368 //            final FiniteDuration duration = duration("5 seconds");
1369 //
1370 //            final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1371 //
1372 //            final TransactionIdentifier transactionID1 = nextTransactionId();
1373 //            final MutableCompositeModification modification1 = new MutableCompositeModification();
1374 //            final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1375 //                    TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID1,
1376 //                    modification1);
1377 //
1378 //            final TransactionIdentifier transactionID2 = nextTransactionId();
1379 //            final MutableCompositeModification modification2 = new MutableCompositeModification();
1380 //            final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1381 //                    TestModel.OUTER_LIST_PATH,
1382 //                    ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), transactionID2,
1383 //                    modification2);
1384 //
1385 //            final TransactionIdentifier transactionID3 = nextTransactionId();
1386 //            final MutableCompositeModification modification3 = new MutableCompositeModification();
1387 //            final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1388 //                    TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID3,
1389 //                    modification3);
1390 //
1391 //            // Ready the Tx's
1392 //
1393 //            shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1,
1394 //                    modification1), getRef());
1395 //            expectMsgClass(duration, ReadyTransactionReply.class);
1396 //
1397 //            shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2,
1398 //                    modification2), getRef());
1399 //            expectMsgClass(duration, ReadyTransactionReply.class);
1400 //
1401 //            // The 3rd Tx should exceed queue capacity and fail.
1402 //
1403 //            shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3,
1404 //                    modification3), getRef());
1405 //            expectMsgClass(duration, akka.actor.Status.Failure.class);
1406 //
1407 //            // canCommit 1st Tx.
1408 //
1409 //            shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1410 //            expectMsgClass(duration, CanCommitTransactionReply.class);
1411 //
1412 //            // canCommit the 2nd Tx - it should get queued.
1413 //
1414 //            shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1415 //
1416 //            // canCommit the 3rd Tx - should exceed queue capacity and fail.
1417 //
1418 //            shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1419 //            expectMsgClass(duration, akka.actor.Status.Failure.class);
1420 //        }};
1421 //    }
1422
1423     @Test
1424     public void testTransactionCommitWithPriorExpiredCohortEntries() {
1425         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1426         final ShardTestKit testKit = new ShardTestKit(getSystem());
1427         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1428             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1429             "testTransactionCommitWithPriorExpiredCohortEntries");
1430
1431         ShardTestKit.waitUntilLeader(shard);
1432
1433         final FiniteDuration duration = testKit.duration("5 seconds");
1434
1435         final TransactionIdentifier transactionID1 = nextTransactionId();
1436         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1437             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1438         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1439
1440         final TransactionIdentifier transactionID2 = nextTransactionId();
1441         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1442             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1443         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1444
1445         final TransactionIdentifier transactionID3 = nextTransactionId();
1446         shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1447             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1448         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1449
1450         // All Tx's are readied. We'll send canCommit for the last one
1451         // but not the others. The others
1452         // should expire from the queue and the last one should be
1453         // processed.
1454
1455         shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), testKit.getRef());
1456         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1457     }
1458
1459     @Test
1460     public void testTransactionCommitWithSubsequentExpiredCohortEntry() {
1461         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1462         final ShardTestKit testKit = new ShardTestKit(getSystem());
1463         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1464             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1465             "testTransactionCommitWithSubsequentExpiredCohortEntry");
1466
1467         ShardTestKit.waitUntilLeader(shard);
1468
1469         final FiniteDuration duration = testKit.duration("5 seconds");
1470
1471         final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1472
1473         final TransactionIdentifier transactionID1 = nextTransactionId();
1474         shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1475             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1476         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1477
1478         // CanCommit the first Tx so it's the current in-progress Tx.
1479
1480         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1481         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1482
1483         // Ready the second Tx.
1484
1485         final TransactionIdentifier transactionID2 = nextTransactionId();
1486         shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1487             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1488         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1489
1490         // Ready the third Tx.
1491
1492         final TransactionIdentifier transactionID3 = nextTransactionId();
1493         final DataTreeModification modification3 = dataStore.newModification();
1494         new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1495             .apply(modification3);
1496         modification3.ready();
1497         final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3,
1498             true, Optional.empty());
1499         shard.tell(readyMessage, testKit.getRef());
1500
1501         // Commit the first Tx. After completing, the second should
1502         // expire from the queue and the third
1503         // Tx committed.
1504
1505         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1506         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1507
1508         // Expect commit reply from the third Tx.
1509
1510         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1511
1512         final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1513         assertNotNull(TestModel.TEST2_PATH + " not found", node);
1514     }
1515
1516     @Test
1517     public void testCanCommitBeforeReadyFailure() {
1518         final ShardTestKit testKit = new ShardTestKit(getSystem());
1519         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1520             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1521             "testCanCommitBeforeReadyFailure");
1522
1523         shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), testKit.getRef());
1524         testKit.expectMsgClass(testKit.duration("5 seconds"), akka.actor.Status.Failure.class);
1525     }
1526
1527     @Test
1528     public void testAbortAfterCanCommit() throws Exception {
1529         final ShardTestKit testKit = new ShardTestKit(getSystem());
1530         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1531             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterCanCommit");
1532
1533         ShardTestKit.waitUntilLeader(shard);
1534
1535         final FiniteDuration duration = testKit.duration("5 seconds");
1536         final Timeout timeout = new Timeout(duration);
1537
1538         // Ready 2 transactions - the first one will be aborted.
1539
1540         final TransactionIdentifier transactionID1 = nextTransactionId();
1541         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1542             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1543         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1544
1545         final TransactionIdentifier transactionID2 = nextTransactionId();
1546         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1547             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1548         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1549
1550         // Send the CanCommitTransaction message for the first Tx.
1551
1552         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1553         CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1554                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
1555         assertTrue("Can commit", canCommitReply.getCanCommit());
1556
1557         // Send the CanCommitTransaction message for the 2nd Tx. This
1558         // should get queued and
1559         // processed after the first Tx completes.
1560
1561         final Future<Object> canCommitFuture = Patterns.ask(shard,
1562             new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1563
1564         // Send the AbortTransaction message for the first Tx. This
1565         // should trigger the 2nd
1566         // Tx to proceed.
1567
1568         shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1569         testKit.expectMsgClass(duration, AbortTransactionReply.class);
1570
1571         // Wait for the 2nd Tx to complete the canCommit phase.
1572
1573         canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture, duration);
1574         assertTrue("Can commit", canCommitReply.getCanCommit());
1575     }
1576
1577     @Test
1578     public void testAbortAfterReady() {
1579         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1580         final ShardTestKit testKit = new ShardTestKit(getSystem());
1581         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1582             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1583
1584         ShardTestKit.waitUntilLeader(shard);
1585
1586         final FiniteDuration duration = testKit.duration("5 seconds");
1587
1588         // Ready a tx.
1589
1590         final TransactionIdentifier transactionID1 = nextTransactionId();
1591         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1592             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1593         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1594
1595         // Send the AbortTransaction message.
1596
1597         shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1598         testKit.expectMsgClass(duration, AbortTransactionReply.class);
1599
1600         assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1601
1602         // Now send CanCommitTransaction - should fail.
1603
1604         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1605         final Throwable failure = testKit.expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
1606         assertTrue("Failure type", failure instanceof IllegalStateException);
1607
1608         // Ready and CanCommit another and verify success.
1609
1610         final TransactionIdentifier transactionID2 = nextTransactionId();
1611         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1612             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1613         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1614
1615         shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1616         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1617     }
1618
1619     @Test
1620     public void testAbortQueuedTransaction() {
1621         final ShardTestKit testKit = new ShardTestKit(getSystem());
1622         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1623             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1624
1625         ShardTestKit.waitUntilLeader(shard);
1626
1627         final FiniteDuration duration = testKit.duration("5 seconds");
1628
1629         // Ready 3 tx's.
1630
1631         final TransactionIdentifier transactionID1 = nextTransactionId();
1632         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1633             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1634         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1635
1636         final TransactionIdentifier transactionID2 = nextTransactionId();
1637         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1638             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1639         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1640
1641         final TransactionIdentifier transactionID3 = nextTransactionId();
1642         shard.tell(newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
1643                 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1), testKit.getRef());
1644         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1645
1646         // Abort the second tx while it's queued.
1647
1648         shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1649         testKit.expectMsgClass(duration, AbortTransactionReply.class);
1650
1651         // Commit the other 2.
1652
1653         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1654         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1655
1656         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1657         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1658
1659         shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), testKit.getRef());
1660         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1661
1662         shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), testKit.getRef());
1663         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1664
1665         assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1666     }
1667
1668     @Test
1669     public void testCreateSnapshotWithNonPersistentData() throws Exception {
1670         testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1671     }
1672
1673     @Test
1674     public void testCreateSnapshot() throws Exception {
1675         testCreateSnapshot(true, "testCreateSnapshot");
1676     }
1677
1678     private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception {
1679         final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1680
1681         final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1682         class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
1683             TestPersistentDataProvider(final DataPersistenceProvider delegate) {
1684                 super(delegate);
1685             }
1686
1687             @Override
1688             public void saveSnapshot(final Object obj) {
1689                 savedSnapshot.set(obj);
1690                 super.saveSnapshot(obj);
1691             }
1692         }
1693
1694         dataStoreContextBuilder.persistent(persistent);
1695
1696         class TestShard extends Shard {
1697
1698             protected TestShard(final AbstractBuilder<?, ?> builder) {
1699                 super(builder);
1700                 setPersistence(new TestPersistentDataProvider(super.persistence()));
1701             }
1702
1703             @Override
1704             public void handleCommand(final Object message) {
1705                 super.handleCommand(message);
1706
1707                 // XXX:  commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
1708                 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
1709                     latch.get().countDown();
1710                 }
1711             }
1712
1713             @Override
1714             public RaftActorContext getRaftActorContext() {
1715                 return super.getRaftActorContext();
1716             }
1717         }
1718
1719         final ShardTestKit testKit = new ShardTestKit(getSystem());
1720
1721         final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
1722
1723         final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1724             .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1725             shardActorName);
1726
1727         ShardTestKit.waitUntilLeader(shard);
1728         writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1729
1730         final NormalizedNode<?, ?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
1731
1732         // Trigger creation of a snapshot by ensuring
1733         final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
1734         raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1735         awaitAndValidateSnapshot(latch, savedSnapshot, expectedRoot);
1736
1737         raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1738         awaitAndValidateSnapshot(latch, savedSnapshot, expectedRoot);
1739     }
1740
1741     private static void awaitAndValidateSnapshot(final AtomicReference<CountDownLatch> latch,
1742             final AtomicReference<Object> savedSnapshot, final NormalizedNode<?, ?> expectedRoot)
1743                     throws InterruptedException {
1744         assertTrue("Snapshot saved", latch.get().await(5, TimeUnit.SECONDS));
1745
1746         assertTrue("Invalid saved snapshot " + savedSnapshot.get(), savedSnapshot.get() instanceof Snapshot);
1747
1748         verifySnapshot((Snapshot) savedSnapshot.get(), expectedRoot);
1749
1750         latch.set(new CountDownLatch(1));
1751         savedSnapshot.set(null);
1752     }
1753
1754     private static void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?, ?> expectedRoot) {
1755         final NormalizedNode<?, ?> actual = ((ShardSnapshotState)snapshot.getState()).getSnapshot().getRootNode().get();
1756         assertEquals("Root node", expectedRoot, actual);
1757     }
1758
1759     /**
1760      * This test simply verifies that the applySnapShot logic will work.
1761      */
1762     @Test
1763     public void testInMemoryDataTreeRestore() throws DataValidationFailedException {
1764         final DataTree store = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL,
1765             SCHEMA_CONTEXT);
1766
1767         final DataTreeModification putTransaction = store.takeSnapshot().newModification();
1768         putTransaction.write(TestModel.TEST_PATH,
1769             ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1770         commitTransaction(store, putTransaction);
1771
1772
1773         final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
1774
1775         final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
1776
1777         writeTransaction.delete(YangInstanceIdentifier.EMPTY);
1778         writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
1779
1780         commitTransaction(store, writeTransaction);
1781
1782         final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
1783
1784         assertEquals(expected, actual);
1785     }
1786
1787     @Test
1788     public void testRecoveryApplicable() {
1789
1790         final DatastoreContext persistentContext = DatastoreContext.newBuilder()
1791                 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
1792
1793         final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext)
1794                 .schemaContextProvider(() -> SCHEMA_CONTEXT).props();
1795
1796         final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder()
1797                 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
1798
1799         final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext)
1800                 .schemaContextProvider(() -> SCHEMA_CONTEXT).props();
1801
1802         final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
1803
1804         assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
1805
1806         final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
1807
1808         assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
1809     }
1810
1811     @Test
1812     public void testOnDatastoreContext() {
1813         dataStoreContextBuilder.persistent(true);
1814
1815         final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
1816
1817         assertTrue("isRecoveryApplicable", shard.underlyingActor().persistence().isRecoveryApplicable());
1818
1819         ShardTestKit.waitUntilLeader(shard);
1820
1821         shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
1822
1823         assertFalse("isRecoveryApplicable", shard.underlyingActor().persistence().isRecoveryApplicable());
1824
1825         shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
1826
1827         assertTrue("isRecoveryApplicable", shard.underlyingActor().persistence().isRecoveryApplicable());
1828     }
1829
1830     @Test
1831     public void testRegisterRoleChangeListener() {
1832         final ShardTestKit testKit = new ShardTestKit(getSystem());
1833         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1834             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1835             "testRegisterRoleChangeListener");
1836
1837         ShardTestKit.waitUntilLeader(shard);
1838
1839         final ActorRef listener = getSystem().actorOf(MessageCollectorActor.props());
1840
1841         shard.tell(new RegisterRoleChangeListener(), listener);
1842
1843         MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
1844
1845         ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
1846             ShardLeaderStateChanged.class);
1847         assertTrue("getLocalShardDataTree present", leaderStateChanged.getLocalShardDataTree().isPresent());
1848         assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
1849             leaderStateChanged.getLocalShardDataTree().get());
1850
1851         MessageCollectorActor.clearMessages(listener);
1852
1853         // Force a leader change
1854
1855         shard.tell(new RequestVote(10000, "member2", 50, 50), testKit.getRef());
1856
1857         leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener, ShardLeaderStateChanged.class);
1858         assertFalse("getLocalShardDataTree present", leaderStateChanged.getLocalShardDataTree().isPresent());
1859     }
1860
1861     @Test
1862     public void testFollowerInitialSyncStatus() {
1863         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1864                 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1865                 "testFollowerInitialSyncStatus");
1866
1867         shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false,
1868                 "member-1-shard-inventory-operational"));
1869
1870         assertFalse(shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1871
1872         shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true,
1873                 "member-1-shard-inventory-operational"));
1874
1875         assertTrue(shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1876     }
1877
1878     @Test
1879     public void testClusteredDataTreeChangeListenerWithDelayedRegistration() throws Exception {
1880         final ShardTestKit testKit = new ShardTestKit(getSystem());
1881         final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistration";
1882         dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
1883             .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
1884
1885         final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
1886         final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
1887             TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
1888
1889         setupInMemorySnapshotStore();
1890
1891         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1892             newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1893             actorFactory.generateActorId(testName + "-shard"));
1894
1895         testKit.waitUntilNoLeader(shard);
1896
1897         shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), testKit.getRef());
1898         final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(testKit.duration("5 seconds"),
1899             RegisterDataTreeNotificationListenerReply.class);
1900         assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
1901
1902         shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
1903             .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
1904
1905         listener.waitForChangeEvents();
1906     }
1907
1908     @Test
1909     public void testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed() throws Exception {
1910         final ShardTestKit testKit = new ShardTestKit(getSystem());
1911         final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed";
1912         dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
1913             .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
1914
1915         final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(0);
1916         final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
1917             TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
1918
1919         setupInMemorySnapshotStore();
1920
1921         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1922             newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1923             actorFactory.generateActorId(testName + "-shard"));
1924
1925         testKit.waitUntilNoLeader(shard);
1926
1927         shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), testKit.getRef());
1928         final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(testKit.duration("5 seconds"),
1929             RegisterDataTreeNotificationListenerReply.class);
1930         assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
1931
1932         final ActorSelection regActor = getSystem().actorSelection(reply.getListenerRegistrationPath());
1933         regActor.tell(CloseDataTreeNotificationListenerRegistration.getInstance(), testKit.getRef());
1934         testKit.expectMsgClass(CloseDataTreeNotificationListenerRegistrationReply.class);
1935
1936         shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
1937             .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
1938
1939         listener.expectNoMoreChanges("Received unexpected change after close");
1940     }
1941
1942     @Test
1943     public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
1944         final ShardTestKit testKit = new ShardTestKit(getSystem());
1945         final String testName = "testClusteredDataTreeChangeListenerRegistration";
1946         final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
1947             MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
1948
1949         final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
1950             MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
1951
1952         final TestActorRef<Shard> followerShard = actorFactory
1953                 .createTestActor(Shard.builder().id(followerShardID)
1954                     .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
1955                     .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
1956                         "akka://test/user/" + leaderShardID.toString()))
1957                     .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
1958                     .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
1959
1960         final TestActorRef<Shard> leaderShard = actorFactory
1961                 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
1962                     .peerAddresses(Collections.singletonMap(followerShardID.toString(),
1963                         "akka://test/user/" + followerShardID.toString()))
1964                     .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
1965                     .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
1966
1967         leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1968         final String leaderPath = ShardTestKit.waitUntilLeader(followerShard);
1969         assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
1970
1971         final YangInstanceIdentifier path = TestModel.TEST_PATH;
1972         final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
1973         final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
1974             actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
1975
1976         followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), testKit.getRef());
1977         final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(testKit.duration("5 seconds"),
1978             RegisterDataTreeNotificationListenerReply.class);
1979         assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
1980
1981         writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1982
1983         listener.waitForChangeEvents();
1984     }
1985
1986     @Test
1987     public void testServerRemoved() {
1988         final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props()
1989                 .withDispatcher(Dispatchers.DefaultDispatcherId()));
1990
1991         final ActorRef shard = parent.underlyingActor().context().actorOf(
1992                 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1993                 "testServerRemoved");
1994
1995         shard.tell(new ServerRemoved("test"), ActorRef.noSender());
1996
1997         MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);
1998     }
1999 }