BUG 2773 : Transition Shard to Leader state when it has no peers
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / ShardTest.java
1 package org.opendaylight.controller.cluster.datastore;
2
3 import static org.junit.Assert.assertEquals;
4 import static org.junit.Assert.assertFalse;
5 import static org.junit.Assert.assertNotNull;
6 import static org.junit.Assert.assertNull;
7 import static org.junit.Assert.assertTrue;
8 import static org.mockito.Mockito.doReturn;
9 import static org.mockito.Mockito.inOrder;
10 import static org.mockito.Mockito.mock;
11 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.PoisonPill;
15 import akka.actor.Props;
16 import akka.dispatch.Dispatchers;
17 import akka.dispatch.OnComplete;
18 import akka.japi.Creator;
19 import akka.japi.Procedure;
20 import akka.pattern.Patterns;
21 import akka.persistence.SnapshotSelectionCriteria;
22 import akka.testkit.TestActorRef;
23 import akka.util.Timeout;
24 import com.google.common.base.Function;
25 import com.google.common.base.Optional;
26 import com.google.common.util.concurrent.Futures;
27 import com.google.common.util.concurrent.ListenableFuture;
28 import com.google.common.util.concurrent.MoreExecutors;
29 import com.google.common.util.concurrent.Uninterruptibles;
30 import java.io.IOException;
31 import java.util.Collections;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.concurrent.CountDownLatch;
37 import java.util.concurrent.ExecutionException;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.atomic.AtomicBoolean;
40 import java.util.concurrent.atomic.AtomicReference;
41 import org.junit.Test;
42 import org.mockito.InOrder;
43 import org.opendaylight.controller.cluster.DataPersistenceProvider;
44 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
45 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
46 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
47 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
48 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
50 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
51 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
52 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
53 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
54 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
55 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
56 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
57 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
58 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
59 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
60 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
61 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
62 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
63 import org.opendaylight.controller.cluster.datastore.modification.Modification;
64 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
65 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
66 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
67 import org.opendaylight.controller.cluster.datastore.utils.MessageCollectorActor;
68 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
69 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
70 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
71 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
72 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
73 import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry;
74 import org.opendaylight.controller.cluster.raft.Snapshot;
75 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
76 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
77 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
78 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
79 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
80 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
81 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
82 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
83 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
84 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
85 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
86 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
87 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
88 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
89 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
90 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
91 import org.opendaylight.controller.protobuff.messages.cohort3pc.ThreePhaseCommitCohortMessages;
92 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
93 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
94 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
95 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
96 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
97 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
98 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
99 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
100 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
101 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
102 import scala.concurrent.Await;
103 import scala.concurrent.Future;
104 import scala.concurrent.duration.FiniteDuration;
105
106 public class ShardTest extends AbstractShardTest {
107
108     @Test
109     public void testRegisterChangeListener() throws Exception {
110         new ShardTestKit(getSystem()) {{
111             TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
112                     newShardProps(),  "testRegisterChangeListener");
113
114             waitUntilLeader(shard);
115
116             shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
117
118             MockDataChangeListener listener = new MockDataChangeListener(1);
119             ActorRef dclActor = getSystem().actorOf(DataChangeListener.props(listener),
120                     "testRegisterChangeListener-DataChangeListener");
121
122             shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
123                     dclActor, AsyncDataBroker.DataChangeScope.BASE), getRef());
124
125             RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
126                     RegisterChangeListenerReply.class);
127             String replyPath = reply.getListenerRegistrationPath().toString();
128             assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
129                     "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
130
131             YangInstanceIdentifier path = TestModel.TEST_PATH;
132             writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
133
134             listener.waitForChangeEvents(path);
135
136             dclActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
137             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
138         }};
139     }
140
141     @SuppressWarnings("serial")
142     @Test
143     public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
144         // This test tests the timing window in which a change listener is registered before the
145         // shard becomes the leader. We verify that the listener is registered and notified of the
146         // existing data when the shard becomes the leader.
147         new ShardTestKit(getSystem()) {{
148             // For this test, we want to send the RegisterChangeListener message after the shard
149             // has recovered from persistence and before it becomes the leader. So we subclass
150             // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
151             // we know that the shard has been initialized to a follower and has started the
152             // election process. The following 2 CountDownLatches are used to coordinate the
153             // ElectionTimeout with the sending of the RegisterChangeListener message.
154             final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
155             final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
156             Creator<Shard> creator = new Creator<Shard>() {
157                 boolean firstElectionTimeout = true;
158
159                 @Override
160                 public Shard create() throws Exception {
161                     // Use a non persistent provider because this test actually invokes persist on the journal
162                     // this will cause all other messages to not be queued properly after that.
163                     // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
164                     // it does do a persist)
165                     return new Shard(shardID, Collections.<String,String>emptyMap(),
166                             dataStoreContextBuilder.persistent(false).build(), SCHEMA_CONTEXT) {
167                         @Override
168                         public void onReceiveCommand(final Object message) throws Exception {
169                             if(message instanceof ElectionTimeout && firstElectionTimeout) {
170                                 // Got the first ElectionTimeout. We don't forward it to the
171                                 // base Shard yet until we've sent the RegisterChangeListener
172                                 // message. So we signal the onFirstElectionTimeout latch to tell
173                                 // the main thread to send the RegisterChangeListener message and
174                                 // start a thread to wait on the onChangeListenerRegistered latch,
175                                 // which the main thread signals after it has sent the message.
176                                 // After the onChangeListenerRegistered is triggered, we send the
177                                 // original ElectionTimeout message to proceed with the election.
178                                 firstElectionTimeout = false;
179                                 final ActorRef self = getSelf();
180                                 new Thread() {
181                                     @Override
182                                     public void run() {
183                                         Uninterruptibles.awaitUninterruptibly(
184                                                 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
185                                         self.tell(message, self);
186                                     }
187                                 }.start();
188
189                                 onFirstElectionTimeout.countDown();
190                             } else {
191                                 super.onReceiveCommand(message);
192                             }
193                         }
194                     };
195                 }
196             };
197
198             MockDataChangeListener listener = new MockDataChangeListener(1);
199             ActorRef dclActor = getSystem().actorOf(DataChangeListener.props(listener),
200                     "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
201
202             TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
203                     Props.create(new DelegatingShardCreator(creator)),
204                     "testRegisterChangeListenerWhenNotLeaderInitially");
205
206             // Write initial data into the in-memory store.
207             YangInstanceIdentifier path = TestModel.TEST_PATH;
208             writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
209
210             // Wait until the shard receives the first ElectionTimeout message.
211             assertEquals("Got first ElectionTimeout", true,
212                     onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
213
214             // Now send the RegisterChangeListener and wait for the reply.
215             shard.tell(new RegisterChangeListener(path, dclActor,
216                     AsyncDataBroker.DataChangeScope.SUBTREE), getRef());
217
218             RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
219                     RegisterChangeListenerReply.class);
220             assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
221
222             // Sanity check - verify the shard is not the leader yet.
223             shard.tell(new FindLeader(), getRef());
224             FindLeaderReply findLeadeReply =
225                     expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
226             assertNull("Expected the shard not to be the leader", findLeadeReply.getLeaderActor());
227
228             // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
229             // with the election process.
230             onChangeListenerRegistered.countDown();
231
232             // Wait for the shard to become the leader and notify our listener with the existing
233             // data in the store.
234             listener.waitForChangeEvents(path);
235
236             dclActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
237             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
238         }};
239     }
240
241     @Test
242     public void testCreateTransaction(){
243         new ShardTestKit(getSystem()) {{
244             ActorRef shard = getSystem().actorOf(newShardProps(), "testCreateTransaction");
245
246             waitUntilLeader(shard);
247
248             shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
249
250             shard.tell(new CreateTransaction("txn-1",
251                     TransactionProxy.TransactionType.READ_ONLY.ordinal() ).toSerializable(), getRef());
252
253             CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
254                     CreateTransactionReply.class);
255
256             String path = reply.getTransactionActorPath().toString();
257             assertTrue("Unexpected transaction path " + path,
258                     path.contains("akka://test/user/testCreateTransaction/shard-txn-1"));
259
260             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
261         }};
262     }
263
264     @Test
265     public void testCreateTransactionOnChain(){
266         new ShardTestKit(getSystem()) {{
267             final ActorRef shard = getSystem().actorOf(newShardProps(), "testCreateTransactionOnChain");
268
269             waitUntilLeader(shard);
270
271             shard.tell(new CreateTransaction("txn-1",
272                     TransactionProxy.TransactionType.READ_ONLY.ordinal() , "foobar").toSerializable(),
273                     getRef());
274
275             CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
276                     CreateTransactionReply.class);
277
278             String path = reply.getTransactionActorPath().toString();
279             assertTrue("Unexpected transaction path " + path,
280                     path.contains("akka://test/user/testCreateTransactionOnChain/shard-txn-1"));
281
282             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
283         }};
284     }
285
286     @SuppressWarnings("serial")
287     @Test
288     public void testPeerAddressResolved() throws Exception {
289         new ShardTestKit(getSystem()) {{
290             final CountDownLatch recoveryComplete = new CountDownLatch(1);
291             class TestShard extends Shard {
292                 TestShard() {
293                     super(shardID, Collections.<String, String>singletonMap(shardID.toString(), null),
294                             newDatastoreContext(), SCHEMA_CONTEXT);
295                 }
296
297                 Map<String, String> getPeerAddresses() {
298                     return getRaftActorContext().getPeerAddresses();
299                 }
300
301                 @Override
302                 protected void onRecoveryComplete() {
303                     try {
304                         super.onRecoveryComplete();
305                     } finally {
306                         recoveryComplete.countDown();
307                     }
308                 }
309             }
310
311             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
312                     Props.create(new DelegatingShardCreator(new Creator<Shard>() {
313                         @Override
314                         public TestShard create() throws Exception {
315                             return new TestShard();
316                         }
317                     })), "testPeerAddressResolved");
318
319             //waitUntilLeader(shard);
320             assertEquals("Recovery complete", true,
321                     Uninterruptibles.awaitUninterruptibly(recoveryComplete, 5, TimeUnit.SECONDS));
322
323             String address = "akka://foobar";
324             shard.underlyingActor().onReceiveCommand(new PeerAddressResolved(shardID.toString(), address));
325
326             assertEquals("getPeerAddresses", address,
327                     ((TestShard)shard.underlyingActor()).getPeerAddresses().get(shardID.toString()));
328
329             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
330         }};
331     }
332
333     @Test
334     public void testApplySnapshot() throws Exception {
335         TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(),
336                 "testApplySnapshot");
337
338         InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
339         store.onGlobalContextUpdated(SCHEMA_CONTEXT);
340
341         writeToStore(store, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
342
343         YangInstanceIdentifier root = YangInstanceIdentifier.builder().build();
344         NormalizedNode<?,?> expected = readStore(store, root);
345
346         ApplySnapshot applySnapshot = new ApplySnapshot(Snapshot.create(
347                 SerializationUtils.serializeNormalizedNode(expected),
348                 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4));
349
350         shard.underlyingActor().onReceiveCommand(applySnapshot);
351
352         NormalizedNode<?,?> actual = readStore(shard, root);
353
354         assertEquals("Root node", expected, actual);
355
356         shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
357     }
358
359     @Test
360     public void testApplyState() throws Exception {
361
362         TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(), "testApplyState");
363
364         NormalizedNode<?, ?> node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
365
366         ApplyState applyState = new ApplyState(null, "test", new ReplicatedLogImplEntry(1, 2,
367                 newModificationPayload(new WriteModification(TestModel.TEST_PATH, node))));
368
369         shard.underlyingActor().onReceiveCommand(applyState);
370
371         NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
372         assertEquals("Applied state", node, actual);
373
374         shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
375     }
376
377     @Test
378     public void testRecovery() throws Exception {
379
380         // Set up the InMemorySnapshotStore.
381
382         InMemoryDOMDataStore testStore = InMemoryDOMDataStoreFactory.create("Test", null, null);
383         testStore.onGlobalContextUpdated(SCHEMA_CONTEXT);
384
385         writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
386
387         NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.builder().build());
388
389         InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
390                 SerializationUtils.serializeNormalizedNode(root),
391                 Collections.<ReplicatedLogEntry>emptyList(), 0, 1, -1, -1));
392
393         // Set up the InMemoryJournal.
394
395         InMemoryJournal.addEntry(shardID.toString(), 0, new ReplicatedLogImplEntry(0, 1, newModificationPayload(
396                   new WriteModification(TestModel.OUTER_LIST_PATH,
397                           ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build()))));
398
399         int nListEntries = 16;
400         Set<Integer> listEntryKeys = new HashSet<>();
401
402         // Add some ModificationPayload entries
403         for(int i = 1; i <= nListEntries; i++) {
404             listEntryKeys.add(Integer.valueOf(i));
405             YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
406                     .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
407             Modification mod = new MergeModification(path,
408                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
409             InMemoryJournal.addEntry(shardID.toString(), i, new ReplicatedLogImplEntry(i, 1,
410                     newModificationPayload(mod)));
411         }
412
413         InMemoryJournal.addEntry(shardID.toString(), nListEntries + 1,
414                 new ApplyJournalEntries(nListEntries));
415
416         testRecovery(listEntryKeys);
417     }
418
419     private ModificationPayload newModificationPayload(final Modification... mods) throws IOException {
420         MutableCompositeModification compMod = new MutableCompositeModification();
421         for(Modification mod: mods) {
422             compMod.addModification(mod);
423         }
424
425         return new ModificationPayload(compMod);
426     }
427
428     @SuppressWarnings({ "unchecked" })
429     @Test
430     public void testConcurrentThreePhaseCommits() throws Throwable {
431         new ShardTestKit(getSystem()) {{
432             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
433                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
434                     "testConcurrentThreePhaseCommits");
435
436             waitUntilLeader(shard);
437
438             final String transactionID1 = "tx1";
439             final String transactionID2 = "tx2";
440             final String transactionID3 = "tx3";
441
442             final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort1 = new AtomicReference<>();
443             final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort2 = new AtomicReference<>();
444             final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort3 = new AtomicReference<>();
445             ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
446                 @Override
447                 public DOMStoreThreePhaseCommitCohort decorate(String transactionID, DOMStoreThreePhaseCommitCohort actual) {
448                     if(transactionID.equals(transactionID1)) {
449                         mockCohort1.set(createDelegatingMockCohort("cohort1", actual));
450                         return mockCohort1.get();
451                     } else if(transactionID.equals(transactionID2)) {
452                         mockCohort2.set(createDelegatingMockCohort("cohort2", actual));
453                         return mockCohort2.get();
454                     } else {
455                         mockCohort3.set(createDelegatingMockCohort("cohort3", actual));
456                         return mockCohort3.get();
457                     }
458                 }
459             };
460
461             shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
462
463             long timeoutSec = 5;
464             final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
465             final Timeout timeout = new Timeout(duration);
466
467             // Send a BatchedModifications message for the first transaction.
468
469             shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
470                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
471             BatchedModificationsReply batchedReply = expectMsgClass(duration, BatchedModificationsReply.class);
472             assertEquals("getCohortPath", shard.path().toString(), batchedReply.getCohortPath());
473             assertEquals("getNumBatched", 1, batchedReply.getNumBatched());
474
475             // Send the CanCommitTransaction message for the first Tx.
476
477             shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
478             CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
479                     expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
480             assertEquals("Can commit", true, canCommitReply.getCanCommit());
481
482             // Send BatchedModifications for the next 2 Tx's.
483
484             shard.tell(newBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
485                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true), getRef());
486             expectMsgClass(duration, BatchedModificationsReply.class);
487
488             shard.tell(newBatchedModifications(transactionID3, YangInstanceIdentifier.builder(
489                     TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
490                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true), getRef());
491             expectMsgClass(duration, BatchedModificationsReply.class);
492
493             // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
494             // processed after the first Tx completes.
495
496             Future<Object> canCommitFuture1 = Patterns.ask(shard,
497                     new CanCommitTransaction(transactionID2).toSerializable(), timeout);
498
499             Future<Object> canCommitFuture2 = Patterns.ask(shard,
500                     new CanCommitTransaction(transactionID3).toSerializable(), timeout);
501
502             // Send the CommitTransaction message for the first Tx. After it completes, it should
503             // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
504
505             shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
506             expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
507
508             // Wait for the next 2 Tx's to complete.
509
510             final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
511             final CountDownLatch commitLatch = new CountDownLatch(2);
512
513             class OnFutureComplete extends OnComplete<Object> {
514                 private final Class<?> expRespType;
515
516                 OnFutureComplete(final Class<?> expRespType) {
517                     this.expRespType = expRespType;
518                 }
519
520                 @Override
521                 public void onComplete(final Throwable error, final Object resp) {
522                     if(error != null) {
523                         caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
524                     } else {
525                         try {
526                             assertEquals("Commit response type", expRespType, resp.getClass());
527                             onSuccess(resp);
528                         } catch (Exception e) {
529                             caughtEx.set(e);
530                         }
531                     }
532                 }
533
534                 void onSuccess(final Object resp) throws Exception {
535                 }
536             }
537
538             class OnCommitFutureComplete extends OnFutureComplete {
539                 OnCommitFutureComplete() {
540                     super(CommitTransactionReply.SERIALIZABLE_CLASS);
541                 }
542
543                 @Override
544                 public void onComplete(final Throwable error, final Object resp) {
545                     super.onComplete(error, resp);
546                     commitLatch.countDown();
547                 }
548             }
549
550             class OnCanCommitFutureComplete extends OnFutureComplete {
551                 private final String transactionID;
552
553                 OnCanCommitFutureComplete(final String transactionID) {
554                     super(CanCommitTransactionReply.SERIALIZABLE_CLASS);
555                     this.transactionID = transactionID;
556                 }
557
558                 @Override
559                 void onSuccess(final Object resp) throws Exception {
560                     CanCommitTransactionReply canCommitReply =
561                             CanCommitTransactionReply.fromSerializable(resp);
562                     assertEquals("Can commit", true, canCommitReply.getCanCommit());
563
564                     Future<Object> commitFuture = Patterns.ask(shard,
565                             new CommitTransaction(transactionID).toSerializable(), timeout);
566                     commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
567                 }
568             }
569
570             canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
571                     getSystem().dispatcher());
572
573             canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
574                     getSystem().dispatcher());
575
576             boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
577
578             if(caughtEx.get() != null) {
579                 throw caughtEx.get();
580             }
581
582             assertEquals("Commits complete", true, done);
583
584             InOrder inOrder = inOrder(mockCohort1.get(), mockCohort2.get(), mockCohort3.get());
585             inOrder.verify(mockCohort1.get()).canCommit();
586             inOrder.verify(mockCohort1.get()).preCommit();
587             inOrder.verify(mockCohort1.get()).commit();
588             inOrder.verify(mockCohort2.get()).canCommit();
589             inOrder.verify(mockCohort2.get()).preCommit();
590             inOrder.verify(mockCohort2.get()).commit();
591             inOrder.verify(mockCohort3.get()).canCommit();
592             inOrder.verify(mockCohort3.get()).preCommit();
593             inOrder.verify(mockCohort3.get()).commit();
594
595             // Verify data in the data store.
596
597             NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
598             assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
599             assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
600                     outerList.getValue() instanceof Iterable);
601             Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
602             assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
603                        entry instanceof MapEntryNode);
604             MapEntryNode mapEntry = (MapEntryNode)entry;
605             Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
606                     mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
607             assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
608             assertEquals(TestModel.ID_QNAME.getLocalName() + " value", 1, idLeaf.get().getValue());
609
610             verifyLastApplied(shard, 2);
611
612             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
613         }};
614     }
615
616     private BatchedModifications newBatchedModifications(String transactionID, YangInstanceIdentifier path,
617             NormalizedNode<?, ?> data, boolean ready) {
618         return newBatchedModifications(transactionID, null, path, data, ready);
619     }
620
621     private BatchedModifications newBatchedModifications(String transactionID, String transactionChainID,
622             YangInstanceIdentifier path, NormalizedNode<?, ?> data, boolean ready) {
623         BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, transactionChainID);
624         batched.addModification(new WriteModification(path, data));
625         batched.setReady(ready);
626         return batched;
627     }
628
629     @SuppressWarnings("unchecked")
630     @Test
631     public void testMultipleBatchedModifications() throws Throwable {
632         new ShardTestKit(getSystem()) {{
633             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
634                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
635                     "testMultipleBatchedModifications");
636
637             waitUntilLeader(shard);
638
639             final String transactionID = "tx";
640             FiniteDuration duration = duration("5 seconds");
641
642             final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort = new AtomicReference<>();
643             ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
644                 @Override
645                 public DOMStoreThreePhaseCommitCohort decorate(String txID, DOMStoreThreePhaseCommitCohort actual) {
646                     if(mockCohort.get() == null) {
647                         mockCohort.set(createDelegatingMockCohort("cohort", actual));
648                     }
649
650                     return mockCohort.get();
651                 }
652             };
653
654             shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
655
656             // Send a BatchedModifications to start a transaction.
657
658             shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
659                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
660             expectMsgClass(duration, BatchedModificationsReply.class);
661
662             // Send a couple more BatchedModifications.
663
664             shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
665                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
666             expectMsgClass(duration, BatchedModificationsReply.class);
667
668             shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
669                     TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
670                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true), getRef());
671             expectMsgClass(duration, BatchedModificationsReply.class);
672
673             // Send the CanCommitTransaction message.
674
675             shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
676             CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
677                     expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
678             assertEquals("Can commit", true, canCommitReply.getCanCommit());
679
680             // Send the CanCommitTransaction message.
681
682             shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
683             expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
684
685             InOrder inOrder = inOrder(mockCohort.get());
686             inOrder.verify(mockCohort.get()).canCommit();
687             inOrder.verify(mockCohort.get()).preCommit();
688             inOrder.verify(mockCohort.get()).commit();
689
690             // Verify data in the data store.
691
692             NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
693             assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
694             assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
695                     outerList.getValue() instanceof Iterable);
696             Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
697             assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
698                        entry instanceof MapEntryNode);
699             MapEntryNode mapEntry = (MapEntryNode)entry;
700             Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
701                     mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
702             assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
703             assertEquals(TestModel.ID_QNAME.getLocalName() + " value", 1, idLeaf.get().getValue());
704
705             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
706         }};
707     }
708
709     @Test
710     public void testBatchedModificationsOnTransactionChain() throws Throwable {
711         new ShardTestKit(getSystem()) {{
712             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
713                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
714                     "testBatchedModificationsOnTransactionChain");
715
716             waitUntilLeader(shard);
717
718             String transactionChainID = "txChain";
719             String transactionID1 = "tx1";
720             String transactionID2 = "tx2";
721
722             FiniteDuration duration = duration("5 seconds");
723
724             // Send a BatchedModifications to start a chained write transaction and ready it.
725
726             ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
727             YangInstanceIdentifier path = TestModel.TEST_PATH;
728             shard.tell(newBatchedModifications(transactionID1, transactionChainID, path,
729                     containerNode, true), getRef());
730             expectMsgClass(duration, BatchedModificationsReply.class);
731
732             // Create a read Tx on the same chain.
733
734             shard.tell(new CreateTransaction(transactionID2, TransactionProxy.TransactionType.READ_ONLY.ordinal() ,
735                     transactionChainID).toSerializable(), getRef());
736
737             CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
738
739             getSystem().actorSelection(createReply.getTransactionActorPath()).tell(new ReadData(path), getRef());
740             ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
741             assertEquals("Read node", containerNode, readReply.getNormalizedNode());
742
743             // Commit the write transaction.
744
745             shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
746             CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
747                     expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
748             assertEquals("Can commit", true, canCommitReply.getCanCommit());
749
750             shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
751             expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
752
753             // Verify data in the data store.
754
755             NormalizedNode<?, ?> actualNode = readStore(shard, path);
756             assertEquals("Stored node", containerNode, actualNode);
757
758             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
759         }};
760     }
761
762     @Test
763     public void testOnBatchedModificationsWhenNotLeader() {
764         final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
765         new ShardTestKit(getSystem()) {{
766             Creator<Shard> creator = new Creator<Shard>() {
767                 @Override
768                 public Shard create() throws Exception {
769                     return new Shard(shardID, Collections.<String,String>emptyMap(),
770                             newDatastoreContext(), SCHEMA_CONTEXT) {
771                         @Override
772                         protected boolean isLeader() {
773                             return overrideLeaderCalls.get() ? false : super.isLeader();
774                         }
775
776                         @Override
777                         protected ActorSelection getLeader() {
778                             return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
779                                 super.getLeader();
780                         }
781                     };
782                 }
783             };
784
785             TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
786                     Props.create(new DelegatingShardCreator(creator)), "testOnBatchedModificationsWhenNotLeader");
787
788             waitUntilLeader(shard);
789
790             overrideLeaderCalls.set(true);
791
792             BatchedModifications batched = new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, "");
793
794             shard.tell(batched, ActorRef.noSender());
795
796             expectMsgEquals(batched);
797
798             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
799         }};
800     }
801
802     @Test
803     public void testCommitWithPersistenceDisabled() throws Throwable {
804         dataStoreContextBuilder.persistent(false);
805         new ShardTestKit(getSystem()) {{
806             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
807                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
808                     "testCommitWithPersistenceDisabled");
809
810             waitUntilLeader(shard);
811
812             String transactionID = "tx";
813             FiniteDuration duration = duration("5 seconds");
814
815             // Send a BatchedModifications to start a transaction.
816
817             NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
818             shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true), getRef());
819             expectMsgClass(duration, BatchedModificationsReply.class);
820
821             // Send the CanCommitTransaction message.
822
823             shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
824             CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
825                     expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
826             assertEquals("Can commit", true, canCommitReply.getCanCommit());
827
828             // Send the CanCommitTransaction message.
829
830             shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
831             expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
832
833             NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
834             assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
835
836             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
837         }};
838     }
839
840     @Test
841     public void testCommitWhenTransactionHasNoModifications(){
842         // Note that persistence is enabled which would normally result in the entry getting written to the journal
843         // but here that need not happen
844         new ShardTestKit(getSystem()) {
845             {
846                 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
847                         newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
848                         "testCommitWhenTransactionHasNoModifications");
849
850                 waitUntilLeader(shard);
851
852                 String transactionID = "tx1";
853                 MutableCompositeModification modification = new MutableCompositeModification();
854                 DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
855                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
856                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
857                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
858
859                 FiniteDuration duration = duration("5 seconds");
860
861                 // Simulate the ForwardedReadyTransaction messages that would be sent
862                 // by the ShardTransaction.
863
864                 shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION,
865                         cohort, modification, true), getRef());
866                 expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
867
868                 // Send the CanCommitTransaction message.
869
870                 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
871                 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
872                         expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
873                 assertEquals("Can commit", true, canCommitReply.getCanCommit());
874
875                 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
876                 expectMsgClass(duration, ThreePhaseCommitCohortMessages.CommitTransactionReply.class);
877
878                 InOrder inOrder = inOrder(cohort);
879                 inOrder.verify(cohort).canCommit();
880                 inOrder.verify(cohort).preCommit();
881                 inOrder.verify(cohort).commit();
882
883                 // Use MBean for verification
884                 // Committed transaction count should increase as usual
885                 assertEquals(1,shard.underlyingActor().getShardMBean().getCommittedTransactionsCount());
886
887                 // Commit index should not advance because this does not go into the journal
888                 assertEquals(-1, shard.underlyingActor().getShardMBean().getCommitIndex());
889
890                 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
891
892             }
893         };
894     }
895
896     @Test
897     public void testCommitWhenTransactionHasModifications(){
898         new ShardTestKit(getSystem()) {
899             {
900                 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
901                         newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
902                         "testCommitWhenTransactionHasModifications");
903
904                 waitUntilLeader(shard);
905
906                 String transactionID = "tx1";
907                 MutableCompositeModification modification = new MutableCompositeModification();
908                 modification.addModification(new DeleteModification(YangInstanceIdentifier.builder().build()));
909                 DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
910                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
911                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
912                 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
913
914                 FiniteDuration duration = duration("5 seconds");
915
916                 // Simulate the ForwardedReadyTransaction messages that would be sent
917                 // by the ShardTransaction.
918
919                 shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION,
920                         cohort, modification, true), getRef());
921                 expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
922
923                 // Send the CanCommitTransaction message.
924
925                 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
926                 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
927                         expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
928                 assertEquals("Can commit", true, canCommitReply.getCanCommit());
929
930                 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
931                 expectMsgClass(duration, ThreePhaseCommitCohortMessages.CommitTransactionReply.class);
932
933                 InOrder inOrder = inOrder(cohort);
934                 inOrder.verify(cohort).canCommit();
935                 inOrder.verify(cohort).preCommit();
936                 inOrder.verify(cohort).commit();
937
938                 // Use MBean for verification
939                 // Committed transaction count should increase as usual
940                 assertEquals(1, shard.underlyingActor().getShardMBean().getCommittedTransactionsCount());
941
942                 // Commit index should advance as we do not have an empty modification
943                 assertEquals(0, shard.underlyingActor().getShardMBean().getCommitIndex());
944
945                 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
946
947             }
948         };
949     }
950
951     @Test
952     public void testCommitPhaseFailure() throws Throwable {
953         new ShardTestKit(getSystem()) {{
954             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
955                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
956                     "testCommitPhaseFailure");
957
958             waitUntilLeader(shard);
959
960             // Setup 2 mock cohorts. The first one fails in the commit phase.
961
962             final String transactionID1 = "tx1";
963             final DOMStoreThreePhaseCommitCohort cohort1 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
964             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
965             doReturn(Futures.immediateFuture(null)).when(cohort1).preCommit();
966             doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).commit();
967
968             final String transactionID2 = "tx2";
969             final DOMStoreThreePhaseCommitCohort cohort2 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort2");
970             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
971
972             ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
973                 @Override
974                 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
975                         DOMStoreThreePhaseCommitCohort actual) {
976                     return transactionID1.equals(transactionID) ? cohort1 : cohort2;
977                 }
978             };
979
980             shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
981
982             FiniteDuration duration = duration("5 seconds");
983             final Timeout timeout = new Timeout(duration);
984
985             // Send BatchedModifications to start and ready each transaction.
986
987             shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
988                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
989             expectMsgClass(duration, BatchedModificationsReply.class);
990
991             shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
992                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
993             expectMsgClass(duration, BatchedModificationsReply.class);
994
995             // Send the CanCommitTransaction message for the first Tx.
996
997             shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
998             CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
999                     expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1000             assertEquals("Can commit", true, canCommitReply.getCanCommit());
1001
1002             // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1003             // processed after the first Tx completes.
1004
1005             Future<Object> canCommitFuture = Patterns.ask(shard,
1006                     new CanCommitTransaction(transactionID2).toSerializable(), timeout);
1007
1008             // Send the CommitTransaction message for the first Tx. This should send back an error
1009             // and trigger the 2nd Tx to proceed.
1010
1011             shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
1012             expectMsgClass(duration, akka.actor.Status.Failure.class);
1013
1014             // Wait for the 2nd Tx to complete the canCommit phase.
1015
1016             final CountDownLatch latch = new CountDownLatch(1);
1017             canCommitFuture.onComplete(new OnComplete<Object>() {
1018                 @Override
1019                 public void onComplete(final Throwable t, final Object resp) {
1020                     latch.countDown();
1021                 }
1022             }, getSystem().dispatcher());
1023
1024             assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1025
1026             InOrder inOrder = inOrder(cohort1, cohort2);
1027             inOrder.verify(cohort1).canCommit();
1028             inOrder.verify(cohort1).preCommit();
1029             inOrder.verify(cohort1).commit();
1030             inOrder.verify(cohort2).canCommit();
1031
1032             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1033         }};
1034     }
1035
1036     @Test
1037     public void testPreCommitPhaseFailure() throws Throwable {
1038         new ShardTestKit(getSystem()) {{
1039             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1040                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1041                     "testPreCommitPhaseFailure");
1042
1043             waitUntilLeader(shard);
1044
1045             String transactionID = "tx1";
1046             final DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
1047             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1048             doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).preCommit();
1049
1050             ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
1051                 @Override
1052                 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
1053                         DOMStoreThreePhaseCommitCohort actual) {
1054                     return cohort;
1055                 }
1056             };
1057
1058             shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
1059
1060             FiniteDuration duration = duration("5 seconds");
1061
1062             // Send BatchedModifications to start and ready a transaction.
1063
1064             shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
1065                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1066             expectMsgClass(duration, BatchedModificationsReply.class);
1067
1068             // Send the CanCommitTransaction message.
1069
1070             shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1071             CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1072                     expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1073             assertEquals("Can commit", true, canCommitReply.getCanCommit());
1074
1075             // Send the CommitTransaction message. This should send back an error
1076             // for preCommit failure.
1077
1078             shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
1079             expectMsgClass(duration, akka.actor.Status.Failure.class);
1080
1081             InOrder inOrder = inOrder(cohort);
1082             inOrder.verify(cohort).canCommit();
1083             inOrder.verify(cohort).preCommit();
1084
1085             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1086         }};
1087     }
1088
1089     @Test
1090     public void testCanCommitPhaseFailure() throws Throwable {
1091         new ShardTestKit(getSystem()) {{
1092             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1093                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1094                     "testCanCommitPhaseFailure");
1095
1096             waitUntilLeader(shard);
1097
1098             final FiniteDuration duration = duration("5 seconds");
1099
1100             String transactionID = "tx1";
1101             final DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
1102             doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1103
1104             ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
1105                 @Override
1106                 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
1107                         DOMStoreThreePhaseCommitCohort actual) {
1108                     return cohort;
1109                 }
1110             };
1111
1112             shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
1113
1114             // Send BatchedModifications to start and ready a transaction.
1115
1116             shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
1117                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1118             expectMsgClass(duration, BatchedModificationsReply.class);
1119
1120             // Send the CanCommitTransaction message.
1121
1122             shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1123             expectMsgClass(duration, akka.actor.Status.Failure.class);
1124
1125             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1126         }};
1127     }
1128
1129     @Test
1130     public void testAbortBeforeFinishCommit() throws Throwable {
1131         new ShardTestKit(getSystem()) {{
1132             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1133                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1134                     "testAbortBeforeFinishCommit");
1135
1136             waitUntilLeader(shard);
1137
1138             final FiniteDuration duration = duration("5 seconds");
1139             InMemoryDOMDataStore dataStore = shard.underlyingActor().getDataStore();
1140
1141             final String transactionID = "tx1";
1142             Function<DOMStoreThreePhaseCommitCohort,ListenableFuture<Void>> preCommit =
1143                           new Function<DOMStoreThreePhaseCommitCohort,ListenableFuture<Void>>() {
1144                 @Override
1145                 public ListenableFuture<Void> apply(final DOMStoreThreePhaseCommitCohort cohort) {
1146                     ListenableFuture<Void> preCommitFuture = cohort.preCommit();
1147
1148                     // Simulate an AbortTransaction message occurring during replication, after
1149                     // persisting and before finishing the commit to the in-memory store.
1150                     // We have no followers so due to optimizations in the RaftActor, it does not
1151                     // attempt replication and thus we can't send an AbortTransaction message b/c
1152                     // it would be processed too late after CommitTransaction completes. So we'll
1153                     // simulate an AbortTransaction message occurring during replication by calling
1154                     // the shard directly.
1155                     //
1156                     shard.underlyingActor().doAbortTransaction(transactionID, null);
1157
1158                     return preCommitFuture;
1159                 }
1160             };
1161
1162             shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
1163                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1164             expectMsgClass(duration, BatchedModificationsReply.class);
1165
1166             shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1167             CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1168                     expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1169             assertEquals("Can commit", true, canCommitReply.getCanCommit());
1170
1171             shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
1172             expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1173
1174             NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1175
1176             // Since we're simulating an abort occurring during replication and before finish commit,
1177             // the data should still get written to the in-memory store since we've gotten past
1178             // canCommit and preCommit and persisted the data.
1179             assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1180
1181             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1182         }};
1183     }
1184
1185     @Test
1186     public void testTransactionCommitTimeout() throws Throwable {
1187         dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1188
1189         new ShardTestKit(getSystem()) {{
1190             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1191                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1192                     "testTransactionCommitTimeout");
1193
1194             waitUntilLeader(shard);
1195
1196             final FiniteDuration duration = duration("5 seconds");
1197
1198             writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1199             writeToStore(shard, TestModel.OUTER_LIST_PATH,
1200                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1201
1202             // Create and ready the 1st Tx - will timeout
1203
1204             String transactionID1 = "tx1";
1205             shard.tell(newBatchedModifications(transactionID1, YangInstanceIdentifier.builder(
1206                     TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1207                 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true), getRef());
1208             expectMsgClass(duration, BatchedModificationsReply.class);
1209
1210             // Create and ready the 2nd Tx
1211
1212             String transactionID2 = "tx2";
1213             YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1214                     .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1215             shard.tell(newBatchedModifications(transactionID2, listNodePath,
1216                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), true), getRef());
1217             expectMsgClass(duration, BatchedModificationsReply.class);
1218
1219             // canCommit 1st Tx. We don't send the commit so it should timeout.
1220
1221             shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1222             expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1223
1224             // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1225
1226             shard.tell(new CanCommitTransaction(transactionID2).toSerializable(), getRef());
1227             expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1228
1229             // Commit the 2nd Tx.
1230
1231             shard.tell(new CommitTransaction(transactionID2).toSerializable(), getRef());
1232             expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1233
1234             NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1235             assertNotNull(listNodePath + " not found", node);
1236
1237             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1238         }};
1239     }
1240
1241     @Test
1242     public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1243         dataStoreContextBuilder.shardTransactionCommitQueueCapacity(1);
1244
1245         new ShardTestKit(getSystem()) {{
1246             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1247                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1248                     "testTransactionCommitQueueCapacityExceeded");
1249
1250             waitUntilLeader(shard);
1251
1252             final FiniteDuration duration = duration("5 seconds");
1253
1254             String transactionID1 = "tx1";
1255             String transactionID2 = "tx2";
1256             String transactionID3 = "tx3";
1257
1258             // Send a BatchedModifications to start transactions and ready them.
1259
1260             shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1261                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1262             expectMsgClass(duration, BatchedModificationsReply.class);
1263
1264             shard.tell(newBatchedModifications(transactionID2,TestModel.OUTER_LIST_PATH,
1265                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true), getRef());
1266             expectMsgClass(duration, BatchedModificationsReply.class);
1267
1268             shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1269                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1270             expectMsgClass(duration, BatchedModificationsReply.class);
1271
1272             // canCommit 1st Tx.
1273
1274             shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1275             expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1276
1277             // canCommit the 2nd Tx - it should get queued.
1278
1279             shard.tell(new CanCommitTransaction(transactionID2).toSerializable(), getRef());
1280
1281             // canCommit the 3rd Tx - should exceed queue capacity and fail.
1282
1283             shard.tell(new CanCommitTransaction(transactionID3).toSerializable(), getRef());
1284             expectMsgClass(duration, akka.actor.Status.Failure.class);
1285
1286             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1287         }};
1288     }
1289
1290     @Test
1291     public void testCanCommitBeforeReadyFailure() throws Throwable {
1292         new ShardTestKit(getSystem()) {{
1293             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1294                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1295                     "testCanCommitBeforeReadyFailure");
1296
1297             shard.tell(new CanCommitTransaction("tx").toSerializable(), getRef());
1298             expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1299
1300             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1301         }};
1302     }
1303
1304     @Test
1305     public void testAbortTransaction() throws Throwable {
1306         new ShardTestKit(getSystem()) {{
1307             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1308                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1309                     "testAbortTransaction");
1310
1311             waitUntilLeader(shard);
1312
1313             // Setup 2 simulated transactions with mock cohorts. The first one will be aborted.
1314
1315             final String transactionID1 = "tx1";
1316             final DOMStoreThreePhaseCommitCohort cohort1 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
1317             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1318             doReturn(Futures.immediateFuture(null)).when(cohort1).abort();
1319
1320             final String transactionID2 = "tx2";
1321             final DOMStoreThreePhaseCommitCohort cohort2 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort2");
1322             doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1323
1324             FiniteDuration duration = duration("5 seconds");
1325             final Timeout timeout = new Timeout(duration);
1326
1327             ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
1328                 @Override
1329                 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
1330                         DOMStoreThreePhaseCommitCohort actual) {
1331                     return transactionID1.equals(transactionID) ? cohort1 : cohort2;
1332                 }
1333             };
1334
1335             shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
1336
1337             // Send BatchedModifications to start and ready each transaction.
1338
1339             shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1340                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1341             expectMsgClass(duration, BatchedModificationsReply.class);
1342
1343             shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1344                     ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1345             expectMsgClass(duration, BatchedModificationsReply.class);
1346
1347             // Send the CanCommitTransaction message for the first Tx.
1348
1349             shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1350             CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1351                     expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1352             assertEquals("Can commit", true, canCommitReply.getCanCommit());
1353
1354             // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1355             // processed after the first Tx completes.
1356
1357             Future<Object> canCommitFuture = Patterns.ask(shard,
1358                     new CanCommitTransaction(transactionID2).toSerializable(), timeout);
1359
1360             // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1361             // Tx to proceed.
1362
1363             shard.tell(new AbortTransaction(transactionID1).toSerializable(), getRef());
1364             expectMsgClass(duration, AbortTransactionReply.SERIALIZABLE_CLASS);
1365
1366             // Wait for the 2nd Tx to complete the canCommit phase.
1367
1368             Await.ready(canCommitFuture, duration);
1369
1370             InOrder inOrder = inOrder(cohort1, cohort2);
1371             inOrder.verify(cohort1).canCommit();
1372             inOrder.verify(cohort2).canCommit();
1373
1374             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1375         }};
1376     }
1377
1378     @Test
1379     public void testCreateSnapshot() throws Exception {
1380         testCreateSnapshot(true, "testCreateSnapshot");
1381     }
1382
1383     @Test
1384     public void testCreateSnapshotWithNonPersistentData() throws Exception {
1385         testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1386     }
1387
1388     @SuppressWarnings("serial")
1389     public void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
1390
1391         final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1392         class DelegatingPersistentDataProvider implements DataPersistenceProvider {
1393             DataPersistenceProvider delegate;
1394
1395             DelegatingPersistentDataProvider(DataPersistenceProvider delegate) {
1396                 this.delegate = delegate;
1397             }
1398
1399             @Override
1400             public boolean isRecoveryApplicable() {
1401                 return delegate.isRecoveryApplicable();
1402             }
1403
1404             @Override
1405             public <T> void persist(T o, Procedure<T> procedure) {
1406                 delegate.persist(o, procedure);
1407             }
1408
1409             @Override
1410             public void saveSnapshot(Object o) {
1411                 savedSnapshot.set(o);
1412                 delegate.saveSnapshot(o);
1413             }
1414
1415             @Override
1416             public void deleteSnapshots(SnapshotSelectionCriteria criteria) {
1417                 delegate.deleteSnapshots(criteria);
1418             }
1419
1420             @Override
1421             public void deleteMessages(long sequenceNumber) {
1422                 delegate.deleteMessages(sequenceNumber);
1423             }
1424         }
1425
1426         dataStoreContextBuilder.persistent(persistent);
1427
1428         new ShardTestKit(getSystem()) {{
1429             final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1430             Creator<Shard> creator = new Creator<Shard>() {
1431                 @Override
1432                 public Shard create() throws Exception {
1433                     return new Shard(shardID, Collections.<String,String>emptyMap(),
1434                             newDatastoreContext(), SCHEMA_CONTEXT) {
1435
1436                         DelegatingPersistentDataProvider delegating;
1437
1438                         @Override
1439                         protected DataPersistenceProvider persistence() {
1440                             if(delegating == null) {
1441                                 delegating = new DelegatingPersistentDataProvider(super.persistence());
1442                             }
1443
1444                             return delegating;
1445                         }
1446
1447                         @Override
1448                         protected void commitSnapshot(final long sequenceNumber) {
1449                             super.commitSnapshot(sequenceNumber);
1450                             latch.get().countDown();
1451                         }
1452                     };
1453                 }
1454             };
1455
1456             TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1457                     Props.create(new DelegatingShardCreator(creator)), shardActorName);
1458
1459             waitUntilLeader(shard);
1460
1461             writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1462
1463             NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.builder().build());
1464
1465             CaptureSnapshot capture = new CaptureSnapshot(-1, -1, -1, -1, -1, -1);
1466             shard.tell(capture, getRef());
1467
1468             assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1469
1470             assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
1471                     savedSnapshot.get() instanceof Snapshot);
1472
1473             verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
1474
1475             latch.set(new CountDownLatch(1));
1476             savedSnapshot.set(null);
1477
1478             shard.tell(capture, getRef());
1479
1480             assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1481
1482             assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
1483                     savedSnapshot.get() instanceof Snapshot);
1484
1485             verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
1486
1487             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1488         }
1489
1490         private void verifySnapshot(Snapshot snapshot, NormalizedNode<?,?> expectedRoot) {
1491
1492             NormalizedNode<?, ?> actual = SerializationUtils.deserializeNormalizedNode(snapshot.getState());
1493             assertEquals("Root node", expectedRoot, actual);
1494
1495         }};
1496     }
1497
1498     /**
1499      * This test simply verifies that the applySnapShot logic will work
1500      * @throws ReadFailedException
1501      */
1502     @Test
1503     public void testInMemoryDataStoreRestore() throws ReadFailedException {
1504         InMemoryDOMDataStore store = new InMemoryDOMDataStore("test", MoreExecutors.sameThreadExecutor());
1505
1506         store.onGlobalContextUpdated(SCHEMA_CONTEXT);
1507
1508         DOMStoreWriteTransaction putTransaction = store.newWriteOnlyTransaction();
1509         putTransaction.write(TestModel.TEST_PATH,
1510             ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1511         commitTransaction(putTransaction);
1512
1513
1514         NormalizedNode<?, ?> expected = readStore(store);
1515
1516         DOMStoreWriteTransaction writeTransaction = store.newWriteOnlyTransaction();
1517
1518         writeTransaction.delete(YangInstanceIdentifier.builder().build());
1519         writeTransaction.write(YangInstanceIdentifier.builder().build(), expected);
1520
1521         commitTransaction(writeTransaction);
1522
1523         NormalizedNode<?, ?> actual = readStore(store);
1524
1525         assertEquals(expected, actual);
1526     }
1527
1528     @Test
1529     public void testRecoveryApplicable(){
1530
1531         final DatastoreContext persistentContext = DatastoreContext.newBuilder().
1532                 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
1533
1534         final Props persistentProps = Shard.props(shardID, Collections.<String, String>emptyMap(),
1535                 persistentContext, SCHEMA_CONTEXT);
1536
1537         final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
1538                 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
1539
1540         final Props nonPersistentProps = Shard.props(shardID, Collections.<String, String>emptyMap(),
1541                 nonPersistentContext, SCHEMA_CONTEXT);
1542
1543         new ShardTestKit(getSystem()) {{
1544             TestActorRef<Shard> shard1 = TestActorRef.create(getSystem(),
1545                     persistentProps, "testPersistence1");
1546
1547             assertTrue("Recovery Applicable", shard1.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1548
1549             shard1.tell(PoisonPill.getInstance(), ActorRef.noSender());
1550
1551             TestActorRef<Shard> shard2 = TestActorRef.create(getSystem(),
1552                     nonPersistentProps, "testPersistence2");
1553
1554             assertFalse("Recovery Not Applicable", shard2.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1555
1556             shard2.tell(PoisonPill.getInstance(), ActorRef.noSender());
1557
1558         }};
1559
1560     }
1561
1562     @Test
1563     public void testOnDatastoreContext() {
1564         new ShardTestKit(getSystem()) {{
1565             dataStoreContextBuilder.persistent(true);
1566
1567             TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(), "testOnDatastoreContext");
1568
1569             assertEquals("isRecoveryApplicable", true,
1570                     shard.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1571
1572             waitUntilLeader(shard);
1573
1574             shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
1575
1576             assertEquals("isRecoveryApplicable", false,
1577                     shard.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1578
1579             shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
1580
1581             assertEquals("isRecoveryApplicable", true,
1582                     shard.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1583
1584             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1585         }};
1586     }
1587
1588     @Test
1589     public void testRegisterRoleChangeListener() throws Exception {
1590         new ShardTestKit(getSystem()) {
1591             {
1592                 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1593                         newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1594                         "testRegisterRoleChangeListener");
1595
1596                 waitUntilLeader(shard);
1597
1598                 TestActorRef<MessageCollectorActor> listener =
1599                         TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
1600
1601                 shard.tell(new RegisterRoleChangeListener(), listener);
1602
1603                 // TODO: MessageCollectorActor exists as a test util in both the akka-raft and distributed-datastore
1604                 // projects. Need to move it to commons as a regular utility and then we can get rid of this arbitrary
1605                 // sleep.
1606                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1607
1608                 List<Object> allMatching = MessageCollectorActor.getAllMatching(listener, RegisterRoleChangeListenerReply.class);
1609
1610                 assertEquals(1, allMatching.size());
1611             }
1612         };
1613     }
1614
1615     @Test
1616     public void testFollowerInitialSyncStatus() throws Exception {
1617         final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1618                 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1619                 "testFollowerInitialSyncStatus");
1620
1621         shard.underlyingActor().onReceiveCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
1622
1623         assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1624
1625         shard.underlyingActor().onReceiveCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
1626
1627         assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1628
1629         shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1630     }
1631
1632     private void commitTransaction(final DOMStoreWriteTransaction transaction) {
1633         DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
1634         ListenableFuture<Void> future =
1635             commitCohort.preCommit();
1636         try {
1637             future.get();
1638             future = commitCohort.commit();
1639             future.get();
1640         } catch (InterruptedException | ExecutionException e) {
1641         }
1642     }
1643 }