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