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

©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.