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

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