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