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