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

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