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