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