2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.datastore;
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.Mockito.doReturn;
18 import static org.mockito.Mockito.inOrder;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.reset;
21 import static org.mockito.Mockito.verify;
22 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
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.Function;
35 import com.google.common.base.Stopwatch;
36 import com.google.common.util.concurrent.Futures;
37 import com.google.common.util.concurrent.ListenableFuture;
38 import com.google.common.util.concurrent.Uninterruptibles;
39 import java.io.IOException;
40 import java.util.Collections;
41 import java.util.HashSet;
43 import java.util.concurrent.CountDownLatch;
44 import java.util.concurrent.TimeUnit;
45 import java.util.concurrent.atomic.AtomicBoolean;
46 import java.util.concurrent.atomic.AtomicReference;
47 import org.junit.Test;
48 import org.mockito.InOrder;
49 import org.opendaylight.controller.cluster.DataPersistenceProvider;
50 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
51 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
52 import org.opendaylight.controller.cluster.access.concepts.MemberName;
53 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
54 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
55 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
56 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
57 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
58 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
59 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
60 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
61 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
62 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
63 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
65 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
67 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
68 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
70 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
71 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
72 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
73 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
74 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListenerReply;
76 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
77 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
78 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
79 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
80 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
81 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
82 import org.opendaylight.controller.cluster.datastore.persisted.PreBoronShardDataTreeSnapshot;
83 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
84 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
85 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
86 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
87 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
88 import org.opendaylight.controller.cluster.raft.RaftActorContext;
89 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
90 import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry;
91 import org.opendaylight.controller.cluster.raft.Snapshot;
92 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
93 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
94 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
95 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
96 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
97 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
98 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
99 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
100 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
101 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
102 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
103 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
104 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
105 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
106 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
107 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
108 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
109 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
110 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
111 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
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.ModificationType;
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;
128 public class ShardTest extends AbstractShardTest {
129 private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in InMemorySnapshotStore and journal recovery seq number will start from 1";
132 public void testRegisterChangeListener() throws Exception {
133 new ShardTestKit(getSystem()) {{
134 final TestActorRef<Shard> shard = actorFactory.createTestActor(
135 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterChangeListener");
137 waitUntilLeader(shard);
139 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
141 final MockDataChangeListener listener = new MockDataChangeListener(1);
142 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
143 "testRegisterChangeListener-DataChangeListener");
145 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
146 dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
148 final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
149 RegisterChangeListenerReply.class);
150 final String replyPath = reply.getListenerRegistrationPath().toString();
151 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
152 "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
154 final YangInstanceIdentifier path = TestModel.TEST_PATH;
155 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
157 listener.waitForChangeEvents(path);
161 @SuppressWarnings("serial")
163 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
164 // This test tests the timing window in which a change listener is registered before the
165 // shard becomes the leader. We verify that the listener is registered and notified of the
166 // existing data when the shard becomes the leader.
167 new ShardTestKit(getSystem()) {{
168 // For this test, we want to send the RegisterChangeListener message after the shard
169 // has recovered from persistence and before it becomes the leader. So we subclass
170 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
171 // we know that the shard has been initialized to a follower and has started the
172 // election process. The following 2 CountDownLatches are used to coordinate the
173 // ElectionTimeout with the sending of the RegisterChangeListener message.
174 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
175 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
176 final Creator<Shard> creator = new Creator<Shard>() {
177 boolean firstElectionTimeout = true;
180 public Shard create() throws Exception {
181 // Use a non persistent provider because this test actually invokes persist on the journal
182 // this will cause all other messages to not be queued properly after that.
183 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
184 // it does do a persist)
185 return new Shard(newShardBuilder()) {
187 public void handleCommand(final Object message) {
188 if(message instanceof ElectionTimeout && firstElectionTimeout) {
189 // Got the first ElectionTimeout. We don't forward it to the
190 // base Shard yet until we've sent the RegisterChangeListener
191 // message. So we signal the onFirstElectionTimeout latch to tell
192 // the main thread to send the RegisterChangeListener message and
193 // start a thread to wait on the onChangeListenerRegistered latch,
194 // which the main thread signals after it has sent the message.
195 // After the onChangeListenerRegistered is triggered, we send the
196 // original ElectionTimeout message to proceed with the election.
197 firstElectionTimeout = false;
198 final ActorRef self = getSelf();
202 Uninterruptibles.awaitUninterruptibly(
203 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
204 self.tell(message, self);
208 onFirstElectionTimeout.countDown();
210 super.handleCommand(message);
217 setupInMemorySnapshotStore();
219 final MockDataChangeListener listener = new MockDataChangeListener(1);
220 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
221 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
223 final TestActorRef<Shard> shard = actorFactory.createTestActor(
224 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
225 "testRegisterChangeListenerWhenNotLeaderInitially");
227 final YangInstanceIdentifier path = TestModel.TEST_PATH;
229 // Wait until the shard receives the first ElectionTimeout message.
230 assertEquals("Got first ElectionTimeout", true,
231 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
233 // Now send the RegisterChangeListener and wait for the reply.
234 shard.tell(new RegisterChangeListener(path, dclActor,
235 AsyncDataBroker.DataChangeScope.SUBTREE, false), getRef());
237 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
238 RegisterChangeListenerReply.class);
239 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
241 // Sanity check - verify the shard is not the leader yet.
242 shard.tell(FindLeader.INSTANCE, getRef());
243 final FindLeaderReply findLeadeReply =
244 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
245 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
247 // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
248 // with the election process.
249 onChangeListenerRegistered.countDown();
251 // Wait for the shard to become the leader and notify our listener with the existing
252 // data in the store.
253 listener.waitForChangeEvents(path);
258 public void testRegisterDataTreeChangeListener() throws Exception {
259 new ShardTestKit(getSystem()) {{
260 final TestActorRef<Shard> shard = actorFactory.createTestActor(
261 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterDataTreeChangeListener");
263 waitUntilLeader(shard);
265 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
267 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
268 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
269 "testRegisterDataTreeChangeListener-DataTreeChangeListener");
271 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
273 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
274 RegisterDataTreeChangeListenerReply.class);
275 final String replyPath = reply.getListenerRegistrationPath().toString();
276 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
277 "akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
279 final YangInstanceIdentifier path = TestModel.TEST_PATH;
280 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
282 listener.waitForChangeEvents();
286 @SuppressWarnings("serial")
288 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
289 new ShardTestKit(getSystem()) {{
290 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
291 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
292 final Creator<Shard> creator = new Creator<Shard>() {
293 boolean firstElectionTimeout = true;
296 public Shard create() throws Exception {
297 return new Shard(newShardBuilder()) {
299 public void handleCommand(final Object message) {
300 if(message instanceof ElectionTimeout && firstElectionTimeout) {
301 firstElectionTimeout = false;
302 final ActorRef self = getSelf();
306 Uninterruptibles.awaitUninterruptibly(
307 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
308 self.tell(message, self);
312 onFirstElectionTimeout.countDown();
314 super.handleCommand(message);
321 setupInMemorySnapshotStore();
323 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
324 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
325 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
327 final TestActorRef<Shard> shard = actorFactory.createTestActor(
328 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
329 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
331 final YangInstanceIdentifier path = TestModel.TEST_PATH;
333 assertEquals("Got first ElectionTimeout", true,
334 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
336 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
337 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
338 RegisterDataTreeChangeListenerReply.class);
339 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
341 shard.tell(FindLeader.INSTANCE, getRef());
342 final FindLeaderReply findLeadeReply =
343 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
344 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
347 onChangeListenerRegistered.countDown();
349 // TODO: investigate why we do not receive data chage events
350 listener.waitForChangeEvents();
355 public void testCreateTransaction(){
356 new ShardTestKit(getSystem()) {{
357 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
359 waitUntilLeader(shard);
361 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
363 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
364 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
366 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
367 CreateTransactionReply.class);
369 final String path = reply.getTransactionPath().toString();
370 assertTrue("Unexpected transaction path " + path,
371 path.startsWith("akka://test/user/testCreateTransaction/shard-member-1:ShardTransactionTest@0:"));
376 public void testCreateTransactionOnChain(){
377 new ShardTestKit(getSystem()) {{
378 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
380 waitUntilLeader(shard);
382 shard.tell(new CreateTransaction(nextTransactionId(),TransactionType.READ_ONLY.ordinal(),
383 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
385 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
386 CreateTransactionReply.class);
388 final String path = reply.getTransactionPath().toString();
389 assertTrue("Unexpected transaction path " + path,
390 path.startsWith("akka://test/user/testCreateTransactionOnChain/shard-member-1:ShardTransactionTest@0:"));
395 public void testPeerAddressResolved() throws Exception {
396 new ShardTestKit(getSystem()) {{
397 ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"), "config");
398 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder().
399 peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null)).props().
400 withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
402 final String address = "akka://foobar";
403 shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
405 shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
406 OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
407 assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
412 public void testApplySnapshot() throws Exception {
414 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testApplySnapshot");
416 ShardTestKit.waitUntilLeader(shard);
418 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
419 store.setSchemaContext(SCHEMA_CONTEXT);
421 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
422 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
423 withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
424 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
426 writeToStore(store, TestModel.TEST_PATH, container);
428 final YangInstanceIdentifier root = YangInstanceIdentifier.EMPTY;
429 final NormalizedNode<?,?> expected = readStore(store, root);
431 final Snapshot snapshot = Snapshot.create(new PreBoronShardDataTreeSnapshot(expected).serialize(),
432 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
434 shard.underlyingActor().getRaftActorSnapshotCohort().applySnapshot(snapshot.getState());
436 final NormalizedNode<?,?> actual = readStore(shard, root);
438 assertEquals("Root node", expected, actual);
442 public void testApplyState() throws Exception {
443 final TestActorRef<Shard> shard = actorFactory.createTestActor(
444 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");
446 ShardTestKit.waitUntilLeader(shard);
448 final DataTree source = setupInMemorySnapshotStore();
449 final DataTreeModification writeMod = source.takeSnapshot().newModification();
450 ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
451 writeMod.write(TestModel.TEST_PATH, node);
454 final TransactionIdentifier tx = nextTransactionId();
455 final ApplyState applyState = new ApplyState(null, tx,
456 new ReplicatedLogImplEntry(1, 2, payloadForModification(source, writeMod, tx)));
458 shard.tell(applyState, shard);
460 Stopwatch sw = Stopwatch.createStarted();
461 while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
462 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
464 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
466 assertEquals("Applied state", node, actual);
471 fail("State was not applied");
475 public void testDataTreeCandidateRecovery() throws Exception {
476 // Set up the InMemorySnapshotStore.
477 final DataTree source = setupInMemorySnapshotStore();
479 final DataTreeModification writeMod = source.takeSnapshot().newModification();
480 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
482 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
484 // Set up the InMemoryJournal.
485 InMemoryJournal.addEntry(shardID.toString(), 1, new ReplicatedLogImplEntry(0, 1,
486 payloadForModification(source, writeMod, nextTransactionId())));
488 final int nListEntries = 16;
489 final Set<Integer> listEntryKeys = new HashSet<>();
491 // Add some ModificationPayload entries
492 for (int i = 1; i <= nListEntries; i++) {
493 listEntryKeys.add(Integer.valueOf(i));
495 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
496 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
498 final DataTreeModification mod = source.takeSnapshot().newModification();
499 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
502 InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
503 payloadForModification(source, mod, nextTransactionId())));
506 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
507 new ApplyJournalEntries(nListEntries));
509 testRecovery(listEntryKeys);
513 public void testConcurrentThreePhaseCommits() throws Throwable {
514 new ShardTestKit(getSystem()) {{
515 final TestActorRef<Shard> shard = actorFactory.createTestActor(
516 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
517 "testConcurrentThreePhaseCommits");
519 waitUntilLeader(shard);
521 // Setup 3 simulated transactions with mock cohorts backed by real cohorts.
523 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
525 final TransactionIdentifier transactionID1 = nextTransactionId();
526 final MutableCompositeModification modification1 = new MutableCompositeModification();
527 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
528 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
530 final TransactionIdentifier transactionID2 = nextTransactionId();
531 final MutableCompositeModification modification2 = new MutableCompositeModification();
532 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
533 TestModel.OUTER_LIST_PATH,
534 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
537 final TransactionIdentifier transactionID3 = nextTransactionId();
538 final MutableCompositeModification modification3 = new MutableCompositeModification();
539 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
540 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
541 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
542 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
545 final long timeoutSec = 5;
546 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
547 final Timeout timeout = new Timeout(duration);
549 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
550 final ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
551 expectMsgClass(duration, ReadyTransactionReply.class));
552 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
554 // Send the CanCommitTransaction message for the first Tx.
556 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
557 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
558 expectMsgClass(duration, CanCommitTransactionReply.class));
559 assertEquals("Can commit", true, canCommitReply.getCanCommit());
561 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
562 expectMsgClass(duration, ReadyTransactionReply.class);
564 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
565 expectMsgClass(duration, ReadyTransactionReply.class);
567 // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
568 // processed after the first Tx completes.
570 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
571 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
573 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
574 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
576 // Send the CommitTransaction message for the first Tx. After it completes, it should
577 // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
579 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
580 expectMsgClass(duration, CommitTransactionReply.class);
582 // Wait for the next 2 Tx's to complete.
584 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
585 final CountDownLatch commitLatch = new CountDownLatch(2);
587 class OnFutureComplete extends OnComplete<Object> {
588 private final Class<?> expRespType;
590 OnFutureComplete(final Class<?> expRespType) {
591 this.expRespType = expRespType;
595 public void onComplete(final Throwable error, final Object resp) {
597 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
600 assertEquals("Commit response type", expRespType, resp.getClass());
602 } catch (final Exception e) {
608 void onSuccess(final Object resp) throws Exception {
612 class OnCommitFutureComplete extends OnFutureComplete {
613 OnCommitFutureComplete() {
614 super(CommitTransactionReply.class);
618 public void onComplete(final Throwable error, final Object resp) {
619 super.onComplete(error, resp);
620 commitLatch.countDown();
624 class OnCanCommitFutureComplete extends OnFutureComplete {
625 private final TransactionIdentifier transactionID;
627 OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
628 super(CanCommitTransactionReply.class);
629 this.transactionID = transactionID;
633 void onSuccess(final Object resp) throws Exception {
634 final CanCommitTransactionReply canCommitReply =
635 CanCommitTransactionReply.fromSerializable(resp);
636 assertEquals("Can commit", true, canCommitReply.getCanCommit());
638 final Future<Object> commitFuture = Patterns.ask(shard,
639 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
640 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
644 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
645 getSystem().dispatcher());
647 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
648 getSystem().dispatcher());
650 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
652 if(caughtEx.get() != null) {
653 throw caughtEx.get();
656 assertEquals("Commits complete", true, done);
658 final InOrder inOrder = inOrder(cohort1, cohort2, cohort3);
659 inOrder.verify(cohort1).canCommit();
660 inOrder.verify(cohort1).preCommit();
661 inOrder.verify(cohort1).commit();
662 inOrder.verify(cohort2).canCommit();
663 inOrder.verify(cohort2).preCommit();
664 inOrder.verify(cohort2).commit();
665 inOrder.verify(cohort3).canCommit();
666 inOrder.verify(cohort3).preCommit();
667 inOrder.verify(cohort3).commit();
669 // Verify data in the data store.
671 verifyOuterListEntry(shard, 1);
673 verifyLastApplied(shard, 2);
678 public void testBatchedModificationsWithNoCommitOnReady() throws Throwable {
679 new ShardTestKit(getSystem()) {{
680 final TestActorRef<Shard> shard = actorFactory.createTestActor(
681 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
682 "testBatchedModificationsWithNoCommitOnReady");
684 waitUntilLeader(shard);
686 final TransactionIdentifier transactionID = nextTransactionId();
687 final FiniteDuration duration = duration("5 seconds");
689 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
690 final ShardCommitCoordinator.CohortDecorator cohortDecorator = (txID, actual) -> {
691 if(mockCohort.get() == null) {
692 mockCohort.set(createDelegatingMockCohort("cohort", actual));
695 return mockCohort.get();
698 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
700 // Send a BatchedModifications to start a transaction.
702 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
703 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
704 expectMsgClass(duration, BatchedModificationsReply.class);
706 // Send a couple more BatchedModifications.
708 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
709 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
710 expectMsgClass(duration, BatchedModificationsReply.class);
712 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
713 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
714 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3), getRef());
715 expectMsgClass(duration, ReadyTransactionReply.class);
717 // Send the CanCommitTransaction message.
719 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
720 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
721 expectMsgClass(duration, CanCommitTransactionReply.class));
722 assertEquals("Can commit", true, canCommitReply.getCanCommit());
724 // Send the CanCommitTransaction message.
726 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
727 expectMsgClass(duration, CommitTransactionReply.class);
729 final InOrder inOrder = inOrder(mockCohort.get());
730 inOrder.verify(mockCohort.get()).canCommit();
731 inOrder.verify(mockCohort.get()).preCommit();
732 inOrder.verify(mockCohort.get()).commit();
734 // Verify data in the data store.
736 verifyOuterListEntry(shard, 1);
741 public void testBatchedModificationsWithCommitOnReady() throws Throwable {
742 new ShardTestKit(getSystem()) {{
743 final TestActorRef<Shard> shard = actorFactory.createTestActor(
744 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
745 "testBatchedModificationsWithCommitOnReady");
747 waitUntilLeader(shard);
749 final TransactionIdentifier transactionID = nextTransactionId();
750 final FiniteDuration duration = duration("5 seconds");
752 final AtomicReference<ShardDataTreeCohort> mockCohort = new AtomicReference<>();
753 final ShardCommitCoordinator.CohortDecorator cohortDecorator = (txID, actual) -> {
754 if(mockCohort.get() == null) {
755 mockCohort.set(createDelegatingMockCohort("cohort", actual));
758 return mockCohort.get();
761 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
763 // Send a BatchedModifications to start a transaction.
765 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
766 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
767 expectMsgClass(duration, BatchedModificationsReply.class);
769 // Send a couple more BatchedModifications.
771 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
772 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
773 expectMsgClass(duration, BatchedModificationsReply.class);
775 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
776 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
777 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3), getRef());
779 expectMsgClass(duration, CommitTransactionReply.class);
781 final InOrder inOrder = inOrder(mockCohort.get());
782 inOrder.verify(mockCohort.get()).canCommit();
783 inOrder.verify(mockCohort.get()).preCommit();
784 inOrder.verify(mockCohort.get()).commit();
786 // Verify data in the data store.
788 verifyOuterListEntry(shard, 1);
792 @Test(expected=IllegalStateException.class)
793 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Throwable {
794 new ShardTestKit(getSystem()) {{
795 final TestActorRef<Shard> shard = actorFactory.createTestActor(
796 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
797 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
799 waitUntilLeader(shard);
801 final TransactionIdentifier transactionID = nextTransactionId();
802 final BatchedModifications batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
803 batched.setReady(true);
804 batched.setTotalMessagesSent(2);
806 shard.tell(batched, getRef());
808 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
810 if(failure != null) {
811 throw failure.cause();
817 public void testBatchedModificationsWithOperationFailure() throws Throwable {
818 new ShardTestKit(getSystem()) {{
819 final TestActorRef<Shard> shard = actorFactory.createTestActor(
820 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
821 "testBatchedModificationsWithOperationFailure");
823 waitUntilLeader(shard);
825 // Test merge with invalid data. An exception should occur when the merge is applied. Note that
826 // write will not validate the children for performance reasons.
828 TransactionIdentifier transactionID = nextTransactionId();
830 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
831 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
832 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
834 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
835 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
836 shard.tell(batched, getRef());
837 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
839 Throwable cause = failure.cause();
841 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
842 batched.setReady(true);
843 batched.setTotalMessagesSent(2);
845 shard.tell(batched, getRef());
847 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
848 assertEquals("Failure cause", cause, failure.cause());
853 public void testBatchedModificationsOnTransactionChain() throws Throwable {
854 new ShardTestKit(getSystem()) {{
855 final TestActorRef<Shard> shard = actorFactory.createTestActor(
856 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
857 "testBatchedModificationsOnTransactionChain");
859 waitUntilLeader(shard);
861 final LocalHistoryIdentifier historyId = nextHistoryId();
862 final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
863 final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
865 final FiniteDuration duration = duration("5 seconds");
867 // Send a BatchedModifications to start a chained write transaction and ready it.
869 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
870 final YangInstanceIdentifier path = TestModel.TEST_PATH;
871 shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
872 expectMsgClass(duration, ReadyTransactionReply.class);
874 // Create a read Tx on the same chain.
876 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
877 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
879 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
881 getSystem().actorSelection(createReply.getTransactionPath()).tell(
882 new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
883 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
884 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
886 // Commit the write transaction.
888 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
889 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
890 expectMsgClass(duration, CanCommitTransactionReply.class));
891 assertEquals("Can commit", true, canCommitReply.getCanCommit());
893 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
894 expectMsgClass(duration, CommitTransactionReply.class);
896 // Verify data in the data store.
898 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
899 assertEquals("Stored node", containerNode, actualNode);
904 public void testOnBatchedModificationsWhenNotLeader() {
905 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
906 new ShardTestKit(getSystem()) {{
907 final Creator<Shard> creator = new Creator<Shard>() {
908 private static final long serialVersionUID = 1L;
911 public Shard create() throws Exception {
912 return new Shard(newShardBuilder()) {
914 protected boolean isLeader() {
915 return overrideLeaderCalls.get() ? false : super.isLeader();
919 protected ActorSelection getLeader() {
920 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
927 final TestActorRef<Shard> shard = actorFactory.createTestActor(
928 Props.create(new DelegatingShardCreator(creator)).
929 withDispatcher(Dispatchers.DefaultDispatcherId()), "testOnBatchedModificationsWhenNotLeader");
931 waitUntilLeader(shard);
933 overrideLeaderCalls.set(true);
935 final BatchedModifications batched = new BatchedModifications(nextTransactionId(), DataStoreVersions.CURRENT_VERSION);
937 shard.tell(batched, ActorRef.noSender());
939 expectMsgEquals(batched);
944 public void testTransactionMessagesWithNoLeader() {
945 new ShardTestKit(getSystem()) {{
946 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
947 shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
948 final TestActorRef<Shard> shard = actorFactory.createTestActor(
949 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
950 "testTransactionMessagesWithNoLeader");
952 waitUntilNoLeader(shard);
954 final TransactionIdentifier txId = nextTransactionId();
955 shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
956 Failure failure = expectMsgClass(Failure.class);
957 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
959 shard.tell(prepareForwardedReadyTransaction(mock(ShardDataTreeCohort.class), txId,
960 DataStoreVersions.CURRENT_VERSION, true), getRef());
961 failure = expectMsgClass(Failure.class);
962 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
964 shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
965 failure = expectMsgClass(Failure.class);
966 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
971 public void testReadyWithReadWriteImmediateCommit() throws Exception{
972 testReadyWithImmediateCommit(true);
976 public void testReadyWithWriteOnlyImmediateCommit() throws Exception{
977 testReadyWithImmediateCommit(false);
980 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception{
981 new ShardTestKit(getSystem()) {{
982 final TestActorRef<Shard> shard = actorFactory.createTestActor(
983 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
984 "testReadyWithImmediateCommit-" + readWrite);
986 waitUntilLeader(shard);
988 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
990 final TransactionIdentifier transactionID = nextTransactionId();
991 final MutableCompositeModification modification = new MutableCompositeModification();
992 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
993 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
994 TestModel.TEST_PATH, containerNode, modification);
996 final FiniteDuration duration = duration("5 seconds");
998 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification, true), getRef());
1000 expectMsgClass(duration, CommitTransactionReply.class);
1002 final InOrder inOrder = inOrder(cohort);
1003 inOrder.verify(cohort).canCommit();
1004 inOrder.verify(cohort).preCommit();
1005 inOrder.verify(cohort).commit();
1007 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1008 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1013 public void testReadyLocalTransactionWithImmediateCommit() throws Exception{
1014 new ShardTestKit(getSystem()) {{
1015 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1016 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1017 "testReadyLocalTransactionWithImmediateCommit");
1019 waitUntilLeader(shard);
1021 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1023 final DataTreeModification modification = dataStore.newModification();
1025 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1026 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1027 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1028 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1030 final TransactionIdentifier txId = nextTransactionId();
1031 modification.ready();
1032 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1034 shard.tell(readyMessage, getRef());
1036 expectMsgClass(CommitTransactionReply.class);
1038 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1039 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1044 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception{
1045 new ShardTestKit(getSystem()) {{
1046 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1047 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1048 "testReadyLocalTransactionWithThreePhaseCommit");
1050 waitUntilLeader(shard);
1052 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1054 final DataTreeModification modification = dataStore.newModification();
1056 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1057 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1058 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1059 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1061 final TransactionIdentifier txId = nextTransactionId();
1062 modification.ready();
1063 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1065 shard.tell(readyMessage, getRef());
1067 expectMsgClass(ReadyTransactionReply.class);
1069 // Send the CanCommitTransaction message.
1071 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1072 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1073 expectMsgClass(CanCommitTransactionReply.class));
1074 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1076 // Send the CanCommitTransaction message.
1078 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1079 expectMsgClass(CommitTransactionReply.class);
1081 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1082 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1087 public void testReadWriteCommitWithPersistenceDisabled() throws Throwable {
1088 testCommitWithPersistenceDisabled(true);
1092 public void testWriteOnlyCommitWithPersistenceDisabled() throws Throwable {
1093 testCommitWithPersistenceDisabled(true);
1096 private void testCommitWithPersistenceDisabled(final boolean readWrite) throws Throwable {
1097 dataStoreContextBuilder.persistent(false);
1098 new ShardTestKit(getSystem()) {{
1099 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1100 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1101 "testCommitWithPersistenceDisabled-" + readWrite);
1103 waitUntilLeader(shard);
1105 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1107 // Setup a simulated transactions with a mock cohort.
1109 final TransactionIdentifier transactionID = nextTransactionId();
1110 final MutableCompositeModification modification = new MutableCompositeModification();
1111 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1112 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort", dataStore,
1113 TestModel.TEST_PATH, containerNode, modification);
1115 final FiniteDuration duration = duration("5 seconds");
1117 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1118 expectMsgClass(duration, ReadyTransactionReply.class);
1120 // Send the CanCommitTransaction message.
1122 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1123 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1124 expectMsgClass(duration, CanCommitTransactionReply.class));
1125 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1127 // Send the CanCommitTransaction message.
1129 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1130 expectMsgClass(duration, CommitTransactionReply.class);
1132 final InOrder inOrder = inOrder(cohort);
1133 inOrder.verify(cohort).canCommit();
1134 inOrder.verify(cohort).preCommit();
1135 inOrder.verify(cohort).commit();
1137 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1138 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1143 public void testReadWriteCommitWhenTransactionHasNoModifications() {
1144 testCommitWhenTransactionHasNoModifications(true);
1148 public void testWriteOnlyCommitWhenTransactionHasNoModifications() {
1149 testCommitWhenTransactionHasNoModifications(false);
1152 private void testCommitWhenTransactionHasNoModifications(final boolean readWrite){
1153 // Note that persistence is enabled which would normally result in the entry getting written to the journal
1154 // but here that need not happen
1155 new ShardTestKit(getSystem()) {
1157 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1158 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1159 "testCommitWhenTransactionHasNoModifications-" + readWrite);
1161 waitUntilLeader(shard);
1163 final TransactionIdentifier transactionID = nextTransactionId();
1164 final MutableCompositeModification modification = new MutableCompositeModification();
1165 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1166 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1167 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1168 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1169 doReturn(mockUnmodifiedCandidate("cohort1-candidate")).when(cohort).getCandidate();
1171 final FiniteDuration duration = duration("5 seconds");
1173 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1174 expectMsgClass(duration, ReadyTransactionReply.class);
1176 // Send the CanCommitTransaction message.
1178 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1179 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1180 expectMsgClass(duration, CanCommitTransactionReply.class));
1181 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1183 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1184 expectMsgClass(duration, CommitTransactionReply.class);
1186 final InOrder inOrder = inOrder(cohort);
1187 inOrder.verify(cohort).canCommit();
1188 inOrder.verify(cohort).preCommit();
1189 inOrder.verify(cohort).commit();
1191 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1192 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1194 // Use MBean for verification
1195 // Committed transaction count should increase as usual
1196 assertEquals(1,shardStats.getCommittedTransactionsCount());
1198 // Commit index should not advance because this does not go into the journal
1199 assertEquals(-1, shardStats.getCommitIndex());
1205 public void testReadWriteCommitWhenTransactionHasModifications() {
1206 testCommitWhenTransactionHasModifications(true);
1210 public void testWriteOnlyCommitWhenTransactionHasModifications() {
1211 testCommitWhenTransactionHasModifications(false);
1214 private void testCommitWhenTransactionHasModifications(final boolean readWrite){
1215 new ShardTestKit(getSystem()) {
1217 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1218 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1219 "testCommitWhenTransactionHasModifications-" + readWrite);
1221 waitUntilLeader(shard);
1223 final TransactionIdentifier transactionID = nextTransactionId();
1224 final MutableCompositeModification modification = new MutableCompositeModification();
1225 modification.addModification(new DeleteModification(YangInstanceIdentifier.EMPTY));
1226 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1227 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1228 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
1229 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
1230 doReturn(mockCandidate("cohort1-candidate")).when(cohort).getCandidate();
1232 final FiniteDuration duration = duration("5 seconds");
1234 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1235 expectMsgClass(duration, ReadyTransactionReply.class);
1237 // Send the CanCommitTransaction message.
1239 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1240 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1241 expectMsgClass(duration, CanCommitTransactionReply.class));
1242 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1244 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1245 expectMsgClass(duration, CommitTransactionReply.class);
1247 final InOrder inOrder = inOrder(cohort);
1248 inOrder.verify(cohort).canCommit();
1249 inOrder.verify(cohort).preCommit();
1250 inOrder.verify(cohort).commit();
1252 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1253 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1255 // Use MBean for verification
1256 // Committed transaction count should increase as usual
1257 assertEquals(1, shardStats.getCommittedTransactionsCount());
1259 // Commit index should advance as we do not have an empty modification
1260 assertEquals(0, shardStats.getCommitIndex());
1266 public void testCommitPhaseFailure() throws Throwable {
1267 testCommitPhaseFailure(true);
1268 testCommitPhaseFailure(false);
1271 private void testCommitPhaseFailure(final boolean readWrite) throws Throwable {
1272 new ShardTestKit(getSystem()) {{
1273 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1274 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1275 "testCommitPhaseFailure-" + readWrite);
1277 waitUntilLeader(shard);
1279 // Setup 2 simulated transactions with mock cohorts. The first one fails in the
1282 final TransactionIdentifier transactionID1 = nextTransactionId();
1283 final MutableCompositeModification modification1 = new MutableCompositeModification();
1284 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1285 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1286 doReturn(Futures.immediateFuture(null)).when(cohort1).preCommit();
1287 doReturn(Futures.immediateFailedFuture(new RuntimeException("mock"))).when(cohort1).commit();
1288 doReturn(mockCandidate("cohort1-candidate")).when(cohort1).getCandidate();
1290 final TransactionIdentifier transactionID2 = nextTransactionId();
1291 final MutableCompositeModification modification2 = new MutableCompositeModification();
1292 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1293 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1295 final FiniteDuration duration = duration("5 seconds");
1296 final Timeout timeout = new Timeout(duration);
1298 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1299 expectMsgClass(duration, ReadyTransactionReply.class);
1301 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1302 expectMsgClass(duration, ReadyTransactionReply.class);
1304 // Send the CanCommitTransaction message for the first Tx.
1306 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1307 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1308 expectMsgClass(duration, CanCommitTransactionReply.class));
1309 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1311 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1312 // processed after the first Tx completes.
1314 final Future<Object> canCommitFuture = Patterns.ask(shard,
1315 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1317 // Send the CommitTransaction message for the first Tx. This should send back an error
1318 // and trigger the 2nd Tx to proceed.
1320 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1321 expectMsgClass(duration, akka.actor.Status.Failure.class);
1323 // Wait for the 2nd Tx to complete the canCommit phase.
1325 final CountDownLatch latch = new CountDownLatch(1);
1326 canCommitFuture.onComplete(new OnComplete<Object>() {
1328 public void onComplete(final Throwable t, final Object resp) {
1331 }, getSystem().dispatcher());
1333 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1335 final InOrder inOrder = inOrder(cohort1, cohort2);
1336 inOrder.verify(cohort1).canCommit();
1337 inOrder.verify(cohort1).preCommit();
1338 inOrder.verify(cohort1).commit();
1339 inOrder.verify(cohort2).canCommit();
1344 public void testPreCommitPhaseFailure() throws Throwable {
1345 testPreCommitPhaseFailure(true);
1346 testPreCommitPhaseFailure(false);
1349 private void testPreCommitPhaseFailure(final boolean readWrite) throws Throwable {
1350 new ShardTestKit(getSystem()) {{
1351 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1352 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1353 "testPreCommitPhaseFailure-" + readWrite);
1355 waitUntilLeader(shard);
1357 final TransactionIdentifier transactionID1 = nextTransactionId();
1358 final MutableCompositeModification modification1 = new MutableCompositeModification();
1359 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1360 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1361 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).preCommit();
1363 final TransactionIdentifier transactionID2 = nextTransactionId();
1364 final MutableCompositeModification modification2 = new MutableCompositeModification();
1365 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1366 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1368 final FiniteDuration duration = duration("5 seconds");
1369 final Timeout timeout = new Timeout(duration);
1371 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1372 expectMsgClass(duration, ReadyTransactionReply.class);
1374 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1375 expectMsgClass(duration, ReadyTransactionReply.class);
1377 // Send the CanCommitTransaction message for the first Tx.
1379 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1380 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1381 expectMsgClass(duration, CanCommitTransactionReply.class));
1382 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1384 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1385 // processed after the first Tx completes.
1387 final Future<Object> canCommitFuture = Patterns.ask(shard,
1388 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1390 // Send the CommitTransaction message for the first Tx. This should send back an error
1391 // and trigger the 2nd Tx to proceed.
1393 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1394 expectMsgClass(duration, akka.actor.Status.Failure.class);
1396 // Wait for the 2nd Tx to complete the canCommit phase.
1398 final CountDownLatch latch = new CountDownLatch(1);
1399 canCommitFuture.onComplete(new OnComplete<Object>() {
1401 public void onComplete(final Throwable t, final Object resp) {
1404 }, getSystem().dispatcher());
1406 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1408 final InOrder inOrder = inOrder(cohort1, cohort2);
1409 inOrder.verify(cohort1).canCommit();
1410 inOrder.verify(cohort1).preCommit();
1411 inOrder.verify(cohort2).canCommit();
1416 public void testCanCommitPhaseFailure() throws Throwable {
1417 testCanCommitPhaseFailure(true);
1418 testCanCommitPhaseFailure(false);
1421 private void testCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1422 new ShardTestKit(getSystem()) {{
1423 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1424 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1425 "testCanCommitPhaseFailure-" + readWrite);
1427 waitUntilLeader(shard);
1429 final FiniteDuration duration = duration("5 seconds");
1431 final TransactionIdentifier transactionID1 = nextTransactionId();
1432 final MutableCompositeModification modification = new MutableCompositeModification();
1433 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1434 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1436 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1437 expectMsgClass(duration, ReadyTransactionReply.class);
1439 // Send the CanCommitTransaction message.
1441 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1442 expectMsgClass(duration, akka.actor.Status.Failure.class);
1444 // Send another can commit to ensure the failed one got cleaned up.
1448 final TransactionIdentifier transactionID2 = nextTransactionId();
1449 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1451 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1452 expectMsgClass(duration, ReadyTransactionReply.class);
1454 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1455 final CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1456 expectMsgClass(CanCommitTransactionReply.class));
1457 assertEquals("getCanCommit", true, reply.getCanCommit());
1462 public void testCanCommitPhaseFalseResponse() throws Throwable {
1463 testCanCommitPhaseFalseResponse(true);
1464 testCanCommitPhaseFalseResponse(false);
1467 private void testCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1468 new ShardTestKit(getSystem()) {{
1469 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1470 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1471 "testCanCommitPhaseFalseResponse-" + readWrite);
1473 waitUntilLeader(shard);
1475 final FiniteDuration duration = duration("5 seconds");
1477 final TransactionIdentifier transactionID1 = nextTransactionId();
1478 final MutableCompositeModification modification = new MutableCompositeModification();
1479 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1480 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1482 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification), getRef());
1483 expectMsgClass(duration, ReadyTransactionReply.class);
1485 // Send the CanCommitTransaction message.
1487 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1488 CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1489 expectMsgClass(CanCommitTransactionReply.class));
1490 assertEquals("getCanCommit", false, reply.getCanCommit());
1492 // Send another can commit to ensure the failed one got cleaned up.
1496 final TransactionIdentifier transactionID2 = nextTransactionId();
1497 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1499 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification), getRef());
1500 expectMsgClass(duration, ReadyTransactionReply.class);
1502 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1503 reply = CanCommitTransactionReply.fromSerializable(
1504 expectMsgClass(CanCommitTransactionReply.class));
1505 assertEquals("getCanCommit", true, reply.getCanCommit());
1510 public void testImmediateCommitWithCanCommitPhaseFailure() throws Throwable {
1511 testImmediateCommitWithCanCommitPhaseFailure(true);
1512 testImmediateCommitWithCanCommitPhaseFailure(false);
1515 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1516 new ShardTestKit(getSystem()) {{
1517 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1518 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1519 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1521 waitUntilLeader(shard);
1523 final FiniteDuration duration = duration("5 seconds");
1525 final TransactionIdentifier transactionID1 = nextTransactionId();
1526 final MutableCompositeModification modification = new MutableCompositeModification();
1527 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1528 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1530 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification, true), getRef());
1532 expectMsgClass(duration, akka.actor.Status.Failure.class);
1534 // Send another can commit to ensure the failed one got cleaned up.
1538 final TransactionIdentifier transactionID2 = nextTransactionId();
1539 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1540 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1541 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1542 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1543 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1544 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1545 doReturn(candidateRoot).when(candidate).getRootNode();
1546 doReturn(YangInstanceIdentifier.EMPTY).when(candidate).getRootPath();
1547 doReturn(candidate).when(cohort).getCandidate();
1549 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1551 expectMsgClass(duration, CommitTransactionReply.class);
1556 public void testImmediateCommitWithCanCommitPhaseFalseResponse() throws Throwable {
1557 testImmediateCommitWithCanCommitPhaseFalseResponse(true);
1558 testImmediateCommitWithCanCommitPhaseFalseResponse(false);
1561 private void testImmediateCommitWithCanCommitPhaseFalseResponse(final boolean readWrite) throws Throwable {
1562 new ShardTestKit(getSystem()) {{
1563 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1564 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1565 "testImmediateCommitWithCanCommitPhaseFalseResponse-" + readWrite);
1567 waitUntilLeader(shard);
1569 final FiniteDuration duration = duration("5 seconds");
1571 final TransactionIdentifier transactionID1 = nextTransactionId();
1572 final MutableCompositeModification modification = new MutableCompositeModification();
1573 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort1");
1574 doReturn(Futures.immediateFuture(Boolean.FALSE)).when(cohort).canCommit();
1576 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID1, modification, true), getRef());
1578 expectMsgClass(duration, akka.actor.Status.Failure.class);
1580 // Send another can commit to ensure the failed one got cleaned up.
1584 final TransactionIdentifier transactionID2 = nextTransactionId();
1585 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1586 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
1587 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
1588 final DataTreeCandidateTip candidate = mock(DataTreeCandidateTip.class);
1589 final DataTreeCandidateNode candidateRoot = mock(DataTreeCandidateNode.class);
1590 doReturn(ModificationType.UNMODIFIED).when(candidateRoot).getModificationType();
1591 doReturn(candidateRoot).when(candidate).getRootNode();
1592 doReturn(YangInstanceIdentifier.EMPTY).when(candidate).getRootPath();
1593 doReturn(candidate).when(cohort).getCandidate();
1595 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID2, modification, true), getRef());
1597 expectMsgClass(duration, CommitTransactionReply.class);
1602 public void testAbortBeforeFinishCommit() throws Throwable {
1603 testAbortBeforeFinishCommit(true);
1604 testAbortBeforeFinishCommit(false);
1607 private void testAbortBeforeFinishCommit(final boolean readWrite) throws Throwable {
1608 new ShardTestKit(getSystem()) {{
1609 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1610 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1611 "testAbortBeforeFinishCommit-" + readWrite);
1613 waitUntilLeader(shard);
1615 final FiniteDuration duration = duration("5 seconds");
1616 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1618 final TransactionIdentifier transactionID = nextTransactionId();
1619 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit =
1621 final ListenableFuture<Void> preCommitFuture = cohort.preCommit();
1623 // Simulate an AbortTransaction message occurring during replication, after
1624 // persisting and before finishing the commit to the in-memory store.
1625 // We have no followers so due to optimizations in the RaftActor, it does not
1626 // attempt replication and thus we can't send an AbortTransaction message b/c
1627 // it would be processed too late after CommitTransaction completes. So we'll
1628 // simulate an AbortTransaction message occurring during replication by calling
1629 // the shard directly.
1631 shard.underlyingActor().doAbortTransaction(transactionID, null);
1633 return preCommitFuture;
1636 final MutableCompositeModification modification = new MutableCompositeModification();
1637 final ShardDataTreeCohort cohort = setupMockWriteTransaction("cohort1", dataStore,
1638 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME),
1639 modification, preCommit);
1641 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
1642 expectMsgClass(duration, ReadyTransactionReply.class);
1644 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1645 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1646 expectMsgClass(duration, CanCommitTransactionReply.class));
1647 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1649 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1650 expectMsgClass(duration, CommitTransactionReply.class);
1652 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1654 // Since we're simulating an abort occurring during replication and before finish commit,
1655 // the data should still get written to the in-memory store since we've gotten past
1656 // canCommit and preCommit and persisted the data.
1657 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1662 public void testTransactionCommitTimeout() throws Throwable {
1663 testTransactionCommitTimeout(true);
1664 testTransactionCommitTimeout(false);
1667 private void testTransactionCommitTimeout(final boolean readWrite) throws Throwable {
1668 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1670 new ShardTestKit(getSystem()) {{
1671 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1672 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1673 "testTransactionCommitTimeout-" + readWrite);
1675 waitUntilLeader(shard);
1677 final FiniteDuration duration = duration("5 seconds");
1679 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1681 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1682 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1683 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1685 // Create 1st Tx - will timeout
1687 final TransactionIdentifier transactionID1 = nextTransactionId();
1688 final MutableCompositeModification modification1 = new MutableCompositeModification();
1689 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1690 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1691 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1692 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
1697 final TransactionIdentifier transactionID2 = nextTransactionId();
1698 final MutableCompositeModification modification2 = new MutableCompositeModification();
1699 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1700 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1701 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort3", dataStore,
1703 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2),
1708 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1709 expectMsgClass(duration, ReadyTransactionReply.class);
1711 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1712 expectMsgClass(duration, ReadyTransactionReply.class);
1714 // canCommit 1st Tx. We don't send the commit so it should timeout.
1716 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1717 expectMsgClass(duration, CanCommitTransactionReply.class);
1719 // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1721 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1722 expectMsgClass(duration, CanCommitTransactionReply.class);
1724 // Try to commit the 1st Tx - should fail as it's not the current Tx.
1726 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1727 expectMsgClass(duration, akka.actor.Status.Failure.class);
1729 // Commit the 2nd Tx.
1731 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1732 expectMsgClass(duration, CommitTransactionReply.class);
1734 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1735 assertNotNull(listNodePath + " not found", node);
1740 public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1741 dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1743 new ShardTestKit(getSystem()) {{
1744 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1745 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1746 "testTransactionCommitQueueCapacityExceeded");
1748 waitUntilLeader(shard);
1750 final FiniteDuration duration = duration("5 seconds");
1752 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1754 final TransactionIdentifier transactionID1 = nextTransactionId();
1755 final MutableCompositeModification modification1 = new MutableCompositeModification();
1756 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1757 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1759 final TransactionIdentifier transactionID2 = nextTransactionId();
1760 final MutableCompositeModification modification2 = new MutableCompositeModification();
1761 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1762 TestModel.OUTER_LIST_PATH,
1763 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
1766 final TransactionIdentifier transactionID3 = nextTransactionId();
1767 final MutableCompositeModification modification3 = new MutableCompositeModification();
1768 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1769 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification3);
1773 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1774 expectMsgClass(duration, ReadyTransactionReply.class);
1776 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1777 expectMsgClass(duration, ReadyTransactionReply.class);
1779 // The 3rd Tx should exceed queue capacity and fail.
1781 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1782 expectMsgClass(duration, akka.actor.Status.Failure.class);
1784 // canCommit 1st Tx.
1786 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1787 expectMsgClass(duration, CanCommitTransactionReply.class);
1789 // canCommit the 2nd Tx - it should get queued.
1791 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1793 // canCommit the 3rd Tx - should exceed queue capacity and fail.
1795 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1796 expectMsgClass(duration, akka.actor.Status.Failure.class);
1801 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Throwable {
1802 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1804 new ShardTestKit(getSystem()) {{
1805 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1806 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1807 "testTransactionCommitWithPriorExpiredCohortEntries");
1809 waitUntilLeader(shard);
1811 final FiniteDuration duration = duration("5 seconds");
1813 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1815 final TransactionIdentifier transactionID1 = nextTransactionId();
1816 final MutableCompositeModification modification1 = new MutableCompositeModification();
1817 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1818 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1820 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1821 expectMsgClass(duration, ReadyTransactionReply.class);
1823 final TransactionIdentifier transactionID2 = nextTransactionId();
1824 final MutableCompositeModification modification2 = new MutableCompositeModification();
1825 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1826 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1828 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1829 expectMsgClass(duration, ReadyTransactionReply.class);
1831 final TransactionIdentifier transactionID3 = nextTransactionId();
1832 final MutableCompositeModification modification3 = new MutableCompositeModification();
1833 final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1834 TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME), modification3);
1836 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1837 expectMsgClass(duration, ReadyTransactionReply.class);
1839 // All Tx's are readied. We'll send canCommit for the last one but not the others. The others
1840 // should expire from the queue and the last one should be processed.
1842 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1843 expectMsgClass(duration, CanCommitTransactionReply.class);
1848 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Throwable {
1849 dataStoreContextBuilder.shardCommitQueueExpiryTimeoutInMillis(1300).shardTransactionCommitTimeoutInSeconds(1);
1851 new ShardTestKit(getSystem()) {{
1852 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1853 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1854 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1856 waitUntilLeader(shard);
1858 final FiniteDuration duration = duration("5 seconds");
1860 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1862 final TransactionIdentifier transactionID1 = nextTransactionId();
1863 final MutableCompositeModification modification1 = new MutableCompositeModification();
1864 final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1865 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
1867 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1868 expectMsgClass(duration, ReadyTransactionReply.class);
1870 // CanCommit the first one so it's the current in-progress CohortEntry.
1872 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1873 expectMsgClass(duration, CanCommitTransactionReply.class);
1875 // Ready the second Tx.
1877 final TransactionIdentifier transactionID2 = nextTransactionId();
1878 final MutableCompositeModification modification2 = new MutableCompositeModification();
1879 final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1880 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification2);
1882 shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1883 expectMsgClass(duration, ReadyTransactionReply.class);
1885 // Ready the third Tx.
1887 final TransactionIdentifier transactionID3 = nextTransactionId();
1888 final DataTreeModification modification3 = dataStore.newModification();
1889 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1890 .apply(modification3);
1891 modification3.ready();
1892 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3, true);
1894 shard.tell(readyMessage, getRef());
1896 // Commit the first Tx. After completing, the second should expire from the queue and the third
1899 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1900 expectMsgClass(duration, CommitTransactionReply.class);
1902 // Expect commit reply from the third Tx.
1904 expectMsgClass(duration, CommitTransactionReply.class);
1906 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1907 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1912 public void testCanCommitBeforeReadyFailure() throws Throwable {
1913 new ShardTestKit(getSystem()) {{
1914 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1915 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1916 "testCanCommitBeforeReadyFailure");
1918 shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
1919 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1924 public void testAbortCurrentTransaction() throws Throwable {
1925 testAbortCurrentTransaction(true);
1926 testAbortCurrentTransaction(false);
1929 private void testAbortCurrentTransaction(final boolean readWrite) throws Throwable {
1930 new ShardTestKit(getSystem()) {{
1931 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1932 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1933 "testAbortCurrentTransaction-" + readWrite);
1935 waitUntilLeader(shard);
1937 // Setup 2 simulated transactions with mock cohorts. The first one will be aborted.
1939 final TransactionIdentifier transactionID1 = nextTransactionId();
1940 final MutableCompositeModification modification1 = new MutableCompositeModification();
1941 final ShardDataTreeCohort cohort1 = mock(ShardDataTreeCohort.class, "cohort1");
1942 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1943 doReturn(Futures.immediateFuture(null)).when(cohort1).abort();
1945 final TransactionIdentifier transactionID2 = nextTransactionId();
1946 final MutableCompositeModification modification2 = new MutableCompositeModification();
1947 final ShardDataTreeCohort cohort2 = mock(ShardDataTreeCohort.class, "cohort2");
1948 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1950 final FiniteDuration duration = duration("5 seconds");
1951 final Timeout timeout = new Timeout(duration);
1953 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1954 expectMsgClass(duration, ReadyTransactionReply.class);
1956 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1957 expectMsgClass(duration, ReadyTransactionReply.class);
1959 // Send the CanCommitTransaction message for the first Tx.
1961 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1962 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1963 expectMsgClass(duration, CanCommitTransactionReply.class));
1964 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1966 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1967 // processed after the first Tx completes.
1969 final Future<Object> canCommitFuture = Patterns.ask(shard,
1970 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1972 // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1975 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1976 expectMsgClass(duration, AbortTransactionReply.class);
1978 // Wait for the 2nd Tx to complete the canCommit phase.
1980 Await.ready(canCommitFuture, duration);
1982 final InOrder inOrder = inOrder(cohort1, cohort2);
1983 inOrder.verify(cohort1).canCommit();
1984 inOrder.verify(cohort2).canCommit();
1989 public void testAbortQueuedTransaction() throws Throwable {
1990 testAbortQueuedTransaction(true);
1991 testAbortQueuedTransaction(false);
1994 private void testAbortQueuedTransaction(final boolean readWrite) throws Throwable {
1995 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1996 new ShardTestKit(getSystem()) {{
1997 final AtomicReference<CountDownLatch> cleaupCheckLatch = new AtomicReference<>();
1998 @SuppressWarnings("serial")
1999 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
2001 public void handleCommand(final Object message) {
2002 super.handleCommand(message);
2003 if(TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
2004 if(cleaupCheckLatch.get() != null) {
2005 cleaupCheckLatch.get().countDown();
2011 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2012 Props.create(new DelegatingShardCreator(creator)).withDispatcher(
2013 Dispatchers.DefaultDispatcherId()), "testAbortQueuedTransaction-" + readWrite);
2015 waitUntilLeader(shard);
2017 final TransactionIdentifier transactionID = nextTransactionId();
2018 final MutableCompositeModification modification = new MutableCompositeModification();
2019 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, "cohort");
2020 doReturn(Futures.immediateFuture(null)).when(cohort).abort();
2022 final FiniteDuration duration = duration("5 seconds");
2026 shard.tell(prepareReadyTransactionMessage(readWrite, shard.underlyingActor(), cohort, transactionID, modification), getRef());
2027 expectMsgClass(duration, ReadyTransactionReply.class);
2029 assertEquals("getPendingTxCommitQueueSize", 1, shard.underlyingActor().getPendingTxCommitQueueSize());
2031 // Send the AbortTransaction message.
2033 shard.tell(new AbortTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2034 expectMsgClass(duration, AbortTransactionReply.class);
2036 verify(cohort).abort();
2038 // Verify the tx cohort is removed from queue at the cleanup check interval.
2040 cleaupCheckLatch.set(new CountDownLatch(1));
2041 assertEquals("TX_COMMIT_TIMEOUT_CHECK_MESSAGE received", true,
2042 cleaupCheckLatch.get().await(5, TimeUnit.SECONDS));
2044 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
2046 // Now send CanCommitTransaction - should fail.
2048 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
2050 Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
2051 assertTrue("Failure type", failure instanceof IllegalStateException);
2056 public void testCreateSnapshot() throws Exception {
2057 testCreateSnapshot(true, "testCreateSnapshot");
2061 public void testCreateSnapshotWithNonPersistentData() throws Exception {
2062 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
2065 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
2067 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
2069 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
2070 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
2071 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
2076 public void saveSnapshot(final Object o) {
2077 savedSnapshot.set(o);
2078 super.saveSnapshot(o);
2082 dataStoreContextBuilder.persistent(persistent);
2084 new ShardTestKit(getSystem()) {{
2085 class TestShard extends Shard {
2087 protected TestShard(AbstractBuilder<?, ?> builder) {
2089 setPersistence(new TestPersistentDataProvider(super.persistence()));
2093 public void handleCommand(final Object message) {
2094 super.handleCommand(message);
2096 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
2097 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
2098 latch.get().countDown();
2103 public RaftActorContext getRaftActorContext() {
2104 return super.getRaftActorContext();
2108 final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
2110 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2111 Props.create(new DelegatingShardCreator(creator)).
2112 withDispatcher(Dispatchers.DefaultDispatcherId()), shardActorName);
2114 waitUntilLeader(shard);
2115 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2117 final NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
2119 // Trigger creation of a snapshot by ensuring
2120 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
2121 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2122 awaitAndValidateSnapshot(expectedRoot);
2124 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2125 awaitAndValidateSnapshot(expectedRoot);
2128 private void awaitAndValidateSnapshot(NormalizedNode<?,?> expectedRoot) throws InterruptedException, IOException {
2129 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
2131 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
2132 savedSnapshot.get() instanceof Snapshot);
2134 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
2136 latch.set(new CountDownLatch(1));
2137 savedSnapshot.set(null);
2140 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?,?> expectedRoot) throws IOException {
2141 final NormalizedNode<?, ?> actual = ShardDataTreeSnapshot.deserialize(snapshot.getState()).getRootNode().get();
2142 assertEquals("Root node", expectedRoot, actual);
2147 * This test simply verifies that the applySnapShot logic will work
2148 * @throws ReadFailedException
2149 * @throws DataValidationFailedException
2152 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
2153 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
2154 store.setSchemaContext(SCHEMA_CONTEXT);
2156 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
2157 putTransaction.write(TestModel.TEST_PATH,
2158 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2159 commitTransaction(store, putTransaction);
2162 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
2164 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2166 writeTransaction.delete(YangInstanceIdentifier.EMPTY);
2167 writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
2169 commitTransaction(store, writeTransaction);
2171 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
2173 assertEquals(expected, actual);
2177 public void testRecoveryApplicable(){
2179 final DatastoreContext persistentContext = DatastoreContext.newBuilder().
2180 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2182 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext).
2183 schemaContext(SCHEMA_CONTEXT).props();
2185 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
2186 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2188 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext).
2189 schemaContext(SCHEMA_CONTEXT).props();
2191 new ShardTestKit(getSystem()) {{
2192 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2194 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2196 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2198 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2203 public void testOnDatastoreContext() {
2204 new ShardTestKit(getSystem()) {{
2205 dataStoreContextBuilder.persistent(true);
2207 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
2209 assertEquals("isRecoveryApplicable", true,
2210 shard.underlyingActor().persistence().isRecoveryApplicable());
2212 waitUntilLeader(shard);
2214 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2216 assertEquals("isRecoveryApplicable", false,
2217 shard.underlyingActor().persistence().isRecoveryApplicable());
2219 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2221 assertEquals("isRecoveryApplicable", true,
2222 shard.underlyingActor().persistence().isRecoveryApplicable());
2227 public void testRegisterRoleChangeListener() throws Exception {
2228 new ShardTestKit(getSystem()) {
2230 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2231 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2232 "testRegisterRoleChangeListener");
2234 waitUntilLeader(shard);
2236 final TestActorRef<MessageCollectorActor> listener =
2237 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2239 shard.tell(new RegisterRoleChangeListener(), listener);
2241 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2243 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2244 ShardLeaderStateChanged.class);
2245 assertEquals("getLocalShardDataTree present", true,
2246 leaderStateChanged.getLocalShardDataTree().isPresent());
2247 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2248 leaderStateChanged.getLocalShardDataTree().get());
2250 MessageCollectorActor.clearMessages(listener);
2252 // Force a leader change
2254 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2256 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2257 ShardLeaderStateChanged.class);
2258 assertEquals("getLocalShardDataTree present", false,
2259 leaderStateChanged.getLocalShardDataTree().isPresent());
2265 public void testFollowerInitialSyncStatus() throws Exception {
2266 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2267 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2268 "testFollowerInitialSyncStatus");
2270 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
2272 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2274 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
2276 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2280 public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
2281 new ShardTestKit(getSystem()) {{
2282 String testName = "testClusteredDataChangeListenerDelayedRegistration";
2283 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2284 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2286 final MockDataChangeListener listener = new MockDataChangeListener(1);
2287 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2288 actorFactory.generateActorId(testName + "-DataChangeListener"));
2290 setupInMemorySnapshotStore();
2292 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2293 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2294 actorFactory.generateActorId(testName + "-shard"));
2296 waitUntilNoLeader(shard);
2298 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2300 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2301 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2302 RegisterChangeListenerReply.class);
2303 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2305 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2306 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2308 listener.waitForChangeEvents();
2313 public void testClusteredDataChangeListenerRegistration() throws Exception {
2314 new ShardTestKit(getSystem()) {{
2315 String testName = "testClusteredDataChangeListenerRegistration";
2316 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2317 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2319 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2320 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2322 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2323 Shard.builder().id(followerShardID).
2324 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2325 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2326 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2327 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2329 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2330 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2331 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2332 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2333 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2335 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2336 String leaderPath = waitUntilLeader(followerShard);
2337 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2339 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2340 final MockDataChangeListener listener = new MockDataChangeListener(1);
2341 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2342 actorFactory.generateActorId(testName + "-DataChangeListener"));
2344 followerShard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2345 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2346 RegisterChangeListenerReply.class);
2347 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2349 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2351 listener.waitForChangeEvents();
2356 public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
2357 new ShardTestKit(getSystem()) {{
2358 String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
2359 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2360 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2362 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2363 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2364 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2366 setupInMemorySnapshotStore();
2368 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2369 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2370 actorFactory.generateActorId(testName + "-shard"));
2372 waitUntilNoLeader(shard);
2374 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2376 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2377 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2378 RegisterDataTreeChangeListenerReply.class);
2379 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2381 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2382 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2384 listener.waitForChangeEvents();
2389 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2390 new ShardTestKit(getSystem()) {{
2391 String testName = "testClusteredDataTreeChangeListenerRegistration";
2392 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2393 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2395 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2396 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2398 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2399 Shard.builder().id(followerShardID).
2400 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2401 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2402 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2403 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2405 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2406 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2407 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2408 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2409 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2411 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2412 String leaderPath = waitUntilLeader(followerShard);
2413 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2415 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2416 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2417 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2418 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2420 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2421 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2422 RegisterDataTreeChangeListenerReply.class);
2423 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2425 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2427 listener.waitForChangeEvents();
2432 public void testServerRemoved() throws Exception {
2433 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2435 final ActorRef shard = parent.underlyingActor().context().actorOf(
2436 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2437 "testServerRemoved");
2439 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2441 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);