Eliminate ShardTestKit subclasses
[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         assertEquals("Got first ElectionTimeout", true, 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 =
445                         CanCommitTransactionReply.fromSerializable(resp);
446                 assertEquals("Can commit", true, canCommitReply.getCanCommit());
447
448                 final Future<Object> commitFuture = Patterns.ask(shard,
449                         new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
450                 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
451             }
452         }
453
454         final ShardTestKit testKit = new ShardTestKit(getSystem());
455         ShardTestKit.waitUntilLeader(shard);
456
457         final TransactionIdentifier transactionID1 = nextTransactionId();
458         final TransactionIdentifier transactionID2 = nextTransactionId();
459         final TransactionIdentifier transactionID3 = nextTransactionId();
460
461         final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
462             shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
463         final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
464         final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
465         final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
466
467         shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
468             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
469         final ReadyTransactionReply readyReply = ReadyTransactionReply
470                 .fromSerializable(testKit.expectMsgClass(duration, ReadyTransactionReply.class));
471         assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
472         // Send the CanCommitTransaction message for the first Tx.
473
474         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
475         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
476                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
477         assertEquals("Can commit", true, canCommitReply.getCanCommit());
478
479         // Ready 2 more Tx's.
480
481         shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
482             ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), testKit.getRef());
483         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
484
485         shard.tell(
486             prepareBatchedModifications(transactionID3,
487                 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
488                 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
489                 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false), testKit.getRef());
490         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
491
492         // Send the CanCommitTransaction message for the next 2 Tx's.
493         // These should get queued and
494         // processed after the first Tx completes.
495
496         final Future<Object> canCommitFuture1 = Patterns.ask(shard,
497             new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
498
499         final Future<Object> canCommitFuture2 = Patterns.ask(shard,
500             new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
501
502         // Send the CommitTransaction message for the first Tx. After it
503         // completes, it should
504         // trigger the 2nd Tx to proceed which should in turn then
505         // trigger the 3rd.
506
507         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
508         testKit.expectMsgClass(duration, CommitTransactionReply.class);
509
510         // Wait for the next 2 Tx's to complete.
511
512         canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2), getSystem().dispatcher());
513
514         canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3), getSystem().dispatcher());
515
516         final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
517
518         final Throwable t = caughtEx.get();
519         if (t != null) {
520             Throwables.propagateIfPossible(t, Exception.class);
521             throw new RuntimeException(t);
522         }
523
524         assertEquals("Commits complete", true, done);
525
526 //                final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
527 //                        cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
528 //                        cohort3.getPreCommit(), cohort3.getCommit());
529 //                inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
530 //                inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
531 //                inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
532 //                inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
533 //                inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
534 //                inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
535 //                inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
536 //                inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
537 //                inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
538
539         // Verify data in the data store.
540
541         verifyOuterListEntry(shard, 1);
542
543         verifyLastApplied(shard, 5);
544     }
545
546     @Test
547     public void testBatchedModificationsWithNoCommitOnReady() {
548         final ShardTestKit testKit = new ShardTestKit(getSystem());
549         final TestActorRef<Shard> shard = actorFactory.createTestActor(
550             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
551             "testBatchedModificationsWithNoCommitOnReady");
552
553         ShardTestKit.waitUntilLeader(shard);
554
555         final TransactionIdentifier transactionID = nextTransactionId();
556         final FiniteDuration duration = testKit.duration("5 seconds");
557
558         // Send a BatchedModifications to start a transaction.
559
560         shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
561             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), testKit.getRef());
562         testKit.expectMsgClass(duration, BatchedModificationsReply.class);
563
564         // Send a couple more BatchedModifications.
565
566         shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
567                 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
568             testKit.getRef());
569         testKit.expectMsgClass(duration, BatchedModificationsReply.class);
570
571         shard.tell(newBatchedModifications(transactionID,
572             YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
573             .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
574             ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3),
575             testKit.getRef());
576         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
577
578         // Send the CanCommitTransaction message.
579
580         shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
581         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
582                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
583         assertEquals("Can commit", true, canCommitReply.getCanCommit());
584
585         // Send the CommitTransaction message.
586
587         shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
588         testKit.expectMsgClass(duration, CommitTransactionReply.class);
589
590         // Verify data in the data store.
591
592         verifyOuterListEntry(shard, 1);
593     }
594
595     @Test
596     public void testBatchedModificationsWithCommitOnReady() {
597         final ShardTestKit testKit = new ShardTestKit(getSystem());
598         final TestActorRef<Shard> shard = actorFactory.createTestActor(
599             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
600             "testBatchedModificationsWithCommitOnReady");
601
602         ShardTestKit.waitUntilLeader(shard);
603
604         final TransactionIdentifier transactionID = nextTransactionId();
605         final FiniteDuration duration = testKit.duration("5 seconds");
606
607         // Send a BatchedModifications to start a transaction.
608
609         shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
610             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), testKit.getRef());
611         testKit.expectMsgClass(duration, BatchedModificationsReply.class);
612
613         // Send a couple more BatchedModifications.
614
615         shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
616             ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
617             testKit.getRef());
618         testKit.expectMsgClass(duration, BatchedModificationsReply.class);
619
620         shard.tell(newBatchedModifications(transactionID,
621             YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
622             .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
623             ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3),
624             testKit.getRef());
625
626         testKit.expectMsgClass(duration, CommitTransactionReply.class);
627
628         // Verify data in the data store.
629         verifyOuterListEntry(shard, 1);
630     }
631
632     @Test(expected = IllegalStateException.class)
633     public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
634         final ShardTestKit testKit = new ShardTestKit(getSystem());
635         final TestActorRef<Shard> shard = actorFactory.createTestActor(
636             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
637             "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
638
639         ShardTestKit.waitUntilLeader(shard);
640
641         final TransactionIdentifier transactionID = nextTransactionId();
642         final BatchedModifications batched = new BatchedModifications(transactionID,
643             DataStoreVersions.CURRENT_VERSION);
644         batched.setReady();
645         batched.setTotalMessagesSent(2);
646
647         shard.tell(batched, testKit.getRef());
648
649         final Failure failure = testKit.expectMsgClass(testKit.duration("5 seconds"), Failure.class);
650
651         if (failure != null) {
652             Throwables.propagateIfPossible(failure.cause(), Exception.class);
653             throw new RuntimeException(failure.cause());
654         }
655     }
656
657     @Test
658     public void testBatchedModificationsWithOperationFailure() {
659         final ShardTestKit testKit = new ShardTestKit(getSystem());
660         final TestActorRef<Shard> shard = actorFactory.createTestActor(
661             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
662             "testBatchedModificationsWithOperationFailure");
663
664         ShardTestKit.waitUntilLeader(shard);
665
666         // Test merge with invalid data. An exception should occur when
667         // the merge is applied. Note that
668         // write will not validate the children for performance reasons.
669
670         final TransactionIdentifier transactionID = nextTransactionId();
671
672         final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
673                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
674                 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
675
676         BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
677         batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
678         shard.tell(batched, testKit.getRef());
679         Failure failure = testKit.expectMsgClass(testKit.duration("5 seconds"), akka.actor.Status.Failure.class);
680
681         final Throwable cause = failure.cause();
682
683         batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
684         batched.setReady();
685         batched.setTotalMessagesSent(2);
686
687         shard.tell(batched, testKit.getRef());
688
689         failure = testKit.expectMsgClass(testKit.duration("5 seconds"), akka.actor.Status.Failure.class);
690         assertEquals("Failure cause", cause, failure.cause());
691     }
692
693     @Test
694     public void testBatchedModificationsOnTransactionChain() {
695         final ShardTestKit testKit = new ShardTestKit(getSystem());
696         final TestActorRef<Shard> shard = actorFactory.createTestActor(
697             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
698             "testBatchedModificationsOnTransactionChain");
699
700         ShardTestKit.waitUntilLeader(shard);
701
702         final LocalHistoryIdentifier historyId = nextHistoryId();
703         final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
704         final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
705
706         final FiniteDuration duration = testKit.duration("5 seconds");
707
708         // Send a BatchedModifications to start a chained write
709         // transaction and ready it.
710
711         final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
712         final YangInstanceIdentifier path = TestModel.TEST_PATH;
713         shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), testKit.getRef());
714         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
715
716         // Create a read Tx on the same chain.
717
718         shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
719             DataStoreVersions.CURRENT_VERSION).toSerializable(), testKit.getRef());
720
721         final CreateTransactionReply createReply = testKit.expectMsgClass(testKit.duration("3 seconds"),
722             CreateTransactionReply.class);
723
724         getSystem().actorSelection(createReply.getTransactionPath())
725         .tell(new ReadData(path, DataStoreVersions.CURRENT_VERSION), testKit.getRef());
726         final ReadDataReply readReply = testKit.expectMsgClass(testKit.duration("3 seconds"), ReadDataReply.class);
727         assertEquals("Read node", containerNode, readReply.getNormalizedNode());
728
729         // Commit the write transaction.
730
731         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
732         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
733                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
734         assertEquals("Can commit", true, canCommitReply.getCanCommit());
735
736         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
737         testKit.expectMsgClass(duration, CommitTransactionReply.class);
738
739         // Verify data in the data store.
740
741         final NormalizedNode<?, ?> actualNode = readStore(shard, path);
742         assertEquals("Stored node", containerNode, actualNode);
743     }
744
745     @Test
746     public void testOnBatchedModificationsWhenNotLeader() {
747         final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
748         final ShardTestKit testKit = new ShardTestKit(getSystem());
749         final Creator<Shard> creator = new Creator<Shard>() {
750             private static final long serialVersionUID = 1L;
751
752             @Override
753             public Shard create() {
754                 return new Shard(newShardBuilder()) {
755                     @Override
756                     protected boolean isLeader() {
757                         return overrideLeaderCalls.get() ? false : super.isLeader();
758                     }
759
760                     @Override
761                     public ActorSelection getLeader() {
762                         return overrideLeaderCalls.get() ? getSystem().actorSelection(testKit.getRef().path())
763                                 : super.getLeader();
764                     }
765                 };
766             }
767         };
768
769         final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
770             .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
771             "testOnBatchedModificationsWhenNotLeader");
772
773         ShardTestKit.waitUntilLeader(shard);
774
775         overrideLeaderCalls.set(true);
776
777         final BatchedModifications batched = new BatchedModifications(nextTransactionId(),
778             DataStoreVersions.CURRENT_VERSION);
779
780         shard.tell(batched, ActorRef.noSender());
781
782         testKit.expectMsgEquals(batched);
783     }
784
785     @Test
786     public void testTransactionMessagesWithNoLeader() {
787         final ShardTestKit testKit = new ShardTestKit(getSystem());
788         dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
789         .shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
790         final TestActorRef<Shard> shard = actorFactory.createTestActor(
791             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
792             "testTransactionMessagesWithNoLeader");
793
794         testKit.waitUntilNoLeader(shard);
795
796         final TransactionIdentifier txId = nextTransactionId();
797         shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), testKit.getRef());
798         Failure failure = testKit.expectMsgClass(Failure.class);
799         assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
800
801         shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
802             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
803         failure = testKit.expectMsgClass(Failure.class);
804         assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
805
806         shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true, Optional.empty()),
807             testKit.getRef());
808         failure = testKit.expectMsgClass(Failure.class);
809         assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
810     }
811
812     @Test
813     public void testReadyWithReadWriteImmediateCommit() {
814         testReadyWithImmediateCommit(true);
815     }
816
817     @Test
818     public void testReadyWithWriteOnlyImmediateCommit() {
819         testReadyWithImmediateCommit(false);
820     }
821
822     private void testReadyWithImmediateCommit(final boolean readWrite) {
823         final ShardTestKit testKit = new ShardTestKit(getSystem());
824         final TestActorRef<Shard> shard = actorFactory.createTestActor(
825             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
826             "testReadyWithImmediateCommit-" + readWrite);
827
828         ShardTestKit.waitUntilLeader(shard);
829
830         final TransactionIdentifier transactionID = nextTransactionId();
831         final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
832         if (readWrite) {
833             shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH, containerNode, true),
834                 testKit.getRef());
835         } else {
836             shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true),
837                 testKit.getRef());
838         }
839
840         testKit.expectMsgClass(testKit.duration("5 seconds"), CommitTransactionReply.class);
841
842         final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
843         assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
844     }
845
846     @Test
847     public void testReadyLocalTransactionWithImmediateCommit() {
848         final ShardTestKit testKit = new ShardTestKit(getSystem());
849         final TestActorRef<Shard> shard = actorFactory.createTestActor(
850             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
851             "testReadyLocalTransactionWithImmediateCommit");
852
853         ShardTestKit.waitUntilLeader(shard);
854
855         final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
856
857         final DataTreeModification modification = dataStore.newModification();
858
859         final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
860         new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
861         final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
862         new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
863
864         final TransactionIdentifier txId = nextTransactionId();
865         modification.ready();
866         final ReadyLocalTransaction readyMessage =
867                 new ReadyLocalTransaction(txId, modification, true, Optional.empty());
868
869         shard.tell(readyMessage, testKit.getRef());
870
871         testKit.expectMsgClass(CommitTransactionReply.class);
872
873         final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
874         assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
875     }
876
877     @Test
878     public void testReadyLocalTransactionWithThreePhaseCommit() {
879         final ShardTestKit testKit = new ShardTestKit(getSystem());
880         final TestActorRef<Shard> shard = actorFactory.createTestActor(
881             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
882             "testReadyLocalTransactionWithThreePhaseCommit");
883
884         ShardTestKit.waitUntilLeader(shard);
885
886         final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
887
888         final DataTreeModification modification = dataStore.newModification();
889
890         final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
891         new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
892         final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
893         new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
894
895         final TransactionIdentifier txId = nextTransactionId();
896         modification.ready();
897         final ReadyLocalTransaction readyMessage =
898                 new ReadyLocalTransaction(txId, modification, false, Optional.empty());
899
900         shard.tell(readyMessage, testKit.getRef());
901
902         testKit.expectMsgClass(ReadyTransactionReply.class);
903
904         // Send the CanCommitTransaction message.
905
906         shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), testKit.getRef());
907         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
908                 .fromSerializable(testKit.expectMsgClass(CanCommitTransactionReply.class));
909         assertEquals("Can commit", true, canCommitReply.getCanCommit());
910
911         // Send the CanCommitTransaction message.
912
913         shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), testKit.getRef());
914         testKit.expectMsgClass(CommitTransactionReply.class);
915
916         final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
917         assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
918     }
919
920     @Test
921     public void testReadWriteCommitWithPersistenceDisabled() {
922         dataStoreContextBuilder.persistent(false);
923         final ShardTestKit testKit = new ShardTestKit(getSystem());
924         final TestActorRef<Shard> shard = actorFactory.createTestActor(
925             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
926             "testCommitWithPersistenceDisabled");
927
928         ShardTestKit.waitUntilLeader(shard);
929
930         // Setup a simulated transactions with a mock cohort.
931
932         final FiniteDuration duration = testKit.duration("5 seconds");
933
934         final TransactionIdentifier transactionID = nextTransactionId();
935         final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
936         shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false),
937             testKit.getRef());
938         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
939
940         // Send the CanCommitTransaction message.
941
942         shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
943         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
944                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
945         assertEquals("Can commit", true, canCommitReply.getCanCommit());
946
947         // Send the CanCommitTransaction message.
948
949         shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
950         testKit.expectMsgClass(duration, CommitTransactionReply.class);
951
952         final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
953         assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
954     }
955
956     @Test
957     public void testReadWriteCommitWhenTransactionHasModifications() throws Exception {
958         testCommitWhenTransactionHasModifications(true);
959     }
960
961     @Test
962     public void testWriteOnlyCommitWhenTransactionHasModifications() throws Exception {
963         testCommitWhenTransactionHasModifications(false);
964     }
965
966     private void testCommitWhenTransactionHasModifications(final boolean readWrite) throws Exception {
967         final ShardTestKit testKit = new ShardTestKit(getSystem());
968         final DataTree dataTree = createDelegatingMockDataTree();
969         final TestActorRef<Shard> shard = actorFactory.createTestActor(
970             newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
971             "testCommitWhenTransactionHasModifications-" + readWrite);
972
973         ShardTestKit.waitUntilLeader(shard);
974
975         final FiniteDuration duration = testKit.duration("5 seconds");
976         final TransactionIdentifier transactionID = nextTransactionId();
977
978         if (readWrite) {
979             shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
980                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
981         } else {
982             shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
983                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
984         }
985
986         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
987
988         // Send the CanCommitTransaction message.
989
990         shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
991         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
992                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
993         assertEquals("Can commit", true, canCommitReply.getCanCommit());
994
995         shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
996         testKit.expectMsgClass(duration, CommitTransactionReply.class);
997
998         final InOrder inOrder = inOrder(dataTree);
999         inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1000         inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1001         inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1002
1003         // Purge request is scheduled as asynchronous, wait for two heartbeats to let it propagate into
1004         // the journal
1005         Thread.sleep(HEARTBEAT_MILLIS * 2);
1006
1007         shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, testKit.getRef());
1008         final ShardStats shardStats = testKit.expectMsgClass(duration, ShardStats.class);
1009
1010         // Use MBean for verification
1011         // Committed transaction count should increase as usual
1012         assertEquals(1, shardStats.getCommittedTransactionsCount());
1013
1014         // Commit index should advance as we do not have an empty
1015         // modification
1016         assertEquals(1, shardStats.getCommitIndex());
1017     }
1018
1019     @Test
1020     public void testCommitPhaseFailure() throws Exception {
1021         final ShardTestKit testKit = new ShardTestKit(getSystem());
1022         final DataTree dataTree = createDelegatingMockDataTree();
1023         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1024             newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1025             "testCommitPhaseFailure");
1026
1027         ShardTestKit.waitUntilLeader(shard);
1028
1029         final FiniteDuration duration = testKit.duration("5 seconds");
1030         final Timeout timeout = new Timeout(duration);
1031
1032         // Setup 2 simulated transactions with mock cohorts. The first
1033         // one fails in the
1034         // commit phase.
1035
1036         doThrow(new RuntimeException("mock commit failure")).when(dataTree)
1037         .commit(any(DataTreeCandidate.class));
1038
1039         final TransactionIdentifier transactionID1 = nextTransactionId();
1040         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1041             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1042         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1043
1044         final TransactionIdentifier transactionID2 = nextTransactionId();
1045         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1046             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1047         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1048
1049         // Send the CanCommitTransaction message for the first Tx.
1050
1051         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1052         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1053                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
1054         assertEquals("Can commit", true, canCommitReply.getCanCommit());
1055
1056         // Send the CanCommitTransaction message for the 2nd Tx. This
1057         // should get queued and
1058         // processed after the first Tx completes.
1059
1060         final Future<Object> canCommitFuture = Patterns.ask(shard,
1061             new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1062
1063         // Send the CommitTransaction message for the first Tx. This
1064         // should send back an error
1065         // and trigger the 2nd Tx to proceed.
1066
1067         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1068         testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1069
1070         // Wait for the 2nd Tx to complete the canCommit phase.
1071
1072         final CountDownLatch latch = new CountDownLatch(1);
1073         canCommitFuture.onComplete(new OnComplete<Object>() {
1074             @Override
1075             public void onComplete(final Throwable failure, final Object resp) {
1076                 latch.countDown();
1077             }
1078         }, getSystem().dispatcher());
1079
1080         assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1081
1082         final InOrder inOrder = inOrder(dataTree);
1083         inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1084         inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1085
1086         // FIXME: this invocation is done on the result of validate(). To test it, we need to make sure mock
1087         //        validate performs wrapping and we capture that mock
1088         // inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1089
1090         inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1091     }
1092
1093     @Test
1094     public void testPreCommitPhaseFailure() throws Exception {
1095         final ShardTestKit testKit = new ShardTestKit(getSystem());
1096         final DataTree dataTree = createDelegatingMockDataTree();
1097         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1098             newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1099             "testPreCommitPhaseFailure");
1100
1101         ShardTestKit.waitUntilLeader(shard);
1102
1103         final FiniteDuration duration = testKit.duration("5 seconds");
1104         final Timeout timeout = new Timeout(duration);
1105
1106         doThrow(new RuntimeException("mock preCommit failure")).when(dataTree)
1107         .prepare(any(DataTreeModification.class));
1108
1109         final TransactionIdentifier transactionID1 = nextTransactionId();
1110         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1111             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1112         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1113
1114         final TransactionIdentifier transactionID2 = nextTransactionId();
1115         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1116             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1117         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1118
1119         // Send the CanCommitTransaction message for the first Tx.
1120
1121         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1122         final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1123                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
1124         assertEquals("Can commit", true, canCommitReply.getCanCommit());
1125
1126         // Send the CanCommitTransaction message for the 2nd Tx. This
1127         // should get queued and
1128         // processed after the first Tx completes.
1129
1130         final Future<Object> canCommitFuture = Patterns.ask(shard,
1131             new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1132
1133         // Send the CommitTransaction message for the first Tx. This
1134         // should send back an error
1135         // and trigger the 2nd Tx to proceed.
1136
1137         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1138         testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1139
1140         // Wait for the 2nd Tx to complete the canCommit phase.
1141
1142         final CountDownLatch latch = new CountDownLatch(1);
1143         canCommitFuture.onComplete(new OnComplete<Object>() {
1144             @Override
1145             public void onComplete(final Throwable failure, final Object resp) {
1146                 latch.countDown();
1147             }
1148         }, getSystem().dispatcher());
1149
1150         assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1151
1152         final InOrder inOrder = inOrder(dataTree);
1153         inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1154         inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1155         inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1156     }
1157
1158     @Test
1159     public void testCanCommitPhaseFailure() throws Exception {
1160         final ShardTestKit testKit = new ShardTestKit(getSystem());
1161         final DataTree dataTree = createDelegatingMockDataTree();
1162         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1163             newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1164             "testCanCommitPhaseFailure");
1165
1166         ShardTestKit.waitUntilLeader(shard);
1167
1168         final FiniteDuration duration = testKit.duration("5 seconds");
1169         final TransactionIdentifier transactionID1 = nextTransactionId();
1170
1171         doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1172         .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1173
1174         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1175             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1176         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1177
1178         // Send the CanCommitTransaction message.
1179
1180         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1181         testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1182
1183         // Send another can commit to ensure the failed one got cleaned
1184         // up.
1185
1186         final TransactionIdentifier transactionID2 = nextTransactionId();
1187         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1188             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1189         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1190
1191         shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1192         final CanCommitTransactionReply reply = CanCommitTransactionReply
1193                 .fromSerializable(testKit.expectMsgClass(CanCommitTransactionReply.class));
1194         assertEquals("getCanCommit", true, reply.getCanCommit());
1195     }
1196
1197     @Test
1198     public void testImmediateCommitWithCanCommitPhaseFailure() throws Exception {
1199         testImmediateCommitWithCanCommitPhaseFailure(true);
1200         testImmediateCommitWithCanCommitPhaseFailure(false);
1201     }
1202
1203     private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Exception {
1204         final ShardTestKit testKit = new ShardTestKit(getSystem());
1205         final DataTree dataTree = createDelegatingMockDataTree();
1206         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1207             newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1208             "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1209
1210         ShardTestKit.waitUntilLeader(shard);
1211
1212         doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1213         .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1214
1215         final FiniteDuration duration = testKit.duration("5 seconds");
1216
1217         final TransactionIdentifier transactionID1 = nextTransactionId();
1218
1219         if (readWrite) {
1220             shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
1221                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1222         } else {
1223             shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1224                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1225         }
1226
1227         testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1228
1229         // Send another can commit to ensure the failed one got cleaned
1230         // up.
1231
1232         final TransactionIdentifier transactionID2 = nextTransactionId();
1233         if (readWrite) {
1234             shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
1235                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1236         } else {
1237             shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1238                 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1239         }
1240
1241         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1242     }
1243
1244     @Test
1245     public void testAbortWithCommitPending() {
1246         final ShardTestKit testKit = new ShardTestKit(getSystem());
1247         final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
1248             @Override
1249             void persistPayload(final Identifier id, final Payload payload,
1250                     final boolean batchHint) {
1251                 // Simulate an AbortTransaction message occurring during
1252                 // replication, after
1253                 // persisting and before finishing the commit to the
1254                 // in-memory store.
1255
1256                 doAbortTransaction(id, null);
1257                 super.persistPayload(id, payload, batchHint);
1258             }
1259         };
1260
1261         final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1262             .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1263             "testAbortWithCommitPending");
1264
1265         ShardTestKit.waitUntilLeader(shard);
1266
1267         final FiniteDuration duration = testKit.duration("5 seconds");
1268
1269         final TransactionIdentifier transactionID = nextTransactionId();
1270
1271         shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1272             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1273         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1274
1275         shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
1276         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1277
1278         shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
1279         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1280
1281         final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1282
1283         // Since we're simulating an abort occurring during replication
1284         // and before finish commit,
1285         // the data should still get written to the in-memory store
1286         // since we've gotten past
1287         // canCommit and preCommit and persisted the data.
1288         assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1289     }
1290
1291     @Test
1292     public void testTransactionCommitTimeout() throws Exception {
1293         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1294         final ShardTestKit testKit = new ShardTestKit(getSystem());
1295         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1296             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1297             "testTransactionCommitTimeout");
1298
1299         ShardTestKit.waitUntilLeader(shard);
1300
1301         final FiniteDuration duration = testKit.duration("5 seconds");
1302
1303         writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1304         writeToStore(shard, TestModel.OUTER_LIST_PATH,
1305             ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1306
1307         // Ready 2 Tx's - the first will timeout
1308
1309         final TransactionIdentifier transactionID1 = nextTransactionId();
1310         shard.tell(
1311             prepareBatchedModifications(transactionID1,
1312                 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1313                 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1314                 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
1315             testKit.getRef());
1316         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1317
1318         final TransactionIdentifier transactionID2 = nextTransactionId();
1319         final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1320                 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1321         shard.tell(
1322             prepareBatchedModifications(transactionID2, listNodePath,
1323                 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false), testKit.getRef());
1324         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1325
1326         // canCommit 1st Tx. We don't send the commit so it should
1327         // timeout.
1328
1329         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1330         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1331
1332         // canCommit the 2nd Tx - it should complete after the 1st Tx
1333         // times out.
1334
1335         shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1336         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1337
1338         // Try to commit the 1st Tx - should fail as it's not the
1339         // current Tx.
1340
1341         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1342         testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1343
1344         // Commit the 2nd Tx.
1345
1346         shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1347         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1348
1349         final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1350         assertNotNull(listNodePath + " not found", node);
1351     }
1352
1353 //    @Test
1354 //    @Ignore
1355 //    public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1356 //        dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1357 //
1358 //        new ShardTestKit(getSystem()) {{
1359 //            final TestActorRef<Shard> shard = actorFactory.createTestActor(
1360 //                    newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1361 //                    "testTransactionCommitQueueCapacityExceeded");
1362 //
1363 //            waitUntilLeader(shard);
1364 //
1365 //            final FiniteDuration duration = duration("5 seconds");
1366 //
1367 //            final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1368 //
1369 //            final TransactionIdentifier transactionID1 = nextTransactionId();
1370 //            final MutableCompositeModification modification1 = new MutableCompositeModification();
1371 //            final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1372 //                    TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID1,
1373 //                    modification1);
1374 //
1375 //            final TransactionIdentifier transactionID2 = nextTransactionId();
1376 //            final MutableCompositeModification modification2 = new MutableCompositeModification();
1377 //            final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1378 //                    TestModel.OUTER_LIST_PATH,
1379 //                    ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), transactionID2,
1380 //                    modification2);
1381 //
1382 //            final TransactionIdentifier transactionID3 = nextTransactionId();
1383 //            final MutableCompositeModification modification3 = new MutableCompositeModification();
1384 //            final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1385 //                    TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID3,
1386 //                    modification3);
1387 //
1388 //            // Ready the Tx's
1389 //
1390 //            shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1,
1391 //                    modification1), getRef());
1392 //            expectMsgClass(duration, ReadyTransactionReply.class);
1393 //
1394 //            shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2,
1395 //                    modification2), getRef());
1396 //            expectMsgClass(duration, ReadyTransactionReply.class);
1397 //
1398 //            // The 3rd Tx should exceed queue capacity and fail.
1399 //
1400 //            shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3,
1401 //                    modification3), getRef());
1402 //            expectMsgClass(duration, akka.actor.Status.Failure.class);
1403 //
1404 //            // canCommit 1st Tx.
1405 //
1406 //            shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1407 //            expectMsgClass(duration, CanCommitTransactionReply.class);
1408 //
1409 //            // canCommit the 2nd Tx - it should get queued.
1410 //
1411 //            shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1412 //
1413 //            // canCommit the 3rd Tx - should exceed queue capacity and fail.
1414 //
1415 //            shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1416 //            expectMsgClass(duration, akka.actor.Status.Failure.class);
1417 //        }};
1418 //    }
1419
1420     @Test
1421     public void testTransactionCommitWithPriorExpiredCohortEntries() {
1422         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1423         final ShardTestKit testKit = new ShardTestKit(getSystem());
1424         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1425             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1426             "testTransactionCommitWithPriorExpiredCohortEntries");
1427
1428         ShardTestKit.waitUntilLeader(shard);
1429
1430         final FiniteDuration duration = testKit.duration("5 seconds");
1431
1432         final TransactionIdentifier transactionID1 = nextTransactionId();
1433         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1434             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1435         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1436
1437         final TransactionIdentifier transactionID2 = nextTransactionId();
1438         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1439             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1440         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1441
1442         final TransactionIdentifier transactionID3 = nextTransactionId();
1443         shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1444             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1445         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1446
1447         // All Tx's are readied. We'll send canCommit for the last one
1448         // but not the others. The others
1449         // should expire from the queue and the last one should be
1450         // processed.
1451
1452         shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), testKit.getRef());
1453         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1454     }
1455
1456     @Test
1457     public void testTransactionCommitWithSubsequentExpiredCohortEntry() {
1458         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1459         final ShardTestKit testKit = new ShardTestKit(getSystem());
1460         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1461             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1462             "testTransactionCommitWithSubsequentExpiredCohortEntry");
1463
1464         ShardTestKit.waitUntilLeader(shard);
1465
1466         final FiniteDuration duration = testKit.duration("5 seconds");
1467
1468         final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1469
1470         final TransactionIdentifier transactionID1 = nextTransactionId();
1471         shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1472             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1473         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1474
1475         // CanCommit the first Tx so it's the current in-progress Tx.
1476
1477         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1478         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1479
1480         // Ready the second Tx.
1481
1482         final TransactionIdentifier transactionID2 = nextTransactionId();
1483         shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1484             ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1485         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1486
1487         // Ready the third Tx.
1488
1489         final TransactionIdentifier transactionID3 = nextTransactionId();
1490         final DataTreeModification modification3 = dataStore.newModification();
1491         new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1492             .apply(modification3);
1493         modification3.ready();
1494         final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3,
1495             true, Optional.empty());
1496         shard.tell(readyMessage, testKit.getRef());
1497
1498         // Commit the first Tx. After completing, the second should
1499         // expire from the queue and the third
1500         // Tx committed.
1501
1502         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1503         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1504
1505         // Expect commit reply from the third Tx.
1506
1507         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1508
1509         final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1510         assertNotNull(TestModel.TEST2_PATH + " not found", node);
1511     }
1512
1513     @Test
1514     public void testCanCommitBeforeReadyFailure() {
1515         final ShardTestKit testKit = new ShardTestKit(getSystem());
1516         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1517             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1518             "testCanCommitBeforeReadyFailure");
1519
1520         shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), testKit.getRef());
1521         testKit.expectMsgClass(testKit.duration("5 seconds"), akka.actor.Status.Failure.class);
1522     }
1523
1524     @Test
1525     public void testAbortAfterCanCommit() throws Exception {
1526         final ShardTestKit testKit = new ShardTestKit(getSystem());
1527         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1528             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterCanCommit");
1529
1530         ShardTestKit.waitUntilLeader(shard);
1531
1532         final FiniteDuration duration = testKit.duration("5 seconds");
1533         final Timeout timeout = new Timeout(duration);
1534
1535         // Ready 2 transactions - the first one will be aborted.
1536
1537         final TransactionIdentifier transactionID1 = nextTransactionId();
1538         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1539             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1540         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1541
1542         final TransactionIdentifier transactionID2 = nextTransactionId();
1543         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1544             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1545         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1546
1547         // Send the CanCommitTransaction message for the first Tx.
1548
1549         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1550         CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1551                 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
1552         assertEquals("Can commit", true, canCommitReply.getCanCommit());
1553
1554         // Send the CanCommitTransaction message for the 2nd Tx. This
1555         // should get queued and
1556         // processed after the first Tx completes.
1557
1558         final Future<Object> canCommitFuture = Patterns.ask(shard,
1559             new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1560
1561         // Send the AbortTransaction message for the first Tx. This
1562         // should trigger the 2nd
1563         // Tx to proceed.
1564
1565         shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1566         testKit.expectMsgClass(duration, AbortTransactionReply.class);
1567
1568         // Wait for the 2nd Tx to complete the canCommit phase.
1569
1570         canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture, duration);
1571         assertEquals("Can commit", true, canCommitReply.getCanCommit());
1572     }
1573
1574     @Test
1575     public void testAbortAfterReady() {
1576         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1577         final ShardTestKit testKit = new ShardTestKit(getSystem());
1578         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1579             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1580
1581         ShardTestKit.waitUntilLeader(shard);
1582
1583         final FiniteDuration duration = testKit.duration("5 seconds");
1584
1585         // Ready a tx.
1586
1587         final TransactionIdentifier transactionID1 = nextTransactionId();
1588         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1589             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1590         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1591
1592         // Send the AbortTransaction message.
1593
1594         shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1595         testKit.expectMsgClass(duration, AbortTransactionReply.class);
1596
1597         assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1598
1599         // Now send CanCommitTransaction - should fail.
1600
1601         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1602         final Throwable failure = testKit.expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
1603         assertTrue("Failure type", failure instanceof IllegalStateException);
1604
1605         // Ready and CanCommit another and verify success.
1606
1607         final TransactionIdentifier transactionID2 = nextTransactionId();
1608         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1609             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1610         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1611
1612         shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1613         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1614     }
1615
1616     @Test
1617     public void testAbortQueuedTransaction() {
1618         final ShardTestKit testKit = new ShardTestKit(getSystem());
1619         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1620             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1621
1622         ShardTestKit.waitUntilLeader(shard);
1623
1624         final FiniteDuration duration = testKit.duration("5 seconds");
1625
1626         // Ready 3 tx's.
1627
1628         final TransactionIdentifier transactionID1 = nextTransactionId();
1629         shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1630             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1631         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1632
1633         final TransactionIdentifier transactionID2 = nextTransactionId();
1634         shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1635             ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1636         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1637
1638         final TransactionIdentifier transactionID3 = nextTransactionId();
1639         shard.tell(newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
1640                 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1), testKit.getRef());
1641         testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1642
1643         // Abort the second tx while it's queued.
1644
1645         shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1646         testKit.expectMsgClass(duration, AbortTransactionReply.class);
1647
1648         // Commit the other 2.
1649
1650         shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1651         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1652
1653         shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1654         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1655
1656         shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), testKit.getRef());
1657         testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1658
1659         shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), testKit.getRef());
1660         testKit.expectMsgClass(duration, CommitTransactionReply.class);
1661
1662         assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1663     }
1664
1665     @Test
1666     public void testCreateSnapshotWithNonPersistentData() throws Exception {
1667         testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1668     }
1669
1670     @Test
1671     public void testCreateSnapshot() throws Exception {
1672         testCreateSnapshot(true, "testCreateSnapshot");
1673     }
1674
1675     private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception {
1676         final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1677
1678         final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1679         class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
1680             TestPersistentDataProvider(final DataPersistenceProvider delegate) {
1681                 super(delegate);
1682             }
1683
1684             @Override
1685             public void saveSnapshot(final Object obj) {
1686                 savedSnapshot.set(obj);
1687                 super.saveSnapshot(obj);
1688             }
1689         }
1690
1691         dataStoreContextBuilder.persistent(persistent);
1692
1693         class TestShard extends Shard {
1694
1695             protected TestShard(final AbstractBuilder<?, ?> builder) {
1696                 super(builder);
1697                 setPersistence(new TestPersistentDataProvider(super.persistence()));
1698             }
1699
1700             @Override
1701             public void handleCommand(final Object message) {
1702                 super.handleCommand(message);
1703
1704                 // XXX:  commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
1705                 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
1706                     latch.get().countDown();
1707                 }
1708             }
1709
1710             @Override
1711             public RaftActorContext getRaftActorContext() {
1712                 return super.getRaftActorContext();
1713             }
1714         }
1715
1716         final ShardTestKit testKit = new ShardTestKit(getSystem());
1717
1718         final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
1719
1720         final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1721             .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1722             shardActorName);
1723
1724         ShardTestKit.waitUntilLeader(shard);
1725         writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1726
1727         final NormalizedNode<?, ?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
1728
1729         // Trigger creation of a snapshot by ensuring
1730         final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
1731         raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1732         awaitAndValidateSnapshot(latch, savedSnapshot, expectedRoot);
1733
1734         raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1735         awaitAndValidateSnapshot(latch, savedSnapshot, expectedRoot);
1736     }
1737
1738     private static void awaitAndValidateSnapshot(final AtomicReference<CountDownLatch> latch,
1739             final AtomicReference<Object> savedSnapshot, final NormalizedNode<?, ?> expectedRoot)
1740                     throws InterruptedException {
1741         assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1742
1743         assertTrue("Invalid saved snapshot " + savedSnapshot.get(), savedSnapshot.get() instanceof Snapshot);
1744
1745         verifySnapshot((Snapshot) savedSnapshot.get(), expectedRoot);
1746
1747         latch.set(new CountDownLatch(1));
1748         savedSnapshot.set(null);
1749     }
1750
1751     private static void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?, ?> expectedRoot) {
1752         final NormalizedNode<?, ?> actual = ((ShardSnapshotState)snapshot.getState()).getSnapshot().getRootNode().get();
1753         assertEquals("Root node", expectedRoot, actual);
1754     }
1755
1756     /**
1757      * This test simply verifies that the applySnapShot logic will work.
1758      */
1759     @Test
1760     public void testInMemoryDataTreeRestore() throws DataValidationFailedException {
1761         final DataTree store = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL,
1762             SCHEMA_CONTEXT);
1763
1764         final DataTreeModification putTransaction = store.takeSnapshot().newModification();
1765         putTransaction.write(TestModel.TEST_PATH,
1766             ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1767         commitTransaction(store, putTransaction);
1768
1769
1770         final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
1771
1772         final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
1773
1774         writeTransaction.delete(YangInstanceIdentifier.EMPTY);
1775         writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
1776
1777         commitTransaction(store, writeTransaction);
1778
1779         final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
1780
1781         assertEquals(expected, actual);
1782     }
1783
1784     @Test
1785     public void testRecoveryApplicable() {
1786
1787         final DatastoreContext persistentContext = DatastoreContext.newBuilder()
1788                 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
1789
1790         final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext)
1791                 .schemaContextProvider(() -> SCHEMA_CONTEXT).props();
1792
1793         final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder()
1794                 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
1795
1796         final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext)
1797                 .schemaContextProvider(() -> SCHEMA_CONTEXT).props();
1798
1799         final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
1800
1801         assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
1802
1803         final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
1804
1805         assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
1806     }
1807
1808     @Test
1809     public void testOnDatastoreContext() {
1810         dataStoreContextBuilder.persistent(true);
1811
1812         final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
1813
1814         assertEquals("isRecoveryApplicable", true, shard.underlyingActor().persistence().isRecoveryApplicable());
1815
1816         ShardTestKit.waitUntilLeader(shard);
1817
1818         shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
1819
1820         assertEquals("isRecoveryApplicable", false, shard.underlyingActor().persistence().isRecoveryApplicable());
1821
1822         shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
1823
1824         assertEquals("isRecoveryApplicable", true, shard.underlyingActor().persistence().isRecoveryApplicable());
1825     }
1826
1827     @Test
1828     public void testRegisterRoleChangeListener() {
1829         final ShardTestKit testKit = new ShardTestKit(getSystem());
1830         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1831             newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1832             "testRegisterRoleChangeListener");
1833
1834         ShardTestKit.waitUntilLeader(shard);
1835
1836         final ActorRef listener = getSystem().actorOf(MessageCollectorActor.props());
1837
1838         shard.tell(new RegisterRoleChangeListener(), listener);
1839
1840         MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
1841
1842         ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
1843             ShardLeaderStateChanged.class);
1844         assertEquals("getLocalShardDataTree present", true,
1845             leaderStateChanged.getLocalShardDataTree().isPresent());
1846         assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
1847             leaderStateChanged.getLocalShardDataTree().get());
1848
1849         MessageCollectorActor.clearMessages(listener);
1850
1851         // Force a leader change
1852
1853         shard.tell(new RequestVote(10000, "member2", 50, 50), testKit.getRef());
1854
1855         leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
1856             ShardLeaderStateChanged.class);
1857         assertEquals("getLocalShardDataTree present", false, leaderStateChanged.getLocalShardDataTree().isPresent());
1858     }
1859
1860     @Test
1861     public void testFollowerInitialSyncStatus() {
1862         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1863                 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1864                 "testFollowerInitialSyncStatus");
1865
1866         shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false,
1867                 "member-1-shard-inventory-operational"));
1868
1869         assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1870
1871         shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true,
1872                 "member-1-shard-inventory-operational"));
1873
1874         assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1875     }
1876
1877     @Test
1878     public void testClusteredDataTreeChangeListenerWithDelayedRegistration() throws Exception {
1879         final ShardTestKit testKit = new ShardTestKit(getSystem());
1880         final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistration";
1881         dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
1882             .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
1883
1884         final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
1885         final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
1886             TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
1887
1888         setupInMemorySnapshotStore();
1889
1890         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1891             newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1892             actorFactory.generateActorId(testName + "-shard"));
1893
1894         testKit.waitUntilNoLeader(shard);
1895
1896         shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), testKit.getRef());
1897         final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(testKit.duration("5 seconds"),
1898             RegisterDataTreeNotificationListenerReply.class);
1899         assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
1900
1901         shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
1902             .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
1903
1904         listener.waitForChangeEvents();
1905     }
1906
1907     @Test
1908     public void testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed() throws Exception {
1909         final ShardTestKit testKit = new ShardTestKit(getSystem());
1910         final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed";
1911         dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
1912             .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
1913
1914         final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(0);
1915         final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
1916             TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
1917
1918         setupInMemorySnapshotStore();
1919
1920         final TestActorRef<Shard> shard = actorFactory.createTestActor(
1921             newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1922             actorFactory.generateActorId(testName + "-shard"));
1923
1924         testKit.waitUntilNoLeader(shard);
1925
1926         shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), testKit.getRef());
1927         final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(testKit.duration("5 seconds"),
1928             RegisterDataTreeNotificationListenerReply.class);
1929         assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
1930
1931         final ActorSelection regActor = getSystem().actorSelection(reply.getListenerRegistrationPath());
1932         regActor.tell(CloseDataTreeNotificationListenerRegistration.getInstance(), testKit.getRef());
1933         testKit.expectMsgClass(CloseDataTreeNotificationListenerRegistrationReply.class);
1934
1935         shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
1936             .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
1937
1938         listener.expectNoMoreChanges("Received unexpected change after close");
1939     }
1940
1941     @Test
1942     public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
1943         final ShardTestKit testKit = new ShardTestKit(getSystem());
1944         final String testName = "testClusteredDataTreeChangeListenerRegistration";
1945         final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
1946             MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
1947
1948         final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
1949             MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
1950
1951         final TestActorRef<Shard> followerShard = actorFactory
1952                 .createTestActor(Shard.builder().id(followerShardID)
1953                     .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
1954                     .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
1955                         "akka://test/user/" + leaderShardID.toString()))
1956                     .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
1957                     .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
1958
1959         final TestActorRef<Shard> leaderShard = actorFactory
1960                 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
1961                     .peerAddresses(Collections.singletonMap(followerShardID.toString(),
1962                         "akka://test/user/" + followerShardID.toString()))
1963                     .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
1964                     .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
1965
1966         leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1967         final String leaderPath = ShardTestKit.waitUntilLeader(followerShard);
1968         assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
1969
1970         final YangInstanceIdentifier path = TestModel.TEST_PATH;
1971         final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
1972         final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
1973             actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
1974
1975         followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), testKit.getRef());
1976         final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(testKit.duration("5 seconds"),
1977             RegisterDataTreeNotificationListenerReply.class);
1978         assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
1979
1980         writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1981
1982         listener.waitForChangeEvents();
1983     }
1984
1985     @Test
1986     public void testServerRemoved() {
1987         final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props()
1988                 .withDispatcher(Dispatchers.DefaultDispatcherId()));
1989
1990         final ActorRef shard = parent.underlyingActor().context().actorOf(
1991                 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1992                 "testServerRemoved");
1993
1994         shard.tell(new ServerRemoved("test"), ActorRef.noSender());
1995
1996         MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);
1997     }
1998 }