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.Matchers.any;
18 import static org.mockito.Mockito.doThrow;
19 import static org.mockito.Mockito.inOrder;
20 import static org.mockito.Mockito.mock;
21 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
22 import akka.actor.ActorRef;
23 import akka.actor.ActorSelection;
24 import akka.actor.Props;
25 import akka.actor.Status.Failure;
26 import akka.dispatch.Dispatchers;
27 import akka.dispatch.OnComplete;
28 import akka.japi.Creator;
29 import akka.pattern.Patterns;
30 import akka.persistence.SaveSnapshotSuccess;
31 import akka.testkit.TestActorRef;
32 import akka.util.Timeout;
33 import com.google.common.base.Stopwatch;
34 import com.google.common.primitives.UnsignedLong;
35 import com.google.common.util.concurrent.Uninterruptibles;
36 import java.io.IOException;
37 import java.util.Collections;
38 import java.util.HashSet;
41 import java.util.concurrent.CountDownLatch;
42 import java.util.concurrent.TimeUnit;
43 import java.util.concurrent.atomic.AtomicBoolean;
44 import java.util.concurrent.atomic.AtomicReference;
45 import org.junit.Test;
46 import org.mockito.InOrder;
47 import org.opendaylight.controller.cluster.DataPersistenceProvider;
48 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
49 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
50 import org.opendaylight.controller.cluster.access.concepts.MemberName;
51 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
52 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
53 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
54 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
55 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
56 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
57 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
58 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
59 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
61 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
62 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
63 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
65 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
67 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
68 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
70 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
71 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
72 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
73 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
74 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListenerReply;
75 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
76 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
77 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
78 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
79 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
80 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
81 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
82 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
83 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
84 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
85 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
86 import org.opendaylight.controller.cluster.raft.RaftActorContext;
87 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
88 import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry;
89 import org.opendaylight.controller.cluster.raft.Snapshot;
90 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
91 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
92 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
93 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
94 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
95 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
96 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
97 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
98 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
99 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
100 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
101 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
102 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
103 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
104 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
105 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
106 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
107 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
108 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
109 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
110 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
111 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
117 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
118 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
119 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
120 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
121 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
122 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
123 import scala.concurrent.Await;
124 import scala.concurrent.Future;
125 import scala.concurrent.duration.FiniteDuration;
127 public class ShardTest extends AbstractShardTest {
128 private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in InMemorySnapshotStore and journal recovery seq number will start from 1";
131 public void testRegisterChangeListener() throws Exception {
132 new ShardTestKit(getSystem()) {{
133 final TestActorRef<Shard> shard = actorFactory.createTestActor(
134 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterChangeListener");
136 waitUntilLeader(shard);
138 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
140 final MockDataChangeListener listener = new MockDataChangeListener(1);
141 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
142 "testRegisterChangeListener-DataChangeListener");
144 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
145 dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
147 final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
148 RegisterChangeListenerReply.class);
149 final String replyPath = reply.getListenerRegistrationPath().toString();
150 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
151 "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
153 final YangInstanceIdentifier path = TestModel.TEST_PATH;
154 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
156 listener.waitForChangeEvents(path);
160 @SuppressWarnings("serial")
162 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
163 // This test tests the timing window in which a change listener is registered before the
164 // shard becomes the leader. We verify that the listener is registered and notified of the
165 // existing data when the shard becomes the leader.
166 new ShardTestKit(getSystem()) {{
167 // For this test, we want to send the RegisterChangeListener message after the shard
168 // has recovered from persistence and before it becomes the leader. So we subclass
169 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
170 // we know that the shard has been initialized to a follower and has started the
171 // election process. The following 2 CountDownLatches are used to coordinate the
172 // ElectionTimeout with the sending of the RegisterChangeListener message.
173 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
174 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
175 final Creator<Shard> creator = new Creator<Shard>() {
176 boolean firstElectionTimeout = true;
179 public Shard create() throws Exception {
180 // Use a non persistent provider because this test actually invokes persist on the journal
181 // this will cause all other messages to not be queued properly after that.
182 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
183 // it does do a persist)
184 return new Shard(newShardBuilder()) {
186 public void handleCommand(final Object message) {
187 if(message instanceof ElectionTimeout && firstElectionTimeout) {
188 // Got the first ElectionTimeout. We don't forward it to the
189 // base Shard yet until we've sent the RegisterChangeListener
190 // message. So we signal the onFirstElectionTimeout latch to tell
191 // the main thread to send the RegisterChangeListener message and
192 // start a thread to wait on the onChangeListenerRegistered latch,
193 // which the main thread signals after it has sent the message.
194 // After the onChangeListenerRegistered is triggered, we send the
195 // original ElectionTimeout message to proceed with the election.
196 firstElectionTimeout = false;
197 final ActorRef self = getSelf();
201 Uninterruptibles.awaitUninterruptibly(
202 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
203 self.tell(message, self);
207 onFirstElectionTimeout.countDown();
209 super.handleCommand(message);
216 setupInMemorySnapshotStore();
218 final MockDataChangeListener listener = new MockDataChangeListener(1);
219 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
220 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
222 final TestActorRef<Shard> shard = actorFactory.createTestActor(
223 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
224 "testRegisterChangeListenerWhenNotLeaderInitially");
226 final YangInstanceIdentifier path = TestModel.TEST_PATH;
228 // Wait until the shard receives the first ElectionTimeout message.
229 assertEquals("Got first ElectionTimeout", true,
230 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
232 // Now send the RegisterChangeListener and wait for the reply.
233 shard.tell(new RegisterChangeListener(path, dclActor,
234 AsyncDataBroker.DataChangeScope.SUBTREE, false), getRef());
236 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
237 RegisterChangeListenerReply.class);
238 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
240 // Sanity check - verify the shard is not the leader yet.
241 shard.tell(FindLeader.INSTANCE, getRef());
242 final FindLeaderReply findLeadeReply =
243 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
244 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
246 // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
247 // with the election process.
248 onChangeListenerRegistered.countDown();
250 // Wait for the shard to become the leader and notify our listener with the existing
251 // data in the store.
252 listener.waitForChangeEvents(path);
257 public void testRegisterDataTreeChangeListener() throws Exception {
258 new ShardTestKit(getSystem()) {{
259 final TestActorRef<Shard> shard = actorFactory.createTestActor(
260 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterDataTreeChangeListener");
262 waitUntilLeader(shard);
264 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
266 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
267 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
268 "testRegisterDataTreeChangeListener-DataTreeChangeListener");
270 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
272 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
273 RegisterDataTreeChangeListenerReply.class);
274 final String replyPath = reply.getListenerRegistrationPath().toString();
275 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
276 "akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
278 final YangInstanceIdentifier path = TestModel.TEST_PATH;
279 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
281 listener.waitForChangeEvents();
285 @SuppressWarnings("serial")
287 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
288 new ShardTestKit(getSystem()) {{
289 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
290 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
291 final Creator<Shard> creator = new Creator<Shard>() {
292 boolean firstElectionTimeout = true;
295 public Shard create() throws Exception {
296 return new Shard(newShardBuilder()) {
298 public void handleCommand(final Object message) {
299 if(message instanceof ElectionTimeout && firstElectionTimeout) {
300 firstElectionTimeout = false;
301 final ActorRef self = getSelf();
305 Uninterruptibles.awaitUninterruptibly(
306 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
307 self.tell(message, self);
311 onFirstElectionTimeout.countDown();
313 super.handleCommand(message);
320 setupInMemorySnapshotStore();
322 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
323 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
324 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
326 final TestActorRef<Shard> shard = actorFactory.createTestActor(
327 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
328 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
330 final YangInstanceIdentifier path = TestModel.TEST_PATH;
332 assertEquals("Got first ElectionTimeout", true,
333 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
335 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
336 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
337 RegisterDataTreeChangeListenerReply.class);
338 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
340 shard.tell(FindLeader.INSTANCE, getRef());
341 final FindLeaderReply findLeadeReply =
342 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
343 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
346 onChangeListenerRegistered.countDown();
348 // TODO: investigate why we do not receive data chage events
349 listener.waitForChangeEvents();
354 public void testCreateTransaction(){
355 new ShardTestKit(getSystem()) {{
356 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
358 waitUntilLeader(shard);
360 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
362 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
363 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
365 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
366 CreateTransactionReply.class);
368 final String path = reply.getTransactionPath().toString();
369 assertTrue("Unexpected transaction path " + path,
370 path.startsWith("akka://test/user/testCreateTransaction/shard-member-1:ShardTransactionTest@0:"));
375 public void testCreateTransactionOnChain(){
376 new ShardTestKit(getSystem()) {{
377 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
379 waitUntilLeader(shard);
381 shard.tell(new CreateTransaction(nextTransactionId(),TransactionType.READ_ONLY.ordinal(),
382 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
384 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
385 CreateTransactionReply.class);
387 final String path = reply.getTransactionPath().toString();
388 assertTrue("Unexpected transaction path " + path,
389 path.startsWith("akka://test/user/testCreateTransactionOnChain/shard-member-1:ShardTransactionTest@0:"));
394 public void testPeerAddressResolved() throws Exception {
395 new ShardTestKit(getSystem()) {{
396 final ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"), "config");
397 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder().
398 peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null)).props().
399 withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
401 final String address = "akka://foobar";
402 shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
404 shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
405 final OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
406 assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
411 public void testApplySnapshot() throws Exception {
413 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps().
414 withDispatcher(Dispatchers.DefaultDispatcherId()), "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 MetadataShardDataTreeSnapshot(expected).serialize(),
432 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
434 shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
436 final Stopwatch sw = Stopwatch.createStarted();
437 while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
438 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
441 assertEquals("Root node", expected, readStore(shard, root));
443 } catch(final AssertionError e) {
448 fail("Snapshot was not applied");
452 public void testApplyState() throws Exception {
453 final TestActorRef<Shard> shard = actorFactory.createTestActor(
454 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");
456 ShardTestKit.waitUntilLeader(shard);
458 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
459 store.setSchemaContext(SCHEMA_CONTEXT);
460 writeToStore(store, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
462 final NormalizedNode<?, ?> root = readStore(store, YangInstanceIdentifier.EMPTY);
463 final Snapshot snapshot = Snapshot.create(new MetadataShardDataTreeSnapshot(root).serialize(),
464 Collections.<ReplicatedLogEntry> emptyList(), 1, 2, 3, 4);
466 shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
468 final DataTreeModification writeMod = store.takeSnapshot().newModification();
469 final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
470 writeMod.write(TestModel.TEST_PATH, node);
473 final TransactionIdentifier tx = nextTransactionId();
474 final ApplyState applyState = new ApplyState(null, tx,
475 new ReplicatedLogImplEntry(1, 2, payloadForModification(store, writeMod, tx)));
477 shard.tell(applyState, shard);
479 final Stopwatch sw = Stopwatch.createStarted();
480 while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
481 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
483 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
485 assertEquals("Applied state", node, actual);
490 fail("State was not applied");
494 public void testDataTreeCandidateRecovery() throws Exception {
495 // Set up the InMemorySnapshotStore.
496 final DataTree source = setupInMemorySnapshotStore();
498 final DataTreeModification writeMod = source.takeSnapshot().newModification();
499 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
501 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
503 // Set up the InMemoryJournal.
504 InMemoryJournal.addEntry(shardID.toString(), 1, new ReplicatedLogImplEntry(0, 1,
505 payloadForModification(source, writeMod, nextTransactionId())));
507 final int nListEntries = 16;
508 final Set<Integer> listEntryKeys = new HashSet<>();
510 // Add some ModificationPayload entries
511 for (int i = 1; i <= nListEntries; i++) {
512 listEntryKeys.add(Integer.valueOf(i));
514 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
515 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
517 final DataTreeModification mod = source.takeSnapshot().newModification();
518 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
521 InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
522 payloadForModification(source, mod, nextTransactionId())));
525 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
526 new ApplyJournalEntries(nListEntries));
528 testRecovery(listEntryKeys);
532 public void testConcurrentThreePhaseCommits() throws Throwable {
533 new ShardTestKit(getSystem()) {{
534 final TestActorRef<Shard> shard = actorFactory.createTestActor(
535 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
536 "testConcurrentThreePhaseCommits");
538 waitUntilLeader(shard);
540 final TransactionIdentifier transactionID1 = nextTransactionId();
541 final TransactionIdentifier transactionID2 = nextTransactionId();
542 final TransactionIdentifier transactionID3 = nextTransactionId();
544 final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
545 shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
546 final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
547 final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
548 final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
550 final long timeoutSec = 5;
551 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
552 final Timeout timeout = new Timeout(duration);
554 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
555 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
556 final ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
557 expectMsgClass(duration, ReadyTransactionReply.class));
558 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
560 // Send the CanCommitTransaction message for the first Tx.
562 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
563 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
564 expectMsgClass(duration, CanCommitTransactionReply.class));
565 assertEquals("Can commit", true, canCommitReply.getCanCommit());
567 // Ready 2 more Tx's.
569 shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
570 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
571 expectMsgClass(duration, ReadyTransactionReply.class);
573 shard.tell(prepareBatchedModifications(transactionID3, YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
574 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
575 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false), getRef());
576 expectMsgClass(duration, ReadyTransactionReply.class);
578 // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
579 // processed after the first Tx completes.
581 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
582 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
584 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
585 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
587 // Send the CommitTransaction message for the first Tx. After it completes, it should
588 // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
590 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
591 expectMsgClass(duration, CommitTransactionReply.class);
593 // Wait for the next 2 Tx's to complete.
595 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
596 final CountDownLatch commitLatch = new CountDownLatch(2);
598 class OnFutureComplete extends OnComplete<Object> {
599 private final Class<?> expRespType;
601 OnFutureComplete(final Class<?> expRespType) {
602 this.expRespType = expRespType;
606 public void onComplete(final Throwable error, final Object resp) {
608 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
611 assertEquals("Commit response type", expRespType, resp.getClass());
613 } catch (final Exception e) {
619 void onSuccess(final Object resp) throws Exception {
623 class OnCommitFutureComplete extends OnFutureComplete {
624 OnCommitFutureComplete() {
625 super(CommitTransactionReply.class);
629 public void onComplete(final Throwable error, final Object resp) {
630 super.onComplete(error, resp);
631 commitLatch.countDown();
635 class OnCanCommitFutureComplete extends OnFutureComplete {
636 private final TransactionIdentifier transactionID;
638 OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
639 super(CanCommitTransactionReply.class);
640 this.transactionID = transactionID;
644 void onSuccess(final Object resp) throws Exception {
645 final CanCommitTransactionReply canCommitReply =
646 CanCommitTransactionReply.fromSerializable(resp);
647 assertEquals("Can commit", true, canCommitReply.getCanCommit());
649 final Future<Object> commitFuture = Patterns.ask(shard,
650 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
651 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
655 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
656 getSystem().dispatcher());
658 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
659 getSystem().dispatcher());
661 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
663 if(caughtEx.get() != null) {
664 throw caughtEx.get();
667 assertEquals("Commits complete", true, done);
669 final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
670 cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
671 cohort3.getPreCommit(), cohort3.getCommit());
672 inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
673 inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
674 inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
675 inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
676 inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
677 inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
678 inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
679 inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
680 inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
682 // Verify data in the data store.
684 verifyOuterListEntry(shard, 1);
686 verifyLastApplied(shard, 2);
691 public void testBatchedModificationsWithNoCommitOnReady() throws Throwable {
692 new ShardTestKit(getSystem()) {{
693 final TestActorRef<Shard> shard = actorFactory.createTestActor(
694 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
695 "testBatchedModificationsWithNoCommitOnReady");
697 waitUntilLeader(shard);
699 final TransactionIdentifier transactionID = nextTransactionId();
700 final FiniteDuration duration = duration("5 seconds");
702 // Send a BatchedModifications to start a transaction.
704 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
705 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
706 expectMsgClass(duration, BatchedModificationsReply.class);
708 // Send a couple more BatchedModifications.
710 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
711 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
712 expectMsgClass(duration, BatchedModificationsReply.class);
714 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
715 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
716 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3), getRef());
717 expectMsgClass(duration, ReadyTransactionReply.class);
719 // Send the CanCommitTransaction message.
721 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
722 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
723 expectMsgClass(duration, CanCommitTransactionReply.class));
724 assertEquals("Can commit", true, canCommitReply.getCanCommit());
726 // Send the CommitTransaction message.
728 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
729 expectMsgClass(duration, CommitTransactionReply.class);
731 // Verify data in the data store.
733 verifyOuterListEntry(shard, 1);
738 public void testBatchedModificationsWithCommitOnReady() throws Throwable {
739 new ShardTestKit(getSystem()) {{
740 final TestActorRef<Shard> shard = actorFactory.createTestActor(
741 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
742 "testBatchedModificationsWithCommitOnReady");
744 waitUntilLeader(shard);
746 final TransactionIdentifier transactionID = nextTransactionId();
747 final FiniteDuration duration = duration("5 seconds");
749 // Send a BatchedModifications to start a transaction.
751 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
752 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
753 expectMsgClass(duration, BatchedModificationsReply.class);
755 // Send a couple more BatchedModifications.
757 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
758 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
759 expectMsgClass(duration, BatchedModificationsReply.class);
761 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
762 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
763 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3), getRef());
765 expectMsgClass(duration, CommitTransactionReply.class);
767 // Verify data in the data store.
769 verifyOuterListEntry(shard, 1);
773 @Test(expected=IllegalStateException.class)
774 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Throwable {
775 new ShardTestKit(getSystem()) {{
776 final TestActorRef<Shard> shard = actorFactory.createTestActor(
777 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
778 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
780 waitUntilLeader(shard);
782 final TransactionIdentifier transactionID = nextTransactionId();
783 final BatchedModifications batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
784 batched.setReady(true);
785 batched.setTotalMessagesSent(2);
787 shard.tell(batched, getRef());
789 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
791 if(failure != null) {
792 throw failure.cause();
798 public void testBatchedModificationsWithOperationFailure() throws Throwable {
799 new ShardTestKit(getSystem()) {{
800 final TestActorRef<Shard> shard = actorFactory.createTestActor(
801 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
802 "testBatchedModificationsWithOperationFailure");
804 waitUntilLeader(shard);
806 // Test merge with invalid data. An exception should occur when the merge is applied. Note that
807 // write will not validate the children for performance reasons.
809 final TransactionIdentifier transactionID = nextTransactionId();
811 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
812 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
813 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
815 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
816 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
817 shard.tell(batched, getRef());
818 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
820 final Throwable cause = failure.cause();
822 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
823 batched.setReady(true);
824 batched.setTotalMessagesSent(2);
826 shard.tell(batched, getRef());
828 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
829 assertEquals("Failure cause", cause, failure.cause());
834 public void testBatchedModificationsOnTransactionChain() throws Throwable {
835 new ShardTestKit(getSystem()) {{
836 final TestActorRef<Shard> shard = actorFactory.createTestActor(
837 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
838 "testBatchedModificationsOnTransactionChain");
840 waitUntilLeader(shard);
842 final LocalHistoryIdentifier historyId = nextHistoryId();
843 final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
844 final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
846 final FiniteDuration duration = duration("5 seconds");
848 // Send a BatchedModifications to start a chained write transaction and ready it.
850 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
851 final YangInstanceIdentifier path = TestModel.TEST_PATH;
852 shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
853 expectMsgClass(duration, ReadyTransactionReply.class);
855 // Create a read Tx on the same chain.
857 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
858 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
860 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
862 getSystem().actorSelection(createReply.getTransactionPath()).tell(
863 new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
864 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
865 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
867 // Commit the write transaction.
869 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
870 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
871 expectMsgClass(duration, CanCommitTransactionReply.class));
872 assertEquals("Can commit", true, canCommitReply.getCanCommit());
874 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
875 expectMsgClass(duration, CommitTransactionReply.class);
877 // Verify data in the data store.
879 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
880 assertEquals("Stored node", containerNode, actualNode);
885 public void testOnBatchedModificationsWhenNotLeader() {
886 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
887 new ShardTestKit(getSystem()) {{
888 final Creator<Shard> creator = new Creator<Shard>() {
889 private static final long serialVersionUID = 1L;
892 public Shard create() throws Exception {
893 return new Shard(newShardBuilder()) {
895 protected boolean isLeader() {
896 return overrideLeaderCalls.get() ? false : super.isLeader();
900 protected ActorSelection getLeader() {
901 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
908 final TestActorRef<Shard> shard = actorFactory.createTestActor(
909 Props.create(new DelegatingShardCreator(creator)).
910 withDispatcher(Dispatchers.DefaultDispatcherId()), "testOnBatchedModificationsWhenNotLeader");
912 waitUntilLeader(shard);
914 overrideLeaderCalls.set(true);
916 final BatchedModifications batched = new BatchedModifications(nextTransactionId(), DataStoreVersions.CURRENT_VERSION);
918 shard.tell(batched, ActorRef.noSender());
920 expectMsgEquals(batched);
925 public void testTransactionMessagesWithNoLeader() {
926 new ShardTestKit(getSystem()) {{
927 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
928 shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
929 final TestActorRef<Shard> shard = actorFactory.createTestActor(
930 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
931 "testTransactionMessagesWithNoLeader");
933 waitUntilNoLeader(shard);
935 final TransactionIdentifier txId = nextTransactionId();
936 shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
937 Failure failure = expectMsgClass(Failure.class);
938 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
940 shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
941 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
942 failure = expectMsgClass(Failure.class);
943 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
945 shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
946 failure = expectMsgClass(Failure.class);
947 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
952 public void testReadyWithReadWriteImmediateCommit() throws Exception{
953 testReadyWithImmediateCommit(true);
957 public void testReadyWithWriteOnlyImmediateCommit() throws Exception{
958 testReadyWithImmediateCommit(false);
961 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception{
962 new ShardTestKit(getSystem()) {{
963 final TestActorRef<Shard> shard = actorFactory.createTestActor(
964 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
965 "testReadyWithImmediateCommit-" + readWrite);
967 waitUntilLeader(shard);
969 final TransactionIdentifier transactionID = nextTransactionId();
970 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
972 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
973 containerNode, true), getRef());
975 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true), getRef());
978 expectMsgClass(duration("5 seconds"), CommitTransactionReply.class);
980 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
981 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
986 public void testReadyLocalTransactionWithImmediateCommit() throws Exception{
987 new ShardTestKit(getSystem()) {{
988 final TestActorRef<Shard> shard = actorFactory.createTestActor(
989 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
990 "testReadyLocalTransactionWithImmediateCommit");
992 waitUntilLeader(shard);
994 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
996 final DataTreeModification modification = dataStore.newModification();
998 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
999 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1000 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1001 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1003 final TransactionIdentifier txId = nextTransactionId();
1004 modification.ready();
1005 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1007 shard.tell(readyMessage, getRef());
1009 expectMsgClass(CommitTransactionReply.class);
1011 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1012 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1017 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception{
1018 new ShardTestKit(getSystem()) {{
1019 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1020 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1021 "testReadyLocalTransactionWithThreePhaseCommit");
1023 waitUntilLeader(shard);
1025 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1027 final DataTreeModification modification = dataStore.newModification();
1029 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1030 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1031 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1032 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1034 final TransactionIdentifier txId = nextTransactionId();
1035 modification.ready();
1036 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1038 shard.tell(readyMessage, getRef());
1040 expectMsgClass(ReadyTransactionReply.class);
1042 // Send the CanCommitTransaction message.
1044 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1045 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1046 expectMsgClass(CanCommitTransactionReply.class));
1047 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1049 // Send the CanCommitTransaction message.
1051 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1052 expectMsgClass(CommitTransactionReply.class);
1054 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1055 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1060 public void testReadWriteCommitWithPersistenceDisabled() throws Throwable {
1061 dataStoreContextBuilder.persistent(false);
1062 new ShardTestKit(getSystem()) {{
1063 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1064 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1065 "testCommitWithPersistenceDisabled");
1067 waitUntilLeader(shard);
1069 // Setup a simulated transactions with a mock cohort.
1071 final FiniteDuration duration = duration("5 seconds");
1073 final TransactionIdentifier transactionID = nextTransactionId();
1074 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1075 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false), getRef());
1076 expectMsgClass(duration, ReadyTransactionReply.class);
1078 // Send the CanCommitTransaction message.
1080 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1081 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1082 expectMsgClass(duration, CanCommitTransactionReply.class));
1083 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1085 // Send the CanCommitTransaction message.
1087 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1088 expectMsgClass(duration, CommitTransactionReply.class);
1090 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1091 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1096 public void testReadWriteCommitWhenTransactionHasNoModifications() {
1097 testCommitWhenTransactionHasNoModifications(true);
1101 public void testWriteOnlyCommitWhenTransactionHasNoModifications() {
1102 testCommitWhenTransactionHasNoModifications(false);
1105 private void testCommitWhenTransactionHasNoModifications(final boolean readWrite){
1106 // Note that persistence is enabled which would normally result in the entry getting written to the journal
1107 // but here that need not happen
1108 new ShardTestKit(getSystem()) {{
1109 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1110 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1111 "testCommitWhenTransactionHasNoModifications-" + readWrite);
1113 waitUntilLeader(shard);
1115 final TransactionIdentifier transactionID = nextTransactionId();
1117 final FiniteDuration duration = duration("5 seconds");
1120 final ReadWriteShardDataTreeTransaction rwTx = shard.underlyingActor().getDataStore().
1121 newReadWriteTransaction(transactionID);
1122 shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, rwTx, false), getRef());
1124 shard.tell(prepareBatchedModifications(transactionID, new MutableCompositeModification()), getRef());
1127 expectMsgClass(duration, ReadyTransactionReply.class);
1129 // Send the CanCommitTransaction message.
1131 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1132 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1133 expectMsgClass(duration, CanCommitTransactionReply.class));
1134 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1136 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1137 expectMsgClass(duration, CommitTransactionReply.class);
1139 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1140 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1142 // Use MBean for verification
1143 // Committed transaction count should increase as usual
1144 assertEquals(1,shardStats.getCommittedTransactionsCount());
1146 // Commit index should not advance because this does not go into the journal
1147 assertEquals(-1, shardStats.getCommitIndex());
1152 public void testReadWriteCommitWhenTransactionHasModifications() throws Exception {
1153 testCommitWhenTransactionHasModifications(true);
1157 public void testWriteOnlyCommitWhenTransactionHasModifications() throws Exception {
1158 testCommitWhenTransactionHasModifications(false);
1161 private void testCommitWhenTransactionHasModifications(final boolean readWrite) throws Exception {
1162 new ShardTestKit(getSystem()) {{
1163 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1164 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1165 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1166 "testCommitWhenTransactionHasModifications-" + readWrite);
1168 waitUntilLeader(shard);
1170 final FiniteDuration duration = duration("5 seconds");
1171 final TransactionIdentifier transactionID = nextTransactionId();
1174 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1175 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1177 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1178 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1181 expectMsgClass(duration, ReadyTransactionReply.class);
1183 // Send the CanCommitTransaction message.
1185 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1186 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1187 expectMsgClass(duration, CanCommitTransactionReply.class));
1188 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1190 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1191 expectMsgClass(duration, CommitTransactionReply.class);
1193 final InOrder inOrder = inOrder(dataTree);
1194 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1195 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1196 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1198 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1199 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1201 // Use MBean for verification
1202 // Committed transaction count should increase as usual
1203 assertEquals(1, shardStats.getCommittedTransactionsCount());
1205 // Commit index should advance as we do not have an empty modification
1206 assertEquals(0, shardStats.getCommitIndex());
1211 public void testCommitPhaseFailure() throws Throwable {
1212 new ShardTestKit(getSystem()) {{
1213 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1214 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1215 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1216 "testCommitPhaseFailure");
1218 waitUntilLeader(shard);
1220 final FiniteDuration duration = duration("5 seconds");
1221 final Timeout timeout = new Timeout(duration);
1223 // Setup 2 simulated transactions with mock cohorts. The first one fails in the
1226 doThrow(new RuntimeException("mock commit failure")).when(dataTree).commit(any(DataTreeCandidate.class));
1228 final TransactionIdentifier transactionID1 = nextTransactionId();
1229 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1230 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1231 expectMsgClass(duration, ReadyTransactionReply.class);
1233 final TransactionIdentifier transactionID2 = nextTransactionId();
1234 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1235 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1236 expectMsgClass(duration, ReadyTransactionReply.class);
1238 // Send the CanCommitTransaction message for the first Tx.
1240 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1241 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1242 expectMsgClass(duration, CanCommitTransactionReply.class));
1243 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1245 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1246 // processed after the first Tx completes.
1248 final Future<Object> canCommitFuture = Patterns.ask(shard,
1249 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1251 // Send the CommitTransaction message for the first Tx. This should send back an error
1252 // and trigger the 2nd Tx to proceed.
1254 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1255 expectMsgClass(duration, akka.actor.Status.Failure.class);
1257 // Wait for the 2nd Tx to complete the canCommit phase.
1259 final CountDownLatch latch = new CountDownLatch(1);
1260 canCommitFuture.onComplete(new OnComplete<Object>() {
1262 public void onComplete(final Throwable t, final Object resp) {
1265 }, getSystem().dispatcher());
1267 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1269 final InOrder inOrder = inOrder(dataTree);
1270 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1271 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1272 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1273 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1278 public void testPreCommitPhaseFailure() throws Throwable {
1279 new ShardTestKit(getSystem()) {{
1280 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1281 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1282 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1283 "testPreCommitPhaseFailure");
1285 waitUntilLeader(shard);
1287 final FiniteDuration duration = duration("5 seconds");
1288 final Timeout timeout = new Timeout(duration);
1290 doThrow(new RuntimeException("mock preCommit failure")).when(dataTree).prepare(any(DataTreeModification.class));
1292 final TransactionIdentifier transactionID1 = nextTransactionId();
1293 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1294 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1295 expectMsgClass(duration, ReadyTransactionReply.class);
1297 final TransactionIdentifier transactionID2 = nextTransactionId();
1298 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1299 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1300 expectMsgClass(duration, ReadyTransactionReply.class);
1302 // Send the CanCommitTransaction message for the first Tx.
1304 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1305 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1306 expectMsgClass(duration, CanCommitTransactionReply.class));
1307 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1309 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1310 // processed after the first Tx completes.
1312 final Future<Object> canCommitFuture = Patterns.ask(shard,
1313 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1315 // Send the CommitTransaction message for the first Tx. This should send back an error
1316 // and trigger the 2nd Tx to proceed.
1318 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1319 expectMsgClass(duration, akka.actor.Status.Failure.class);
1321 // Wait for the 2nd Tx to complete the canCommit phase.
1323 final CountDownLatch latch = new CountDownLatch(1);
1324 canCommitFuture.onComplete(new OnComplete<Object>() {
1326 public void onComplete(final Throwable t, final Object resp) {
1329 }, getSystem().dispatcher());
1331 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1333 final InOrder inOrder = inOrder(dataTree);
1334 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1335 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1336 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1341 public void testCanCommitPhaseFailure() throws Throwable {
1342 new ShardTestKit(getSystem()) {{
1343 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1344 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1345 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1346 "testCanCommitPhaseFailure");
1348 waitUntilLeader(shard);
1350 final FiniteDuration duration = duration("5 seconds");
1351 final TransactionIdentifier transactionID1 = nextTransactionId();
1353 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure")).
1354 doNothing().when(dataTree).validate(any(DataTreeModification.class));
1356 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1357 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1358 expectMsgClass(duration, ReadyTransactionReply.class);
1360 // Send the CanCommitTransaction message.
1362 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1363 expectMsgClass(duration, akka.actor.Status.Failure.class);
1365 // Send another can commit to ensure the failed one got cleaned up.
1367 final TransactionIdentifier transactionID2 = nextTransactionId();
1368 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1369 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1370 expectMsgClass(duration, ReadyTransactionReply.class);
1372 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1373 final CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
1374 expectMsgClass(CanCommitTransactionReply.class));
1375 assertEquals("getCanCommit", true, reply.getCanCommit());
1380 public void testImmediateCommitWithCanCommitPhaseFailure() throws Throwable {
1381 testImmediateCommitWithCanCommitPhaseFailure(true);
1382 testImmediateCommitWithCanCommitPhaseFailure(false);
1385 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
1386 new ShardTestKit(getSystem()) {{
1387 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1388 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1389 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1390 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1392 waitUntilLeader(shard);
1394 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure")).
1395 doNothing().when(dataTree).validate(any(DataTreeModification.class));
1397 final FiniteDuration duration = duration("5 seconds");
1399 final TransactionIdentifier transactionID1 = nextTransactionId();
1402 shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
1403 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1405 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1406 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1409 expectMsgClass(duration, akka.actor.Status.Failure.class);
1411 // Send another can commit to ensure the failed one got cleaned up.
1413 final TransactionIdentifier transactionID2 = nextTransactionId();
1415 shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
1416 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1418 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1419 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1422 expectMsgClass(duration, CommitTransactionReply.class);
1426 @SuppressWarnings("serial")
1428 public void testAbortWithCommitPending() throws Throwable {
1429 new ShardTestKit(getSystem()) {{
1430 final Creator<Shard> creator = new Creator<Shard>() {
1432 public Shard create() throws Exception {
1433 return new Shard(newShardBuilder()) {
1435 void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
1436 // Simulate an AbortTransaction message occurring during replication, after
1437 // persisting and before finishing the commit to the in-memory store.
1439 doAbortTransaction(transactionId, null);
1440 super.persistPayload(transactionId, payload);
1446 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1447 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1448 "testAbortWithCommitPending");
1450 waitUntilLeader(shard);
1452 final FiniteDuration duration = duration("5 seconds");
1454 final TransactionIdentifier transactionID = nextTransactionId();
1456 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1457 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1458 expectMsgClass(duration, ReadyTransactionReply.class);
1460 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1461 expectMsgClass(duration, CanCommitTransactionReply.class);
1463 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1464 expectMsgClass(duration, CommitTransactionReply.class);
1466 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1468 // Since we're simulating an abort occurring during replication and before finish commit,
1469 // the data should still get written to the in-memory store since we've gotten past
1470 // canCommit and preCommit and persisted the data.
1471 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1476 public void testTransactionCommitTimeout() throws Throwable {
1477 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1478 new ShardTestKit(getSystem()) {{
1479 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1480 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1481 "testTransactionCommitTimeout");
1483 waitUntilLeader(shard);
1485 final FiniteDuration duration = duration("5 seconds");
1487 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1488 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1489 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1491 // Ready 2 Tx's - the first will timeout
1493 final TransactionIdentifier transactionID1 = nextTransactionId();
1494 shard.tell(prepareBatchedModifications(transactionID1, YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1495 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1496 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false), getRef());
1497 expectMsgClass(duration, ReadyTransactionReply.class);
1499 final TransactionIdentifier transactionID2 = nextTransactionId();
1500 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1501 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1502 shard.tell(prepareBatchedModifications(transactionID2, listNodePath,
1503 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false), getRef());
1504 expectMsgClass(duration, ReadyTransactionReply.class);
1506 // canCommit 1st Tx. We don't send the commit so it should timeout.
1508 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1509 expectMsgClass(duration, CanCommitTransactionReply.class);
1511 // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1513 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1514 expectMsgClass(duration, CanCommitTransactionReply.class);
1516 // Try to commit the 1st Tx - should fail as it's not the current Tx.
1518 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1519 expectMsgClass(duration, akka.actor.Status.Failure.class);
1521 // Commit the 2nd Tx.
1523 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1524 expectMsgClass(duration, CommitTransactionReply.class);
1526 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1527 assertNotNull(listNodePath + " not found", node);
1533 // public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1534 // dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1536 // new ShardTestKit(getSystem()) {{
1537 // final TestActorRef<Shard> shard = actorFactory.createTestActor(
1538 // newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1539 // "testTransactionCommitQueueCapacityExceeded");
1541 // waitUntilLeader(shard);
1543 // final FiniteDuration duration = duration("5 seconds");
1545 // final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1547 // final TransactionIdentifier transactionID1 = nextTransactionId();
1548 // final MutableCompositeModification modification1 = new MutableCompositeModification();
1549 // final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1550 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID1,
1553 // final TransactionIdentifier transactionID2 = nextTransactionId();
1554 // final MutableCompositeModification modification2 = new MutableCompositeModification();
1555 // final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1556 // TestModel.OUTER_LIST_PATH,
1557 // ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), transactionID2,
1560 // final TransactionIdentifier transactionID3 = nextTransactionId();
1561 // final MutableCompositeModification modification3 = new MutableCompositeModification();
1562 // final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1563 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID3,
1566 // // Ready the Tx's
1568 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
1569 // expectMsgClass(duration, ReadyTransactionReply.class);
1571 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
1572 // expectMsgClass(duration, ReadyTransactionReply.class);
1574 // // The 3rd Tx should exceed queue capacity and fail.
1576 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
1577 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1579 // // canCommit 1st Tx.
1581 // shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1582 // expectMsgClass(duration, CanCommitTransactionReply.class);
1584 // // canCommit the 2nd Tx - it should get queued.
1586 // shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1588 // // canCommit the 3rd Tx - should exceed queue capacity and fail.
1590 // shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1591 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1596 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Throwable {
1597 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1598 new ShardTestKit(getSystem()) {{
1599 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1600 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1601 "testTransactionCommitWithPriorExpiredCohortEntries");
1603 waitUntilLeader(shard);
1605 final FiniteDuration duration = duration("5 seconds");
1607 final TransactionIdentifier transactionID1 = nextTransactionId();
1608 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1609 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1610 expectMsgClass(duration, ReadyTransactionReply.class);
1612 final TransactionIdentifier transactionID2 = nextTransactionId();
1613 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1614 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1615 expectMsgClass(duration, ReadyTransactionReply.class);
1617 final TransactionIdentifier transactionID3 = nextTransactionId();
1618 shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1619 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1620 expectMsgClass(duration, ReadyTransactionReply.class);
1622 // All Tx's are readied. We'll send canCommit for the last one but not the others. The others
1623 // should expire from the queue and the last one should be processed.
1625 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1626 expectMsgClass(duration, CanCommitTransactionReply.class);
1631 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Throwable {
1632 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1633 new ShardTestKit(getSystem()) {{
1634 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1635 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1636 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1638 waitUntilLeader(shard);
1640 final FiniteDuration duration = duration("5 seconds");
1642 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1644 final TransactionIdentifier transactionID1 = nextTransactionId();
1645 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1646 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1647 expectMsgClass(duration, ReadyTransactionReply.class);
1649 // CanCommit the first Tx so it's the current in-progress Tx.
1651 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1652 expectMsgClass(duration, CanCommitTransactionReply.class);
1654 // Ready the second Tx.
1656 final TransactionIdentifier transactionID2 = nextTransactionId();
1657 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1658 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1659 expectMsgClass(duration, ReadyTransactionReply.class);
1661 // Ready the third Tx.
1663 final TransactionIdentifier transactionID3 = nextTransactionId();
1664 final DataTreeModification modification3 = dataStore.newModification();
1665 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1666 .apply(modification3);
1667 modification3.ready();
1668 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3, true);
1669 shard.tell(readyMessage, getRef());
1671 // Commit the first Tx. After completing, the second should expire from the queue and the third
1674 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1675 expectMsgClass(duration, CommitTransactionReply.class);
1677 // Expect commit reply from the third Tx.
1679 expectMsgClass(duration, CommitTransactionReply.class);
1681 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1682 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1687 public void testCanCommitBeforeReadyFailure() throws Throwable {
1688 new ShardTestKit(getSystem()) {{
1689 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1690 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1691 "testCanCommitBeforeReadyFailure");
1693 shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
1694 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1699 public void testAbortAfterCanCommit() throws Throwable {
1700 new ShardTestKit(getSystem()) {{
1701 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1702 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1703 "testAbortAfterCanCommit");
1705 waitUntilLeader(shard);
1707 final FiniteDuration duration = duration("5 seconds");
1708 final Timeout timeout = new Timeout(duration);
1710 // Ready 2 transactions - the first one will be aborted.
1712 final TransactionIdentifier transactionID1 = nextTransactionId();
1713 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1714 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1715 expectMsgClass(duration, ReadyTransactionReply.class);
1717 final TransactionIdentifier transactionID2 = nextTransactionId();
1718 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1719 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1720 expectMsgClass(duration, ReadyTransactionReply.class);
1722 // Send the CanCommitTransaction message for the first Tx.
1724 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1725 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1726 expectMsgClass(duration, CanCommitTransactionReply.class));
1727 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1729 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1730 // processed after the first Tx completes.
1732 final Future<Object> canCommitFuture = Patterns.ask(shard,
1733 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1735 // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1738 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1739 expectMsgClass(duration, AbortTransactionReply.class);
1741 // Wait for the 2nd Tx to complete the canCommit phase.
1743 canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture, duration);
1744 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1749 public void testAbortAfterReady() throws Throwable {
1750 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1751 new ShardTestKit(getSystem()) {{
1752 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1753 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1755 waitUntilLeader(shard);
1757 final FiniteDuration duration = duration("5 seconds");
1761 final TransactionIdentifier transactionID1 = nextTransactionId();
1762 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1763 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1764 expectMsgClass(duration, ReadyTransactionReply.class);
1766 // Send the AbortTransaction message.
1768 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1769 expectMsgClass(duration, AbortTransactionReply.class);
1771 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1773 // Now send CanCommitTransaction - should fail.
1775 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1776 final Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
1777 assertTrue("Failure type", failure instanceof IllegalStateException);
1779 // Ready and CanCommit another and verify success.
1781 final TransactionIdentifier transactionID2 = nextTransactionId();
1782 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1783 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1784 expectMsgClass(duration, ReadyTransactionReply.class);
1786 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1787 expectMsgClass(duration, CanCommitTransactionReply.class);
1792 public void testAbortQueuedTransaction() throws Throwable {
1793 new ShardTestKit(getSystem()) {{
1794 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1795 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1797 waitUntilLeader(shard);
1799 final FiniteDuration duration = duration("5 seconds");
1803 final TransactionIdentifier transactionID1 = nextTransactionId();
1804 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1805 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1806 expectMsgClass(duration, ReadyTransactionReply.class);
1808 final TransactionIdentifier transactionID2 = nextTransactionId();
1809 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1810 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1811 expectMsgClass(duration, ReadyTransactionReply.class);
1813 final TransactionIdentifier transactionID3 = nextTransactionId();
1814 shard.tell(newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
1815 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1), getRef());
1816 expectMsgClass(duration, ReadyTransactionReply.class);
1818 // Abort the second tx while it's queued.
1820 shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1821 expectMsgClass(duration, AbortTransactionReply.class);
1823 // Commit the other 2.
1825 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1826 expectMsgClass(duration, CanCommitTransactionReply.class);
1828 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1829 expectMsgClass(duration, CommitTransactionReply.class);
1831 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1832 expectMsgClass(duration, CanCommitTransactionReply.class);
1834 shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1835 expectMsgClass(duration, CommitTransactionReply.class);
1837 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1842 public void testCreateSnapshot() throws Exception {
1843 testCreateSnapshot(true, "testCreateSnapshot");
1847 public void testCreateSnapshotWithNonPersistentData() throws Exception {
1848 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1851 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
1853 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1855 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1856 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
1857 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
1862 public void saveSnapshot(final Object o) {
1863 savedSnapshot.set(o);
1864 super.saveSnapshot(o);
1868 dataStoreContextBuilder.persistent(persistent);
1870 new ShardTestKit(getSystem()) {{
1871 class TestShard extends Shard {
1873 protected TestShard(final AbstractBuilder<?, ?> builder) {
1875 setPersistence(new TestPersistentDataProvider(super.persistence()));
1879 public void handleCommand(final Object message) {
1880 super.handleCommand(message);
1882 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
1883 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
1884 latch.get().countDown();
1889 public RaftActorContext getRaftActorContext() {
1890 return super.getRaftActorContext();
1894 final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
1896 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1897 Props.create(new DelegatingShardCreator(creator)).
1898 withDispatcher(Dispatchers.DefaultDispatcherId()), shardActorName);
1900 waitUntilLeader(shard);
1901 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1903 final NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
1905 // Trigger creation of a snapshot by ensuring
1906 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
1907 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1908 awaitAndValidateSnapshot(expectedRoot);
1910 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1911 awaitAndValidateSnapshot(expectedRoot);
1914 private void awaitAndValidateSnapshot(final NormalizedNode<?,?> expectedRoot) throws InterruptedException, IOException {
1915 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1917 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
1918 savedSnapshot.get() instanceof Snapshot);
1920 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
1922 latch.set(new CountDownLatch(1));
1923 savedSnapshot.set(null);
1926 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?,?> expectedRoot) throws IOException {
1927 final NormalizedNode<?, ?> actual = ShardDataTreeSnapshot.deserialize(snapshot.getState()).getRootNode().get();
1928 assertEquals("Root node", expectedRoot, actual);
1933 * This test simply verifies that the applySnapShot logic will work
1934 * @throws ReadFailedException
1935 * @throws DataValidationFailedException
1938 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
1939 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
1940 store.setSchemaContext(SCHEMA_CONTEXT);
1942 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
1943 putTransaction.write(TestModel.TEST_PATH,
1944 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1945 commitTransaction(store, putTransaction);
1948 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
1950 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
1952 writeTransaction.delete(YangInstanceIdentifier.EMPTY);
1953 writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
1955 commitTransaction(store, writeTransaction);
1957 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
1959 assertEquals(expected, actual);
1963 public void testRecoveryApplicable(){
1965 final DatastoreContext persistentContext = DatastoreContext.newBuilder().
1966 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
1968 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext).
1969 schemaContext(SCHEMA_CONTEXT).props();
1971 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
1972 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
1974 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext).
1975 schemaContext(SCHEMA_CONTEXT).props();
1977 new ShardTestKit(getSystem()) {{
1978 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
1980 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
1982 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
1984 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
1989 public void testOnDatastoreContext() {
1990 new ShardTestKit(getSystem()) {{
1991 dataStoreContextBuilder.persistent(true);
1993 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
1995 assertEquals("isRecoveryApplicable", true,
1996 shard.underlyingActor().persistence().isRecoveryApplicable());
1998 waitUntilLeader(shard);
2000 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2002 assertEquals("isRecoveryApplicable", false,
2003 shard.underlyingActor().persistence().isRecoveryApplicable());
2005 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2007 assertEquals("isRecoveryApplicable", true,
2008 shard.underlyingActor().persistence().isRecoveryApplicable());
2013 public void testRegisterRoleChangeListener() throws Exception {
2014 new ShardTestKit(getSystem()) {
2016 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2017 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2018 "testRegisterRoleChangeListener");
2020 waitUntilLeader(shard);
2022 final TestActorRef<MessageCollectorActor> listener =
2023 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2025 shard.tell(new RegisterRoleChangeListener(), listener);
2027 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2029 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2030 ShardLeaderStateChanged.class);
2031 assertEquals("getLocalShardDataTree present", true,
2032 leaderStateChanged.getLocalShardDataTree().isPresent());
2033 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2034 leaderStateChanged.getLocalShardDataTree().get());
2036 MessageCollectorActor.clearMessages(listener);
2038 // Force a leader change
2040 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2042 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2043 ShardLeaderStateChanged.class);
2044 assertEquals("getLocalShardDataTree present", false,
2045 leaderStateChanged.getLocalShardDataTree().isPresent());
2051 public void testFollowerInitialSyncStatus() throws Exception {
2052 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2053 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2054 "testFollowerInitialSyncStatus");
2056 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
2058 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2060 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
2062 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2066 public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
2067 new ShardTestKit(getSystem()) {{
2068 final String testName = "testClusteredDataChangeListenerDelayedRegistration";
2069 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2070 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2072 final MockDataChangeListener listener = new MockDataChangeListener(1);
2073 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2074 actorFactory.generateActorId(testName + "-DataChangeListener"));
2076 setupInMemorySnapshotStore();
2078 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2079 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2080 actorFactory.generateActorId(testName + "-shard"));
2082 waitUntilNoLeader(shard);
2084 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2086 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2087 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2088 RegisterChangeListenerReply.class);
2089 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2091 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2092 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2094 listener.waitForChangeEvents();
2099 public void testClusteredDataChangeListenerRegistration() throws Exception {
2100 new ShardTestKit(getSystem()) {{
2101 final String testName = "testClusteredDataChangeListenerRegistration";
2102 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2103 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2105 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2106 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2108 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2109 Shard.builder().id(followerShardID).
2110 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2111 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2112 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2113 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2115 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2116 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2117 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2118 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2119 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2121 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2122 final String leaderPath = waitUntilLeader(followerShard);
2123 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2125 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2126 final MockDataChangeListener listener = new MockDataChangeListener(1);
2127 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2128 actorFactory.generateActorId(testName + "-DataChangeListener"));
2130 followerShard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
2131 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2132 RegisterChangeListenerReply.class);
2133 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2135 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2137 listener.waitForChangeEvents();
2142 public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
2143 new ShardTestKit(getSystem()) {{
2144 final String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
2145 dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
2146 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2148 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2149 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2150 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2152 setupInMemorySnapshotStore();
2154 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2155 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2156 actorFactory.generateActorId(testName + "-shard"));
2158 waitUntilNoLeader(shard);
2160 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2161 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2162 RegisterDataTreeChangeListenerReply.class);
2163 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2165 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
2166 customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2168 listener.waitForChangeEvents();
2173 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2174 new ShardTestKit(getSystem()) {{
2175 final String testName = "testClusteredDataTreeChangeListenerRegistration";
2176 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2177 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2179 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2180 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2182 final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
2183 Shard.builder().id(followerShardID).
2184 datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
2185 peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2186 "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2187 withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2189 final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
2190 Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
2191 peerAddresses(Collections.singletonMap(followerShardID.toString(),
2192 "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
2193 withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2195 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2196 final String leaderPath = waitUntilLeader(followerShard);
2197 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2199 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2200 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2201 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2202 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2204 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2205 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2206 RegisterDataTreeChangeListenerReply.class);
2207 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2209 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2211 listener.waitForChangeEvents();
2216 public void testServerRemoved() throws Exception {
2217 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2219 final ActorRef shard = parent.underlyingActor().context().actorOf(
2220 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2221 "testServerRemoved");
2223 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2225 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);