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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.