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;
23 import akka.actor.ActorRef;
24 import akka.actor.ActorSelection;
25 import akka.actor.Props;
26 import akka.actor.Status.Failure;
27 import akka.dispatch.Dispatchers;
28 import akka.dispatch.OnComplete;
29 import akka.japi.Creator;
30 import akka.pattern.Patterns;
31 import akka.persistence.SaveSnapshotSuccess;
32 import akka.testkit.TestActorRef;
33 import akka.util.Timeout;
34 import com.google.common.base.Stopwatch;
35 import com.google.common.base.Throwables;
36 import com.google.common.primitives.UnsignedLong;
37 import com.google.common.util.concurrent.Uninterruptibles;
38 import java.io.IOException;
39 import java.util.Collections;
40 import java.util.HashSet;
43 import java.util.concurrent.CountDownLatch;
44 import java.util.concurrent.TimeUnit;
45 import java.util.concurrent.atomic.AtomicBoolean;
46 import java.util.concurrent.atomic.AtomicReference;
47 import org.junit.Test;
48 import org.mockito.InOrder;
49 import org.opendaylight.controller.cluster.DataPersistenceProvider;
50 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
51 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
52 import org.opendaylight.controller.cluster.access.concepts.MemberName;
53 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
54 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
55 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
56 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
57 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
58 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
59 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
60 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
61 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
62 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
63 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
65 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
67 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
68 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
70 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
71 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
73 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
74 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
76 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListenerReply;
77 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
78 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
79 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
80 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
81 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
82 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
83 import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
84 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
85 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
86 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
87 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
88 import org.opendaylight.controller.cluster.raft.RaftActorContext;
89 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
90 import org.opendaylight.controller.cluster.raft.Snapshot;
91 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
92 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
93 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
94 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
95 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
96 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
97 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
98 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
99 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
100 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
101 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
102 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
103 import org.opendaylight.controller.cluster.raft.persisted.SimpleReplicatedLogEntry;
104 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
105 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
106 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
107 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
108 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
109 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
110 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
111 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
112 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
113 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
117 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
118 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
119 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
120 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
121 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
122 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
123 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
124 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
125 import scala.concurrent.Await;
126 import scala.concurrent.Future;
127 import scala.concurrent.duration.FiniteDuration;
129 public class ShardTest extends AbstractShardTest {
130 private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in "
131 + "InMemorySnapshotStore and journal recovery seq number will start from 1";
134 public void testRegisterChangeListener() throws Exception {
135 new ShardTestKit(getSystem()) {
137 final TestActorRef<Shard> shard = actorFactory.createTestActor(
138 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
139 "testRegisterChangeListener");
141 waitUntilLeader(shard);
143 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
145 final MockDataChangeListener listener = new MockDataChangeListener(1);
146 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
147 "testRegisterChangeListener-DataChangeListener");
149 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH, dclActor,
150 AsyncDataBroker.DataChangeScope.BASE, true), getRef());
152 final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
153 RegisterChangeListenerReply.class);
154 final String replyPath = reply.getListenerRegistrationPath().toString();
155 assertTrue("Incorrect reply path: " + replyPath,
156 replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
158 final YangInstanceIdentifier path = TestModel.TEST_PATH;
159 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
161 listener.waitForChangeEvents(path);
166 @SuppressWarnings("serial")
168 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
169 // This test tests the timing window in which a change listener is registered before the
170 // shard becomes the leader. We verify that the listener is registered and notified of the
171 // existing data when the shard becomes the leader.
172 // For this test, we want to send the RegisterChangeListener message after the shard
173 // has recovered from persistence and before it becomes the leader. So we subclass
174 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
175 // we know that the shard has been initialized to a follower and has started the
176 // election process. The following 2 CountDownLatches are used to coordinate the
177 // ElectionTimeout with the sending of the RegisterChangeListener message.
178 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
179 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
180 final Creator<Shard> creator = new Creator<Shard>() {
181 boolean firstElectionTimeout = true;
184 public Shard create() throws Exception {
185 // Use a non persistent provider because this test actually invokes persist on the journal
186 // this will cause all other messages to not be queued properly after that.
187 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
188 // it does do a persist)
189 return new Shard(newShardBuilder()) {
191 public void handleCommand(final Object message) {
192 if (message instanceof ElectionTimeout && firstElectionTimeout) {
193 // Got the first ElectionTimeout. We don't forward it to the
194 // base Shard yet until we've sent the RegisterChangeListener
195 // message. So we signal the onFirstElectionTimeout latch to tell
196 // the main thread to send the RegisterChangeListener message and
197 // start a thread to wait on the onChangeListenerRegistered latch,
198 // which the main thread signals after it has sent the message.
199 // After the onChangeListenerRegistered is triggered, we send the
200 // original ElectionTimeout message to proceed with the election.
201 firstElectionTimeout = false;
202 final ActorRef self = getSelf();
206 Uninterruptibles.awaitUninterruptibly(
207 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
208 self.tell(message, self);
212 onFirstElectionTimeout.countDown();
214 super.handleCommand(message);
221 setupInMemorySnapshotStore();
223 final MockDataChangeListener listener = new MockDataChangeListener(1);
224 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
225 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
227 final TestActorRef<Shard> shard = actorFactory.createTestActor(
228 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
229 "testRegisterChangeListenerWhenNotLeaderInitially");
231 new ShardTestKit(getSystem()) {
233 final YangInstanceIdentifier path = TestModel.TEST_PATH;
235 // Wait until the shard receives the first ElectionTimeout
237 assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
239 // Now send the RegisterChangeListener and wait for the reply.
240 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.SUBTREE, false),
243 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
244 RegisterChangeListenerReply.class);
245 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
247 // Sanity check - verify the shard is not the leader yet.
248 shard.tell(FindLeader.INSTANCE, getRef());
249 final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
250 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
252 // Signal the onChangeListenerRegistered latch to tell the
253 // thread above to proceed
254 // with the election process.
255 onChangeListenerRegistered.countDown();
257 // Wait for the shard to become the leader and notify our
258 // listener with the existing
259 // data in the store.
260 listener.waitForChangeEvents(path);
266 public void testRegisterDataTreeChangeListener() throws Exception {
267 new ShardTestKit(getSystem()) {
269 final TestActorRef<Shard> shard = actorFactory.createTestActor(
270 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
271 "testRegisterDataTreeChangeListener");
273 waitUntilLeader(shard);
275 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
277 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
278 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
279 "testRegisterDataTreeChangeListener-DataTreeChangeListener");
281 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
283 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
284 RegisterDataTreeChangeListenerReply.class);
285 final String replyPath = reply.getListenerRegistrationPath().toString();
286 assertTrue("Incorrect reply path: " + replyPath,
287 replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
289 final YangInstanceIdentifier path = TestModel.TEST_PATH;
290 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
292 listener.waitForChangeEvents();
297 @SuppressWarnings("serial")
299 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
300 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
301 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
302 final Creator<Shard> creator = new Creator<Shard>() {
303 boolean firstElectionTimeout = true;
306 public Shard create() throws Exception {
307 return new Shard(newShardBuilder()) {
309 public void handleCommand(final Object message) {
310 if (message instanceof ElectionTimeout && firstElectionTimeout) {
311 firstElectionTimeout = false;
312 final ActorRef self = getSelf();
316 Uninterruptibles.awaitUninterruptibly(
317 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
318 self.tell(message, self);
322 onFirstElectionTimeout.countDown();
324 super.handleCommand(message);
331 setupInMemorySnapshotStore();
333 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
334 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
335 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
337 final TestActorRef<Shard> shard = actorFactory.createTestActor(
338 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
339 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
341 final YangInstanceIdentifier path = TestModel.TEST_PATH;
343 new ShardTestKit(getSystem()) {
345 assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
347 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
348 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
349 RegisterDataTreeChangeListenerReply.class);
350 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
352 shard.tell(FindLeader.INSTANCE, getRef());
353 final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
354 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
356 onChangeListenerRegistered.countDown();
358 // TODO: investigate why we do not receive data chage events
359 listener.waitForChangeEvents();
365 public void testCreateTransaction() {
366 new ShardTestKit(getSystem()) {
368 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
370 waitUntilLeader(shard);
372 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
374 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
375 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
377 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
378 CreateTransactionReply.class);
380 final String path = reply.getTransactionPath().toString();
381 assertTrue("Unexpected transaction path " + path, path
382 .startsWith("akka://test/user/testCreateTransaction/shard-member-1:ShardTransactionTest@0:"));
388 public void testCreateTransactionOnChain() {
389 new ShardTestKit(getSystem()) {
391 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
393 waitUntilLeader(shard);
395 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
396 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
398 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
399 CreateTransactionReply.class);
401 final String path = reply.getTransactionPath().toString();
402 assertTrue("Unexpected transaction path " + path, path.startsWith(
403 "akka://test/user/testCreateTransactionOnChain/shard-member-1:ShardTransactionTest@0:"));
409 public void testPeerAddressResolved() throws Exception {
410 new ShardTestKit(getSystem()) {
412 final ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"),
414 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder()
415 .peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null))
416 .props().withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
418 final String address = "akka://foobar";
419 shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
421 shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
422 final OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
423 assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
429 public void testApplySnapshot() throws Exception {
431 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps()
432 .withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplySnapshot");
434 ShardTestKit.waitUntilLeader(shard);
436 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
437 store.setSchemaContext(SCHEMA_CONTEXT);
439 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
440 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
441 .withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
442 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
444 writeToStore(store, TestModel.TEST_PATH, container);
446 final YangInstanceIdentifier root = YangInstanceIdentifier.EMPTY;
447 final NormalizedNode<?,?> expected = readStore(store, root);
449 final Snapshot snapshot = Snapshot.create(new MetadataShardDataTreeSnapshot(expected).serialize(),
450 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
452 shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
454 final Stopwatch sw = Stopwatch.createStarted();
455 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
456 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
459 assertEquals("Root node", expected, readStore(shard, root));
461 } catch (final AssertionError e) {
466 fail("Snapshot was not applied");
470 public void testApplyState() throws Exception {
471 final TestActorRef<Shard> shard = actorFactory.createTestActor(
472 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");
474 ShardTestKit.waitUntilLeader(shard);
476 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
477 store.setSchemaContext(SCHEMA_CONTEXT);
478 writeToStore(store, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
480 final NormalizedNode<?, ?> root = readStore(store, YangInstanceIdentifier.EMPTY);
481 final Snapshot snapshot = Snapshot.create(new MetadataShardDataTreeSnapshot(root).serialize(),
482 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
484 shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
486 final DataTreeModification writeMod = store.takeSnapshot().newModification();
487 final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
488 writeMod.write(TestModel.TEST_PATH, node);
491 final TransactionIdentifier tx = nextTransactionId();
492 final ApplyState applyState = new ApplyState(null, tx,
493 new SimpleReplicatedLogEntry(1, 2, payloadForModification(store, writeMod, tx)));
495 shard.tell(applyState, shard);
497 final Stopwatch sw = Stopwatch.createStarted();
498 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
499 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
501 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
502 if (actual != null) {
503 assertEquals("Applied state", node, actual);
508 fail("State was not applied");
512 public void testDataTreeCandidateRecovery() throws Exception {
513 // Set up the InMemorySnapshotStore.
514 final DataTree source = setupInMemorySnapshotStore();
516 final DataTreeModification writeMod = source.takeSnapshot().newModification();
517 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
519 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
521 // Set up the InMemoryJournal.
522 InMemoryJournal.addEntry(shardID.toString(), 1, new SimpleReplicatedLogEntry(0, 1,
523 payloadForModification(source, writeMod, nextTransactionId())));
525 final int nListEntries = 16;
526 final Set<Integer> listEntryKeys = new HashSet<>();
528 // Add some ModificationPayload entries
529 for (int i = 1; i <= nListEntries; i++) {
530 listEntryKeys.add(Integer.valueOf(i));
532 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
533 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
535 final DataTreeModification mod = source.takeSnapshot().newModification();
536 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
539 InMemoryJournal.addEntry(shardID.toString(), i + 1, new SimpleReplicatedLogEntry(i, 1,
540 payloadForModification(source, mod, nextTransactionId())));
543 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
544 new ApplyJournalEntries(nListEntries));
546 testRecovery(listEntryKeys);
550 @SuppressWarnings("checkstyle:IllegalCatch")
551 public void testConcurrentThreePhaseCommits() throws Exception {
552 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
553 final CountDownLatch commitLatch = new CountDownLatch(2);
555 final long timeoutSec = 5;
556 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
557 final Timeout timeout = new Timeout(duration);
559 final TestActorRef<Shard> shard = actorFactory.createTestActor(
560 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
561 "testConcurrentThreePhaseCommits");
563 class OnFutureComplete extends OnComplete<Object> {
564 private final Class<?> expRespType;
566 OnFutureComplete(final Class<?> expRespType) {
567 this.expRespType = expRespType;
571 public void onComplete(final Throwable error, final Object resp) {
573 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
576 assertEquals("Commit response type", expRespType, resp.getClass());
578 } catch (final Exception e) {
584 void onSuccess(final Object resp) throws Exception {
588 class OnCommitFutureComplete extends OnFutureComplete {
589 OnCommitFutureComplete() {
590 super(CommitTransactionReply.class);
594 public void onComplete(final Throwable error, final Object resp) {
595 super.onComplete(error, resp);
596 commitLatch.countDown();
600 class OnCanCommitFutureComplete extends OnFutureComplete {
601 private final TransactionIdentifier transactionID;
603 OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
604 super(CanCommitTransactionReply.class);
605 this.transactionID = transactionID;
609 void onSuccess(final Object resp) throws Exception {
610 final CanCommitTransactionReply canCommitReply =
611 CanCommitTransactionReply.fromSerializable(resp);
612 assertEquals("Can commit", true, canCommitReply.getCanCommit());
614 final Future<Object> commitFuture = Patterns.ask(shard,
615 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
616 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
620 new ShardTestKit(getSystem()) {
622 waitUntilLeader(shard);
624 final TransactionIdentifier transactionID1 = nextTransactionId();
625 final TransactionIdentifier transactionID2 = nextTransactionId();
626 final TransactionIdentifier transactionID3 = nextTransactionId();
628 final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
629 shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
630 final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
631 final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
632 final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
634 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
635 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
636 final ReadyTransactionReply readyReply = ReadyTransactionReply
637 .fromSerializable(expectMsgClass(duration, ReadyTransactionReply.class));
638 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
640 // Send the CanCommitTransaction message for the first Tx.
642 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
643 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
644 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
645 assertEquals("Can commit", true, canCommitReply.getCanCommit());
647 // Ready 2 more Tx's.
649 shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
650 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
651 expectMsgClass(duration, ReadyTransactionReply.class);
654 prepareBatchedModifications(transactionID3,
655 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
656 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
657 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
659 expectMsgClass(duration, ReadyTransactionReply.class);
661 // Send the CanCommitTransaction message for the next 2 Tx's.
662 // These should get queued and
663 // processed after the first Tx completes.
665 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
666 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
668 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
669 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
671 // Send the CommitTransaction message for the first Tx. After it
672 // completes, it should
673 // trigger the 2nd Tx to proceed which should in turn then
676 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
677 expectMsgClass(duration, CommitTransactionReply.class);
679 // Wait for the next 2 Tx's to complete.
681 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2), getSystem().dispatcher());
683 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3), getSystem().dispatcher());
685 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
687 if (caughtEx.get() != null) {
688 Throwables.propagateIfInstanceOf(caughtEx.get(), Exception.class);
689 Throwables.propagate(caughtEx.get());
692 assertEquals("Commits complete", true, done);
694 final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
695 cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
696 cohort3.getPreCommit(), cohort3.getCommit());
697 inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
698 inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
699 inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
700 inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
701 inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
702 inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
703 inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
704 inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
705 inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
707 // Verify data in the data store.
709 verifyOuterListEntry(shard, 1);
711 verifyLastApplied(shard, 2);
717 public void testBatchedModificationsWithNoCommitOnReady() throws Exception {
718 new ShardTestKit(getSystem()) {
720 final TestActorRef<Shard> shard = actorFactory.createTestActor(
721 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
722 "testBatchedModificationsWithNoCommitOnReady");
724 waitUntilLeader(shard);
726 final TransactionIdentifier transactionID = nextTransactionId();
727 final FiniteDuration duration = duration("5 seconds");
729 // Send a BatchedModifications to start a transaction.
731 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
732 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
733 expectMsgClass(duration, BatchedModificationsReply.class);
735 // Send a couple more BatchedModifications.
738 newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
739 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
741 expectMsgClass(duration, BatchedModificationsReply.class);
743 shard.tell(newBatchedModifications(transactionID,
744 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
745 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
746 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3),
748 expectMsgClass(duration, ReadyTransactionReply.class);
750 // Send the CanCommitTransaction message.
752 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
753 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
754 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
755 assertEquals("Can commit", true, canCommitReply.getCanCommit());
757 // Send the CommitTransaction message.
759 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
760 expectMsgClass(duration, CommitTransactionReply.class);
762 // Verify data in the data store.
764 verifyOuterListEntry(shard, 1);
770 public void testBatchedModificationsWithCommitOnReady() throws Exception {
771 new ShardTestKit(getSystem()) {
773 final TestActorRef<Shard> shard = actorFactory.createTestActor(
774 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
775 "testBatchedModificationsWithCommitOnReady");
777 waitUntilLeader(shard);
779 final TransactionIdentifier transactionID = nextTransactionId();
780 final FiniteDuration duration = duration("5 seconds");
782 // Send a BatchedModifications to start a transaction.
784 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
785 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
786 expectMsgClass(duration, BatchedModificationsReply.class);
788 // Send a couple more BatchedModifications.
790 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
791 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
793 expectMsgClass(duration, BatchedModificationsReply.class);
795 shard.tell(newBatchedModifications(transactionID,
796 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
797 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
798 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3),
801 expectMsgClass(duration, CommitTransactionReply.class);
803 // Verify data in the data store.
805 verifyOuterListEntry(shard, 1);
810 @Test(expected = IllegalStateException.class)
811 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
812 new ShardTestKit(getSystem()) {
814 final TestActorRef<Shard> shard = actorFactory.createTestActor(
815 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
816 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
818 waitUntilLeader(shard);
820 final TransactionIdentifier transactionID = nextTransactionId();
821 final BatchedModifications batched = new BatchedModifications(transactionID,
822 DataStoreVersions.CURRENT_VERSION);
823 batched.setReady(true);
824 batched.setTotalMessagesSent(2);
826 shard.tell(batched, getRef());
828 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
830 if (failure != null) {
831 Throwables.propagateIfInstanceOf(failure.cause(), Exception.class);
832 Throwables.propagate(failure.cause());
839 public void testBatchedModificationsWithOperationFailure() throws Exception {
840 new ShardTestKit(getSystem()) {
842 final TestActorRef<Shard> shard = actorFactory.createTestActor(
843 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
844 "testBatchedModificationsWithOperationFailure");
846 waitUntilLeader(shard);
848 // Test merge with invalid data. An exception should occur when
849 // the merge is applied. Note that
850 // write will not validate the children for performance reasons.
852 final TransactionIdentifier transactionID = nextTransactionId();
854 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
855 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
856 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
858 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
859 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
860 shard.tell(batched, getRef());
861 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
863 final Throwable cause = failure.cause();
865 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
866 batched.setReady(true);
867 batched.setTotalMessagesSent(2);
869 shard.tell(batched, getRef());
871 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
872 assertEquals("Failure cause", cause, failure.cause());
878 public void testBatchedModificationsOnTransactionChain() throws Exception {
879 new ShardTestKit(getSystem()) {
881 final TestActorRef<Shard> shard = actorFactory.createTestActor(
882 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
883 "testBatchedModificationsOnTransactionChain");
885 waitUntilLeader(shard);
887 final LocalHistoryIdentifier historyId = nextHistoryId();
888 final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
889 final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
891 final FiniteDuration duration = duration("5 seconds");
893 // Send a BatchedModifications to start a chained write
894 // transaction and ready it.
896 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
897 final YangInstanceIdentifier path = TestModel.TEST_PATH;
898 shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
899 expectMsgClass(duration, ReadyTransactionReply.class);
901 // Create a read Tx on the same chain.
903 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
904 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
906 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"),
907 CreateTransactionReply.class);
909 getSystem().actorSelection(createReply.getTransactionPath())
910 .tell(new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
911 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
912 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
914 // Commit the write transaction.
916 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
917 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
918 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
919 assertEquals("Can commit", true, canCommitReply.getCanCommit());
921 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
922 expectMsgClass(duration, CommitTransactionReply.class);
924 // Verify data in the data store.
926 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
927 assertEquals("Stored node", containerNode, actualNode);
933 public void testOnBatchedModificationsWhenNotLeader() {
934 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
935 new ShardTestKit(getSystem()) {
937 final Creator<Shard> creator = new Creator<Shard>() {
938 private static final long serialVersionUID = 1L;
941 public Shard create() throws Exception {
942 return new Shard(newShardBuilder()) {
944 protected boolean isLeader() {
945 return overrideLeaderCalls.get() ? false : super.isLeader();
949 public ActorSelection getLeader() {
950 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path())
957 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
958 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
959 "testOnBatchedModificationsWhenNotLeader");
961 waitUntilLeader(shard);
963 overrideLeaderCalls.set(true);
965 final BatchedModifications batched = new BatchedModifications(nextTransactionId(),
966 DataStoreVersions.CURRENT_VERSION);
968 shard.tell(batched, ActorRef.noSender());
970 expectMsgEquals(batched);
976 public void testTransactionMessagesWithNoLeader() {
977 new ShardTestKit(getSystem()) {
979 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
980 .shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
981 final TestActorRef<Shard> shard = actorFactory.createTestActor(
982 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
983 "testTransactionMessagesWithNoLeader");
985 waitUntilNoLeader(shard);
987 final TransactionIdentifier txId = nextTransactionId();
988 shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
989 Failure failure = expectMsgClass(Failure.class);
990 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
992 shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
993 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
994 failure = expectMsgClass(Failure.class);
995 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
997 shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
998 failure = expectMsgClass(Failure.class);
999 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
1005 public void testReadyWithReadWriteImmediateCommit() throws Exception {
1006 testReadyWithImmediateCommit(true);
1010 public void testReadyWithWriteOnlyImmediateCommit() throws Exception {
1011 testReadyWithImmediateCommit(false);
1014 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception {
1015 new ShardTestKit(getSystem()) {
1017 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1018 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1019 "testReadyWithImmediateCommit-" + readWrite);
1021 waitUntilLeader(shard);
1023 final TransactionIdentifier transactionID = nextTransactionId();
1024 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1026 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1027 containerNode, true), getRef());
1029 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true),
1033 expectMsgClass(duration("5 seconds"), CommitTransactionReply.class);
1035 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1036 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1042 public void testReadyLocalTransactionWithImmediateCommit() throws Exception {
1043 new ShardTestKit(getSystem()) {
1045 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1046 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1047 "testReadyLocalTransactionWithImmediateCommit");
1049 waitUntilLeader(shard);
1051 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1053 final DataTreeModification modification = dataStore.newModification();
1055 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1056 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1057 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1058 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1060 final TransactionIdentifier txId = nextTransactionId();
1061 modification.ready();
1062 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1064 shard.tell(readyMessage, getRef());
1066 expectMsgClass(CommitTransactionReply.class);
1068 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1069 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1075 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception {
1076 new ShardTestKit(getSystem()) {
1078 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1079 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1080 "testReadyLocalTransactionWithThreePhaseCommit");
1082 waitUntilLeader(shard);
1084 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1086 final DataTreeModification modification = dataStore.newModification();
1088 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1089 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1090 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1091 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1093 final TransactionIdentifier txId = nextTransactionId();
1094 modification.ready();
1095 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1097 shard.tell(readyMessage, getRef());
1099 expectMsgClass(ReadyTransactionReply.class);
1101 // Send the CanCommitTransaction message.
1103 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1104 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1105 .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
1106 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1108 // Send the CanCommitTransaction message.
1110 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1111 expectMsgClass(CommitTransactionReply.class);
1113 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1114 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1120 public void testReadWriteCommitWithPersistenceDisabled() throws Exception {
1121 dataStoreContextBuilder.persistent(false);
1122 new ShardTestKit(getSystem()) {
1124 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1125 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1126 "testCommitWithPersistenceDisabled");
1128 waitUntilLeader(shard);
1130 // Setup a simulated transactions with a mock cohort.
1132 final FiniteDuration duration = duration("5 seconds");
1134 final TransactionIdentifier transactionID = nextTransactionId();
1135 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1136 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false),
1138 expectMsgClass(duration, ReadyTransactionReply.class);
1140 // Send the CanCommitTransaction message.
1142 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1143 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1144 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1145 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1147 // Send the CanCommitTransaction message.
1149 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1150 expectMsgClass(duration, CommitTransactionReply.class);
1152 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1153 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1159 public void testReadWriteCommitWhenTransactionHasNoModifications() {
1160 testCommitWhenTransactionHasNoModifications(true);
1164 public void testWriteOnlyCommitWhenTransactionHasNoModifications() {
1165 testCommitWhenTransactionHasNoModifications(false);
1168 private void testCommitWhenTransactionHasNoModifications(final boolean readWrite) {
1169 // Note that persistence is enabled which would normally result in the
1170 // entry getting written to the journal
1171 // but here that need not happen
1172 new ShardTestKit(getSystem()) {
1174 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1175 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1176 "testCommitWhenTransactionHasNoModifications-" + readWrite);
1178 waitUntilLeader(shard);
1180 final TransactionIdentifier transactionID = nextTransactionId();
1182 final FiniteDuration duration = duration("5 seconds");
1185 final ReadWriteShardDataTreeTransaction rwTx = shard.underlyingActor().getDataStore()
1186 .newReadWriteTransaction(transactionID);
1187 shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, rwTx, false), getRef());
1189 shard.tell(prepareBatchedModifications(transactionID, new MutableCompositeModification()),
1193 expectMsgClass(duration, ReadyTransactionReply.class);
1195 // Send the CanCommitTransaction message.
1197 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1198 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1199 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1200 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1202 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1203 expectMsgClass(duration, CommitTransactionReply.class);
1205 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1206 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1208 // Use MBean for verification
1209 // Committed transaction count should increase as usual
1210 assertEquals(1, shardStats.getCommittedTransactionsCount());
1212 // Commit index should not advance because this does not go into
1214 assertEquals(-1, shardStats.getCommitIndex());
1220 public void testReadWriteCommitWhenTransactionHasModifications() throws Exception {
1221 testCommitWhenTransactionHasModifications(true);
1225 public void testWriteOnlyCommitWhenTransactionHasModifications() throws Exception {
1226 testCommitWhenTransactionHasModifications(false);
1229 private void testCommitWhenTransactionHasModifications(final boolean readWrite) throws Exception {
1230 new ShardTestKit(getSystem()) {
1232 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1233 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1234 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1235 "testCommitWhenTransactionHasModifications-" + readWrite);
1237 waitUntilLeader(shard);
1239 final FiniteDuration duration = duration("5 seconds");
1240 final TransactionIdentifier transactionID = nextTransactionId();
1243 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1244 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1246 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1247 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1250 expectMsgClass(duration, ReadyTransactionReply.class);
1252 // Send the CanCommitTransaction message.
1254 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1255 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1256 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1257 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1259 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1260 expectMsgClass(duration, CommitTransactionReply.class);
1262 final InOrder inOrder = inOrder(dataTree);
1263 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1264 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1265 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1267 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1268 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1270 // Use MBean for verification
1271 // Committed transaction count should increase as usual
1272 assertEquals(1, shardStats.getCommittedTransactionsCount());
1274 // Commit index should advance as we do not have an empty
1276 assertEquals(0, shardStats.getCommitIndex());
1282 public void testCommitPhaseFailure() throws Exception {
1283 new ShardTestKit(getSystem()) {
1285 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1286 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1287 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1288 "testCommitPhaseFailure");
1290 waitUntilLeader(shard);
1292 final FiniteDuration duration = duration("5 seconds");
1293 final Timeout timeout = new Timeout(duration);
1295 // Setup 2 simulated transactions with mock cohorts. The first
1299 doThrow(new RuntimeException("mock commit failure")).when(dataTree)
1300 .commit(any(DataTreeCandidate.class));
1302 final TransactionIdentifier transactionID1 = nextTransactionId();
1303 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1304 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1305 expectMsgClass(duration, ReadyTransactionReply.class);
1307 final TransactionIdentifier transactionID2 = nextTransactionId();
1308 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1309 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1310 expectMsgClass(duration, ReadyTransactionReply.class);
1312 // Send the CanCommitTransaction message for the first Tx.
1314 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1315 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1316 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1317 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1319 // Send the CanCommitTransaction message for the 2nd Tx. This
1320 // should get queued and
1321 // processed after the first Tx completes.
1323 final Future<Object> canCommitFuture = Patterns.ask(shard,
1324 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1326 // Send the CommitTransaction message for the first Tx. This
1327 // should send back an error
1328 // and trigger the 2nd Tx to proceed.
1330 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1331 expectMsgClass(duration, akka.actor.Status.Failure.class);
1333 // Wait for the 2nd Tx to complete the canCommit phase.
1335 final CountDownLatch latch = new CountDownLatch(1);
1336 canCommitFuture.onComplete(new OnComplete<Object>() {
1338 public void onComplete(final Throwable failure, final Object resp) {
1341 }, getSystem().dispatcher());
1343 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1345 final InOrder inOrder = inOrder(dataTree);
1346 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1347 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1349 // FIXME: this invocation is done on the result of validate(). To test it, we need to make sure mock
1350 // validate performs wrapping and we capture that mock
1351 // inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1353 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1359 public void testPreCommitPhaseFailure() throws Exception {
1360 new ShardTestKit(getSystem()) {
1362 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1363 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1364 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1365 "testPreCommitPhaseFailure");
1367 waitUntilLeader(shard);
1369 final FiniteDuration duration = duration("5 seconds");
1370 final Timeout timeout = new Timeout(duration);
1372 doThrow(new RuntimeException("mock preCommit failure")).when(dataTree)
1373 .prepare(any(DataTreeModification.class));
1375 final TransactionIdentifier transactionID1 = nextTransactionId();
1376 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1377 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1378 expectMsgClass(duration, ReadyTransactionReply.class);
1380 final TransactionIdentifier transactionID2 = nextTransactionId();
1381 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1382 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1383 expectMsgClass(duration, ReadyTransactionReply.class);
1385 // Send the CanCommitTransaction message for the first Tx.
1387 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1388 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1389 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1390 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1392 // Send the CanCommitTransaction message for the 2nd Tx. This
1393 // should get queued and
1394 // processed after the first Tx completes.
1396 final Future<Object> canCommitFuture = Patterns.ask(shard,
1397 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1399 // Send the CommitTransaction message for the first Tx. This
1400 // should send back an error
1401 // and trigger the 2nd Tx to proceed.
1403 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1404 expectMsgClass(duration, akka.actor.Status.Failure.class);
1406 // Wait for the 2nd Tx to complete the canCommit phase.
1408 final CountDownLatch latch = new CountDownLatch(1);
1409 canCommitFuture.onComplete(new OnComplete<Object>() {
1411 public void onComplete(final Throwable failure, final Object resp) {
1414 }, getSystem().dispatcher());
1416 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1418 final InOrder inOrder = inOrder(dataTree);
1419 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1420 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1421 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1427 public void testCanCommitPhaseFailure() throws Exception {
1428 new ShardTestKit(getSystem()) {
1430 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1431 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1432 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1433 "testCanCommitPhaseFailure");
1435 waitUntilLeader(shard);
1437 final FiniteDuration duration = duration("5 seconds");
1438 final TransactionIdentifier transactionID1 = nextTransactionId();
1440 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1441 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1443 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1444 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1445 expectMsgClass(duration, ReadyTransactionReply.class);
1447 // Send the CanCommitTransaction message.
1449 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1450 expectMsgClass(duration, akka.actor.Status.Failure.class);
1452 // Send another can commit to ensure the failed one got cleaned
1455 final TransactionIdentifier transactionID2 = nextTransactionId();
1456 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1457 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1458 expectMsgClass(duration, ReadyTransactionReply.class);
1460 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1461 final CanCommitTransactionReply reply = CanCommitTransactionReply
1462 .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
1463 assertEquals("getCanCommit", true, reply.getCanCommit());
1469 public void testImmediateCommitWithCanCommitPhaseFailure() throws Exception {
1470 testImmediateCommitWithCanCommitPhaseFailure(true);
1471 testImmediateCommitWithCanCommitPhaseFailure(false);
1474 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Exception {
1475 new ShardTestKit(getSystem()) {
1477 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1478 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1479 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1480 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1482 waitUntilLeader(shard);
1484 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1485 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1487 final FiniteDuration duration = duration("5 seconds");
1489 final TransactionIdentifier transactionID1 = nextTransactionId();
1492 shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
1493 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1495 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1496 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1499 expectMsgClass(duration, akka.actor.Status.Failure.class);
1501 // Send another can commit to ensure the failed one got cleaned
1504 final TransactionIdentifier transactionID2 = nextTransactionId();
1506 shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
1507 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1509 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1510 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1513 expectMsgClass(duration, CommitTransactionReply.class);
1519 public void testAbortWithCommitPending() throws Exception {
1520 new ShardTestKit(getSystem()) {
1522 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
1524 void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
1525 // Simulate an AbortTransaction message occurring during
1526 // replication, after
1527 // persisting and before finishing the commit to the
1530 doAbortTransaction(transactionId, null);
1531 super.persistPayload(transactionId, payload);
1535 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1536 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1537 "testAbortWithCommitPending");
1539 waitUntilLeader(shard);
1541 final FiniteDuration duration = duration("5 seconds");
1543 final TransactionIdentifier transactionID = nextTransactionId();
1545 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1546 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1547 expectMsgClass(duration, ReadyTransactionReply.class);
1549 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1550 expectMsgClass(duration, CanCommitTransactionReply.class);
1552 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1553 expectMsgClass(duration, CommitTransactionReply.class);
1555 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1557 // Since we're simulating an abort occurring during replication
1558 // and before finish commit,
1559 // the data should still get written to the in-memory store
1560 // since we've gotten past
1561 // canCommit and preCommit and persisted the data.
1562 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1568 public void testTransactionCommitTimeout() throws Exception {
1569 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1570 new ShardTestKit(getSystem()) {
1572 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1573 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1574 "testTransactionCommitTimeout");
1576 waitUntilLeader(shard);
1578 final FiniteDuration duration = duration("5 seconds");
1580 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1581 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1582 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1584 // Ready 2 Tx's - the first will timeout
1586 final TransactionIdentifier transactionID1 = nextTransactionId();
1588 prepareBatchedModifications(transactionID1,
1589 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1590 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1591 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
1593 expectMsgClass(duration, ReadyTransactionReply.class);
1595 final TransactionIdentifier transactionID2 = nextTransactionId();
1596 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1597 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1599 prepareBatchedModifications(transactionID2, listNodePath,
1600 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false),
1602 expectMsgClass(duration, ReadyTransactionReply.class);
1604 // canCommit 1st Tx. We don't send the commit so it should
1607 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1608 expectMsgClass(duration, CanCommitTransactionReply.class);
1610 // canCommit the 2nd Tx - it should complete after the 1st Tx
1613 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1614 expectMsgClass(duration, CanCommitTransactionReply.class);
1616 // Try to commit the 1st Tx - should fail as it's not the
1619 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1620 expectMsgClass(duration, akka.actor.Status.Failure.class);
1622 // Commit the 2nd Tx.
1624 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1625 expectMsgClass(duration, CommitTransactionReply.class);
1627 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1628 assertNotNull(listNodePath + " not found", node);
1635 // public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1636 // dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1638 // new ShardTestKit(getSystem()) {{
1639 // final TestActorRef<Shard> shard = actorFactory.createTestActor(
1640 // newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1641 // "testTransactionCommitQueueCapacityExceeded");
1643 // waitUntilLeader(shard);
1645 // final FiniteDuration duration = duration("5 seconds");
1647 // final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1649 // final TransactionIdentifier transactionID1 = nextTransactionId();
1650 // final MutableCompositeModification modification1 = new MutableCompositeModification();
1651 // final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1652 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID1,
1655 // final TransactionIdentifier transactionID2 = nextTransactionId();
1656 // final MutableCompositeModification modification2 = new MutableCompositeModification();
1657 // final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1658 // TestModel.OUTER_LIST_PATH,
1659 // ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), transactionID2,
1662 // final TransactionIdentifier transactionID3 = nextTransactionId();
1663 // final MutableCompositeModification modification3 = new MutableCompositeModification();
1664 // final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1665 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID3,
1668 // // Ready the Tx's
1670 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1,
1671 // modification1), getRef());
1672 // expectMsgClass(duration, ReadyTransactionReply.class);
1674 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2,
1675 // modification2), getRef());
1676 // expectMsgClass(duration, ReadyTransactionReply.class);
1678 // // The 3rd Tx should exceed queue capacity and fail.
1680 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3,
1681 // modification3), getRef());
1682 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1684 // // canCommit 1st Tx.
1686 // shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1687 // expectMsgClass(duration, CanCommitTransactionReply.class);
1689 // // canCommit the 2nd Tx - it should get queued.
1691 // shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1693 // // canCommit the 3rd Tx - should exceed queue capacity and fail.
1695 // shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1696 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1701 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Exception {
1702 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1703 new ShardTestKit(getSystem()) {
1705 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1706 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1707 "testTransactionCommitWithPriorExpiredCohortEntries");
1709 waitUntilLeader(shard);
1711 final FiniteDuration duration = duration("5 seconds");
1713 final TransactionIdentifier transactionID1 = nextTransactionId();
1714 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1715 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1716 expectMsgClass(duration, ReadyTransactionReply.class);
1718 final TransactionIdentifier transactionID2 = nextTransactionId();
1719 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1720 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1721 expectMsgClass(duration, ReadyTransactionReply.class);
1723 final TransactionIdentifier transactionID3 = nextTransactionId();
1724 shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1725 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1726 expectMsgClass(duration, ReadyTransactionReply.class);
1728 // All Tx's are readied. We'll send canCommit for the last one
1729 // but not the others. The others
1730 // should expire from the queue and the last one should be
1733 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1734 expectMsgClass(duration, CanCommitTransactionReply.class);
1740 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Exception {
1741 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1742 new ShardTestKit(getSystem()) {
1744 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1745 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1746 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1748 waitUntilLeader(shard);
1750 final FiniteDuration duration = duration("5 seconds");
1752 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1754 final TransactionIdentifier transactionID1 = nextTransactionId();
1755 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1756 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1757 expectMsgClass(duration, ReadyTransactionReply.class);
1759 // CanCommit the first Tx so it's the current in-progress Tx.
1761 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1762 expectMsgClass(duration, CanCommitTransactionReply.class);
1764 // Ready the second Tx.
1766 final TransactionIdentifier transactionID2 = nextTransactionId();
1767 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1768 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1769 expectMsgClass(duration, ReadyTransactionReply.class);
1771 // Ready the third Tx.
1773 final TransactionIdentifier transactionID3 = nextTransactionId();
1774 final DataTreeModification modification3 = dataStore.newModification();
1775 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1776 .apply(modification3);
1777 modification3.ready();
1778 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3,
1780 shard.tell(readyMessage, getRef());
1782 // Commit the first Tx. After completing, the second should
1783 // expire from the queue and the third
1786 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1787 expectMsgClass(duration, CommitTransactionReply.class);
1789 // Expect commit reply from the third Tx.
1791 expectMsgClass(duration, CommitTransactionReply.class);
1793 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1794 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1800 public void testCanCommitBeforeReadyFailure() throws Exception {
1801 new ShardTestKit(getSystem()) {
1803 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1804 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1805 "testCanCommitBeforeReadyFailure");
1807 shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
1808 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1814 public void testAbortAfterCanCommit() throws Exception {
1815 new ShardTestKit(getSystem()) {
1817 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1818 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterCanCommit");
1820 waitUntilLeader(shard);
1822 final FiniteDuration duration = duration("5 seconds");
1823 final Timeout timeout = new Timeout(duration);
1825 // Ready 2 transactions - the first one will be aborted.
1827 final TransactionIdentifier transactionID1 = nextTransactionId();
1828 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1829 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1830 expectMsgClass(duration, ReadyTransactionReply.class);
1832 final TransactionIdentifier transactionID2 = nextTransactionId();
1833 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1834 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1835 expectMsgClass(duration, ReadyTransactionReply.class);
1837 // Send the CanCommitTransaction message for the first Tx.
1839 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1840 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1841 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1842 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1844 // Send the CanCommitTransaction message for the 2nd Tx. This
1845 // should get queued and
1846 // processed after the first Tx completes.
1848 final Future<Object> canCommitFuture = Patterns.ask(shard,
1849 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1851 // Send the AbortTransaction message for the first Tx. This
1852 // should trigger the 2nd
1855 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1856 expectMsgClass(duration, AbortTransactionReply.class);
1858 // Wait for the 2nd Tx to complete the canCommit phase.
1860 canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture, duration);
1861 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1867 public void testAbortAfterReady() throws Exception {
1868 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1869 new ShardTestKit(getSystem()) {
1871 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1872 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1874 waitUntilLeader(shard);
1876 final FiniteDuration duration = duration("5 seconds");
1880 final TransactionIdentifier transactionID1 = nextTransactionId();
1881 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1882 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1883 expectMsgClass(duration, ReadyTransactionReply.class);
1885 // Send the AbortTransaction message.
1887 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1888 expectMsgClass(duration, AbortTransactionReply.class);
1890 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1892 // Now send CanCommitTransaction - should fail.
1894 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1895 final Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
1896 assertTrue("Failure type", failure instanceof IllegalStateException);
1898 // Ready and CanCommit another and verify success.
1900 final TransactionIdentifier transactionID2 = nextTransactionId();
1901 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1902 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1903 expectMsgClass(duration, ReadyTransactionReply.class);
1905 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1906 expectMsgClass(duration, CanCommitTransactionReply.class);
1912 public void testAbortQueuedTransaction() throws Exception {
1913 new ShardTestKit(getSystem()) {
1915 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1916 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1918 waitUntilLeader(shard);
1920 final FiniteDuration duration = duration("5 seconds");
1924 final TransactionIdentifier transactionID1 = nextTransactionId();
1925 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1926 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1927 expectMsgClass(duration, ReadyTransactionReply.class);
1929 final TransactionIdentifier transactionID2 = nextTransactionId();
1930 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1931 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1932 expectMsgClass(duration, ReadyTransactionReply.class);
1934 final TransactionIdentifier transactionID3 = nextTransactionId();
1936 newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
1937 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1),
1939 expectMsgClass(duration, ReadyTransactionReply.class);
1941 // Abort the second tx while it's queued.
1943 shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1944 expectMsgClass(duration, AbortTransactionReply.class);
1946 // Commit the other 2.
1948 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1949 expectMsgClass(duration, CanCommitTransactionReply.class);
1951 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1952 expectMsgClass(duration, CommitTransactionReply.class);
1954 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1955 expectMsgClass(duration, CanCommitTransactionReply.class);
1957 shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1958 expectMsgClass(duration, CommitTransactionReply.class);
1960 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1966 public void testCreateSnapshotWithNonPersistentData() throws Exception {
1967 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1971 public void testCreateSnapshot() throws Exception {
1972 testCreateSnapshot(true, "testCreateSnapshot");
1975 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception {
1976 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1978 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1979 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
1980 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
1985 public void saveSnapshot(final Object obj) {
1986 savedSnapshot.set(obj);
1987 super.saveSnapshot(obj);
1991 dataStoreContextBuilder.persistent(persistent);
1993 class TestShard extends Shard {
1995 protected TestShard(final AbstractBuilder<?, ?> builder) {
1997 setPersistence(new TestPersistentDataProvider(super.persistence()));
2001 public void handleCommand(final Object message) {
2002 super.handleCommand(message);
2004 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
2005 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
2006 latch.get().countDown();
2011 public RaftActorContext getRaftActorContext() {
2012 return super.getRaftActorContext();
2016 new ShardTestKit(getSystem()) {
2018 final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
2020 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
2021 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
2024 waitUntilLeader(shard);
2025 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2027 final NormalizedNode<?, ?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
2029 // Trigger creation of a snapshot by ensuring
2030 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
2031 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2032 awaitAndValidateSnapshot(expectedRoot);
2034 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
2035 awaitAndValidateSnapshot(expectedRoot);
2038 private void awaitAndValidateSnapshot(final NormalizedNode<?, ?> expectedRoot)
2039 throws InterruptedException, IOException {
2040 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
2042 assertTrue("Invalid saved snapshot " + savedSnapshot.get(), savedSnapshot.get() instanceof Snapshot);
2044 verifySnapshot((Snapshot) savedSnapshot.get(), expectedRoot);
2046 latch.set(new CountDownLatch(1));
2047 savedSnapshot.set(null);
2050 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?, ?> expectedRoot)
2051 throws IOException {
2052 final NormalizedNode<?, ?> actual = ShardDataTreeSnapshot.deserialize(snapshot.getState()).getRootNode()
2054 assertEquals("Root node", expectedRoot, actual);
2060 * This test simply verifies that the applySnapShot logic will work.
2063 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
2064 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
2065 store.setSchemaContext(SCHEMA_CONTEXT);
2067 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
2068 putTransaction.write(TestModel.TEST_PATH,
2069 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2070 commitTransaction(store, putTransaction);
2073 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
2075 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2077 writeTransaction.delete(YangInstanceIdentifier.EMPTY);
2078 writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
2080 commitTransaction(store, writeTransaction);
2082 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
2084 assertEquals(expected, actual);
2088 public void testRecoveryApplicable() {
2090 final DatastoreContext persistentContext = DatastoreContext.newBuilder()
2091 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2093 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext)
2094 .schemaContext(SCHEMA_CONTEXT).props();
2096 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder()
2097 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2099 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext)
2100 .schemaContext(SCHEMA_CONTEXT).props();
2102 new ShardTestKit(getSystem()) {
2104 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2106 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2108 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2110 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2116 public void testOnDatastoreContext() {
2117 new ShardTestKit(getSystem()) {
2119 dataStoreContextBuilder.persistent(true);
2121 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(),
2122 "testOnDatastoreContext");
2124 assertEquals("isRecoveryApplicable", true,
2125 shard.underlyingActor().persistence().isRecoveryApplicable());
2127 waitUntilLeader(shard);
2129 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2131 assertEquals("isRecoveryApplicable", false,
2132 shard.underlyingActor().persistence().isRecoveryApplicable());
2134 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2136 assertEquals("isRecoveryApplicable", true,
2137 shard.underlyingActor().persistence().isRecoveryApplicable());
2143 public void testRegisterRoleChangeListener() throws Exception {
2144 new ShardTestKit(getSystem()) {
2146 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2147 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2148 "testRegisterRoleChangeListener");
2150 waitUntilLeader(shard);
2152 final TestActorRef<MessageCollectorActor> listener =
2153 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2155 shard.tell(new RegisterRoleChangeListener(), listener);
2157 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2159 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2160 ShardLeaderStateChanged.class);
2161 assertEquals("getLocalShardDataTree present", true,
2162 leaderStateChanged.getLocalShardDataTree().isPresent());
2163 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2164 leaderStateChanged.getLocalShardDataTree().get());
2166 MessageCollectorActor.clearMessages(listener);
2168 // Force a leader change
2170 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2172 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2173 ShardLeaderStateChanged.class);
2174 assertEquals("getLocalShardDataTree present", false,
2175 leaderStateChanged.getLocalShardDataTree().isPresent());
2181 public void testFollowerInitialSyncStatus() throws Exception {
2182 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2183 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2184 "testFollowerInitialSyncStatus");
2186 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false,
2187 "member-1-shard-inventory-operational"));
2189 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2191 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true,
2192 "member-1-shard-inventory-operational"));
2194 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2198 public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
2199 new ShardTestKit(getSystem()) {
2201 final String testName = "testClusteredDataChangeListenerDelayedRegistration";
2202 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2203 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2205 final MockDataChangeListener listener = new MockDataChangeListener(1);
2206 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2207 actorFactory.generateActorId(testName + "-DataChangeListener"));
2209 setupInMemorySnapshotStore();
2211 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2212 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2213 actorFactory.generateActorId(testName + "-shard"));
2215 waitUntilNoLeader(shard);
2217 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2219 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true),
2221 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2222 RegisterChangeListenerReply.class);
2223 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2225 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2226 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2228 listener.waitForChangeEvents();
2234 public void testClusteredDataChangeListenerRegistration() throws Exception {
2235 new ShardTestKit(getSystem()) {
2237 final String testName = "testClusteredDataChangeListenerRegistration";
2238 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2239 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2241 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2242 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2244 final TestActorRef<Shard> followerShard = actorFactory
2245 .createTestActor(Shard.builder().id(followerShardID)
2246 .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
2247 .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2248 "akka://test/user/" + leaderShardID.toString()))
2249 .schemaContext(SCHEMA_CONTEXT).props()
2250 .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2252 final TestActorRef<Shard> leaderShard = actorFactory
2253 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
2254 .peerAddresses(Collections.singletonMap(followerShardID.toString(),
2255 "akka://test/user/" + followerShardID.toString()))
2256 .schemaContext(SCHEMA_CONTEXT).props()
2257 .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2259 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2260 final String leaderPath = waitUntilLeader(followerShard);
2261 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2263 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2264 final MockDataChangeListener listener = new MockDataChangeListener(1);
2265 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
2266 actorFactory.generateActorId(testName + "-DataChangeListener"));
2269 new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true),
2271 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2272 RegisterChangeListenerReply.class);
2273 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2275 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2277 listener.waitForChangeEvents();
2283 public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
2284 new ShardTestKit(getSystem()) {
2286 final String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
2287 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2288 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2290 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2291 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2292 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2294 setupInMemorySnapshotStore();
2296 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2297 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2298 actorFactory.generateActorId(testName + "-shard"));
2300 waitUntilNoLeader(shard);
2302 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2303 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2304 RegisterDataTreeChangeListenerReply.class);
2305 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2307 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2308 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2310 listener.waitForChangeEvents();
2316 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2317 new ShardTestKit(getSystem()) {
2319 final String testName = "testClusteredDataTreeChangeListenerRegistration";
2320 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2321 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2323 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2324 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2326 final TestActorRef<Shard> followerShard = actorFactory
2327 .createTestActor(Shard.builder().id(followerShardID)
2328 .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
2329 .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2330 "akka://test/user/" + leaderShardID.toString()))
2331 .schemaContext(SCHEMA_CONTEXT).props()
2332 .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2334 final TestActorRef<Shard> leaderShard = actorFactory
2335 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
2336 .peerAddresses(Collections.singletonMap(followerShardID.toString(),
2337 "akka://test/user/" + followerShardID.toString()))
2338 .schemaContext(SCHEMA_CONTEXT).props()
2339 .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2341 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2342 final String leaderPath = waitUntilLeader(followerShard);
2343 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2345 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2346 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2347 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
2348 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2350 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2351 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2352 RegisterDataTreeChangeListenerReply.class);
2353 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2355 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2357 listener.waitForChangeEvents();
2363 public void testServerRemoved() throws Exception {
2364 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2366 final ActorRef shard = parent.underlyingActor().context().actorOf(
2367 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2368 "testServerRemoved");
2370 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2372 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);