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.util.concurrent.Uninterruptibles;
37 import java.io.IOException;
38 import java.util.Collections;
39 import java.util.HashSet;
42 import java.util.concurrent.CountDownLatch;
43 import java.util.concurrent.TimeUnit;
44 import java.util.concurrent.atomic.AtomicBoolean;
45 import java.util.concurrent.atomic.AtomicReference;
46 import org.junit.Test;
47 import org.mockito.InOrder;
48 import org.opendaylight.controller.cluster.DataPersistenceProvider;
49 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
50 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
51 import org.opendaylight.controller.cluster.access.concepts.MemberName;
52 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
53 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
54 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
55 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
56 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
57 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
58 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
59 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
60 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
61 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
62 import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistration;
63 import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistrationReply;
64 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
65 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
68 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
70 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
71 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
73 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
74 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
76 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListenerReply;
77 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
78 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
79 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
80 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
81 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
82 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
83 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
84 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
85 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
86 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
87 import org.opendaylight.controller.cluster.raft.RaftActorContext;
88 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
89 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
90 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
91 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
92 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
93 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
94 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
95 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
96 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
97 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
98 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
99 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
100 import org.opendaylight.controller.cluster.raft.persisted.SimpleReplicatedLogEntry;
101 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
102 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
103 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
104 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
105 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
106 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
107 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
108 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
109 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
110 import org.opendaylight.yangtools.concepts.Identifier;
111 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
112 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
117 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
118 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
119 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
120 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
121 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
122 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
123 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
124 import scala.concurrent.Await;
125 import scala.concurrent.Future;
126 import scala.concurrent.duration.FiniteDuration;
128 public class ShardTest extends AbstractShardTest {
129 private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in "
130 + "InMemorySnapshotStore and journal recovery seq number will start from 1";
133 public void testRegisterChangeListener() throws Exception {
134 new ShardTestKit(getSystem()) {
136 final TestActorRef<Shard> shard = actorFactory.createTestActor(
137 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
138 "testRegisterChangeListener");
140 waitUntilLeader(shard);
142 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
144 final MockDataChangeListener listener = new MockDataChangeListener(1);
145 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener,
146 TestModel.TEST_PATH), "testRegisterChangeListener-DataChangeListener");
148 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH, dclActor,
149 AsyncDataBroker.DataChangeScope.BASE, true), getRef());
151 final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
152 RegisterChangeListenerReply.class);
153 final String replyPath = reply.getListenerRegistrationPath().toString();
154 assertTrue("Incorrect reply path: " + replyPath,
155 replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
157 final YangInstanceIdentifier path = TestModel.TEST_PATH;
158 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
160 listener.waitForChangeEvents(path);
165 @SuppressWarnings("serial")
167 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
168 // This test tests the timing window in which a change listener is registered before the
169 // shard becomes the leader. We verify that the listener is registered and notified of the
170 // existing data when the shard becomes the leader.
171 // For this test, we want to send the RegisterChangeListener message after the shard
172 // has recovered from persistence and before it becomes the leader. So we subclass
173 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
174 // we know that the shard has been initialized to a follower and has started the
175 // election process. The following 2 CountDownLatches are used to coordinate the
176 // ElectionTimeout with the sending of the RegisterChangeListener message.
177 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
178 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
179 final Creator<Shard> creator = new Creator<Shard>() {
180 boolean firstElectionTimeout = true;
183 public Shard create() throws Exception {
184 // Use a non persistent provider because this test actually invokes persist on the journal
185 // this will cause all other messages to not be queued properly after that.
186 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
187 // it does do a persist)
188 return new Shard(newShardBuilder()) {
190 public void handleCommand(final Object message) {
191 if (message instanceof ElectionTimeout && firstElectionTimeout) {
192 // Got the first ElectionTimeout. We don't forward it to the
193 // base Shard yet until we've sent the RegisterChangeListener
194 // message. So we signal the onFirstElectionTimeout latch to tell
195 // the main thread to send the RegisterChangeListener message and
196 // start a thread to wait on the onChangeListenerRegistered latch,
197 // which the main thread signals after it has sent the message.
198 // After the onChangeListenerRegistered is triggered, we send the
199 // original ElectionTimeout message to proceed with the election.
200 firstElectionTimeout = false;
201 final ActorRef self = getSelf();
205 Uninterruptibles.awaitUninterruptibly(
206 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
207 self.tell(message, self);
211 onFirstElectionTimeout.countDown();
213 super.handleCommand(message);
220 setupInMemorySnapshotStore();
222 final YangInstanceIdentifier path = TestModel.TEST_PATH;
223 final MockDataChangeListener listener = new MockDataChangeListener(1);
224 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
225 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
227 final TestActorRef<Shard> shard = actorFactory.createTestActor(
228 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
229 "testRegisterChangeListenerWhenNotLeaderInitially");
231 new ShardTestKit(getSystem()) {
233 // Wait until the shard receives the first ElectionTimeout
235 assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
237 // Now send the RegisterChangeListener and wait for the reply.
238 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.SUBTREE, false),
241 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
242 RegisterChangeListenerReply.class);
243 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
245 // Sanity check - verify the shard is not the leader yet.
246 shard.tell(FindLeader.INSTANCE, getRef());
247 final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
248 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
250 // Signal the onChangeListenerRegistered latch to tell the
251 // thread above to proceed
252 // with the election process.
253 onChangeListenerRegistered.countDown();
255 // Wait for the shard to become the leader and notify our
256 // listener with the existing
257 // data in the store.
258 listener.waitForChangeEvents(path);
264 public void testRegisterDataTreeChangeListener() throws Exception {
265 new ShardTestKit(getSystem()) {
267 final TestActorRef<Shard> shard = actorFactory.createTestActor(
268 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
269 "testRegisterDataTreeChangeListener");
271 waitUntilLeader(shard);
273 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
275 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
276 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
277 TestModel.TEST_PATH), "testRegisterDataTreeChangeListener-DataTreeChangeListener");
279 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
281 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
282 RegisterDataTreeChangeListenerReply.class);
283 final String replyPath = reply.getListenerRegistrationPath().toString();
284 assertTrue("Incorrect reply path: " + replyPath,
285 replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
287 final YangInstanceIdentifier path = TestModel.TEST_PATH;
288 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
290 listener.waitForChangeEvents();
295 @SuppressWarnings("serial")
297 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
298 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
299 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
300 final Creator<Shard> creator = new Creator<Shard>() {
301 boolean firstElectionTimeout = true;
304 public Shard create() throws Exception {
305 return new Shard(newShardBuilder()) {
307 public void handleCommand(final Object message) {
308 if (message instanceof ElectionTimeout && firstElectionTimeout) {
309 firstElectionTimeout = false;
310 final ActorRef self = getSelf();
314 Uninterruptibles.awaitUninterruptibly(
315 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
316 self.tell(message, self);
320 onFirstElectionTimeout.countDown();
322 super.handleCommand(message);
329 setupInMemorySnapshotStore();
331 final YangInstanceIdentifier path = TestModel.TEST_PATH;
332 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
333 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
334 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
336 final TestActorRef<Shard> shard = actorFactory.createTestActor(
337 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
338 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
340 new ShardTestKit(getSystem()) {
342 assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
344 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
345 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
346 RegisterDataTreeChangeListenerReply.class);
347 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
349 shard.tell(FindLeader.INSTANCE, getRef());
350 final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
351 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
353 onChangeListenerRegistered.countDown();
355 // TODO: investigate why we do not receive data chage events
356 listener.waitForChangeEvents();
362 public void testCreateTransaction() {
363 new ShardTestKit(getSystem()) {
365 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
367 waitUntilLeader(shard);
369 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
371 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
372 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
374 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
375 CreateTransactionReply.class);
377 final String path = reply.getTransactionPath().toString();
378 assertTrue("Unexpected transaction path " + path, path.startsWith(String.format(
379 "akka://test/user/testCreateTransaction/shard-%s-%s:ShardTransactionTest@0:",
380 shardID.getShardName(), shardID.getMemberName().getName())));
386 public void testCreateTransactionOnChain() {
387 new ShardTestKit(getSystem()) {
389 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
391 waitUntilLeader(shard);
393 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
394 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
396 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
397 CreateTransactionReply.class);
399 final String path = reply.getTransactionPath().toString();
400 assertTrue("Unexpected transaction path " + path, path.startsWith(String.format(
401 "akka://test/user/testCreateTransactionOnChain/shard-%s-%s:ShardTransactionTest@0:",
402 shardID.getShardName(), shardID.getMemberName().getName())));
408 public void testPeerAddressResolved() throws Exception {
409 new ShardTestKit(getSystem()) {
411 final ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"),
413 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder()
414 .peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null))
415 .props().withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
417 final String address = "akka://foobar";
418 shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
420 shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
421 final OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
422 assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
428 public void testApplySnapshot() throws Exception {
430 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps()
431 .withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplySnapshot");
433 ShardTestKit.waitUntilLeader(shard);
435 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
436 store.setSchemaContext(SCHEMA_CONTEXT);
438 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
439 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
440 .withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
441 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
443 writeToStore(store, TestModel.TEST_PATH, container);
445 final YangInstanceIdentifier root = YangInstanceIdentifier.EMPTY;
446 final NormalizedNode<?,?> expected = readStore(store, root);
448 final Snapshot snapshot = Snapshot.create(
449 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(expected)),
450 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4, -1, null, null);
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);
479 final DataTreeModification writeMod = store.takeSnapshot().newModification();
480 final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
481 writeMod.write(TestModel.TEST_PATH, node);
484 final TransactionIdentifier tx = nextTransactionId();
485 shard.underlyingActor().applyState(null, null, payloadForModification(store, writeMod, tx));
487 final Stopwatch sw = Stopwatch.createStarted();
488 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
489 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
491 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
492 if (actual != null) {
493 assertEquals("Applied state", node, actual);
498 fail("State was not applied");
502 public void testDataTreeCandidateRecovery() throws Exception {
503 // Set up the InMemorySnapshotStore.
504 final DataTree source = setupInMemorySnapshotStore();
506 final DataTreeModification writeMod = source.takeSnapshot().newModification();
507 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
509 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
511 // Set up the InMemoryJournal.
512 InMemoryJournal.addEntry(shardID.toString(), 1, new SimpleReplicatedLogEntry(0, 1,
513 payloadForModification(source, writeMod, nextTransactionId())));
515 final int nListEntries = 16;
516 final Set<Integer> listEntryKeys = new HashSet<>();
518 // Add some ModificationPayload entries
519 for (int i = 1; i <= nListEntries; i++) {
520 listEntryKeys.add(Integer.valueOf(i));
522 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
523 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
525 final DataTreeModification mod = source.takeSnapshot().newModification();
526 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
529 InMemoryJournal.addEntry(shardID.toString(), i + 1, new SimpleReplicatedLogEntry(i, 1,
530 payloadForModification(source, mod, nextTransactionId())));
533 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
534 new ApplyJournalEntries(nListEntries));
536 testRecovery(listEntryKeys);
540 @SuppressWarnings("checkstyle:IllegalCatch")
541 public void testConcurrentThreePhaseCommits() throws Exception {
542 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
543 final CountDownLatch commitLatch = new CountDownLatch(2);
545 final long timeoutSec = 5;
546 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
547 final Timeout timeout = new Timeout(duration);
549 final TestActorRef<Shard> shard = actorFactory.createTestActor(
550 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
551 "testConcurrentThreePhaseCommits");
553 class OnFutureComplete extends OnComplete<Object> {
554 private final Class<?> expRespType;
556 OnFutureComplete(final Class<?> expRespType) {
557 this.expRespType = expRespType;
561 public void onComplete(final Throwable error, final Object resp) {
563 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
566 assertEquals("Commit response type", expRespType, resp.getClass());
568 } catch (final Exception e) {
574 void onSuccess(final Object resp) throws Exception {
578 class OnCommitFutureComplete extends OnFutureComplete {
579 OnCommitFutureComplete() {
580 super(CommitTransactionReply.class);
584 public void onComplete(final Throwable error, final Object resp) {
585 super.onComplete(error, resp);
586 commitLatch.countDown();
590 class OnCanCommitFutureComplete extends OnFutureComplete {
591 private final TransactionIdentifier transactionID;
593 OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
594 super(CanCommitTransactionReply.class);
595 this.transactionID = transactionID;
599 void onSuccess(final Object resp) throws Exception {
600 final CanCommitTransactionReply canCommitReply =
601 CanCommitTransactionReply.fromSerializable(resp);
602 assertEquals("Can commit", true, canCommitReply.getCanCommit());
604 final Future<Object> commitFuture = Patterns.ask(shard,
605 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
606 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
610 new ShardTestKit(getSystem()) {
612 waitUntilLeader(shard);
614 final TransactionIdentifier transactionID1 = nextTransactionId();
615 final TransactionIdentifier transactionID2 = nextTransactionId();
616 final TransactionIdentifier transactionID3 = nextTransactionId();
618 final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
619 shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
620 final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
621 final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
622 final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
624 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
625 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
626 final ReadyTransactionReply readyReply = ReadyTransactionReply
627 .fromSerializable(expectMsgClass(duration, ReadyTransactionReply.class));
628 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
629 // Send the CanCommitTransaction message for the first Tx.
631 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
632 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
633 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
634 assertEquals("Can commit", true, canCommitReply.getCanCommit());
636 // Ready 2 more Tx's.
638 shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
639 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
640 expectMsgClass(duration, ReadyTransactionReply.class);
643 prepareBatchedModifications(transactionID3,
644 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
645 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
646 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
648 expectMsgClass(duration, ReadyTransactionReply.class);
650 // Send the CanCommitTransaction message for the next 2 Tx's.
651 // These should get queued and
652 // processed after the first Tx completes.
654 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
655 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
657 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
658 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
660 // Send the CommitTransaction message for the first Tx. After it
661 // completes, it should
662 // trigger the 2nd Tx to proceed which should in turn then
665 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
666 expectMsgClass(duration, CommitTransactionReply.class);
668 // Wait for the next 2 Tx's to complete.
670 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2), getSystem().dispatcher());
672 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3), getSystem().dispatcher());
674 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
676 if (caughtEx.get() != null) {
677 Throwables.propagateIfInstanceOf(caughtEx.get(), Exception.class);
678 Throwables.propagate(caughtEx.get());
681 assertEquals("Commits complete", true, done);
683 // final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
684 // cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
685 // cohort3.getPreCommit(), cohort3.getCommit());
686 // inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
687 // inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
688 // inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
689 // inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
690 // inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
691 // inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
692 // inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
693 // inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
694 // inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
696 // Verify data in the data store.
698 verifyOuterListEntry(shard, 1);
700 verifyLastApplied(shard, 5);
706 public void testBatchedModificationsWithNoCommitOnReady() throws Exception {
707 new ShardTestKit(getSystem()) {
709 final TestActorRef<Shard> shard = actorFactory.createTestActor(
710 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
711 "testBatchedModificationsWithNoCommitOnReady");
713 waitUntilLeader(shard);
715 final TransactionIdentifier transactionID = nextTransactionId();
716 final FiniteDuration duration = duration("5 seconds");
718 // Send a BatchedModifications to start a transaction.
720 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
721 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
722 expectMsgClass(duration, BatchedModificationsReply.class);
724 // Send a couple more BatchedModifications.
727 newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
728 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
730 expectMsgClass(duration, BatchedModificationsReply.class);
732 shard.tell(newBatchedModifications(transactionID,
733 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
734 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
735 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3),
737 expectMsgClass(duration, ReadyTransactionReply.class);
739 // Send the CanCommitTransaction message.
741 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
742 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
743 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
744 assertEquals("Can commit", true, canCommitReply.getCanCommit());
746 // Send the CommitTransaction message.
748 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
749 expectMsgClass(duration, CommitTransactionReply.class);
751 // Verify data in the data store.
753 verifyOuterListEntry(shard, 1);
759 public void testBatchedModificationsWithCommitOnReady() throws Exception {
760 new ShardTestKit(getSystem()) {
762 final TestActorRef<Shard> shard = actorFactory.createTestActor(
763 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
764 "testBatchedModificationsWithCommitOnReady");
766 waitUntilLeader(shard);
768 final TransactionIdentifier transactionID = nextTransactionId();
769 final FiniteDuration duration = duration("5 seconds");
771 // Send a BatchedModifications to start a transaction.
773 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
774 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
775 expectMsgClass(duration, BatchedModificationsReply.class);
777 // Send a couple more BatchedModifications.
779 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
780 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
782 expectMsgClass(duration, BatchedModificationsReply.class);
784 shard.tell(newBatchedModifications(transactionID,
785 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
786 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
787 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3),
790 expectMsgClass(duration, CommitTransactionReply.class);
792 // Verify data in the data store.
794 verifyOuterListEntry(shard, 1);
799 @Test(expected = IllegalStateException.class)
800 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
801 new ShardTestKit(getSystem()) {
803 final TestActorRef<Shard> shard = actorFactory.createTestActor(
804 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
805 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
807 waitUntilLeader(shard);
809 final TransactionIdentifier transactionID = nextTransactionId();
810 final BatchedModifications batched = new BatchedModifications(transactionID,
811 DataStoreVersions.CURRENT_VERSION);
812 batched.setReady(true);
813 batched.setTotalMessagesSent(2);
815 shard.tell(batched, getRef());
817 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
819 if (failure != null) {
820 Throwables.propagateIfInstanceOf(failure.cause(), Exception.class);
821 Throwables.propagate(failure.cause());
828 public void testBatchedModificationsWithOperationFailure() throws Exception {
829 new ShardTestKit(getSystem()) {
831 final TestActorRef<Shard> shard = actorFactory.createTestActor(
832 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
833 "testBatchedModificationsWithOperationFailure");
835 waitUntilLeader(shard);
837 // Test merge with invalid data. An exception should occur when
838 // the merge is applied. Note that
839 // write will not validate the children for performance reasons.
841 final TransactionIdentifier transactionID = nextTransactionId();
843 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
844 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
845 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
847 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
848 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
849 shard.tell(batched, getRef());
850 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
852 final Throwable cause = failure.cause();
854 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
855 batched.setReady(true);
856 batched.setTotalMessagesSent(2);
858 shard.tell(batched, getRef());
860 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
861 assertEquals("Failure cause", cause, failure.cause());
867 public void testBatchedModificationsOnTransactionChain() throws Exception {
868 new ShardTestKit(getSystem()) {
870 final TestActorRef<Shard> shard = actorFactory.createTestActor(
871 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
872 "testBatchedModificationsOnTransactionChain");
874 waitUntilLeader(shard);
876 final LocalHistoryIdentifier historyId = nextHistoryId();
877 final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
878 final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
880 final FiniteDuration duration = duration("5 seconds");
882 // Send a BatchedModifications to start a chained write
883 // transaction and ready it.
885 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
886 final YangInstanceIdentifier path = TestModel.TEST_PATH;
887 shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
888 expectMsgClass(duration, ReadyTransactionReply.class);
890 // Create a read Tx on the same chain.
892 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
893 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
895 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"),
896 CreateTransactionReply.class);
898 getSystem().actorSelection(createReply.getTransactionPath())
899 .tell(new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
900 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
901 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
903 // Commit the write transaction.
905 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
906 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
907 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
908 assertEquals("Can commit", true, canCommitReply.getCanCommit());
910 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
911 expectMsgClass(duration, CommitTransactionReply.class);
913 // Verify data in the data store.
915 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
916 assertEquals("Stored node", containerNode, actualNode);
922 public void testOnBatchedModificationsWhenNotLeader() {
923 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
924 new ShardTestKit(getSystem()) {
926 final Creator<Shard> creator = new Creator<Shard>() {
927 private static final long serialVersionUID = 1L;
930 public Shard create() throws Exception {
931 return new Shard(newShardBuilder()) {
933 protected boolean isLeader() {
934 return overrideLeaderCalls.get() ? false : super.isLeader();
938 public ActorSelection getLeader() {
939 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path())
946 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
947 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
948 "testOnBatchedModificationsWhenNotLeader");
950 waitUntilLeader(shard);
952 overrideLeaderCalls.set(true);
954 final BatchedModifications batched = new BatchedModifications(nextTransactionId(),
955 DataStoreVersions.CURRENT_VERSION);
957 shard.tell(batched, ActorRef.noSender());
959 expectMsgEquals(batched);
965 public void testTransactionMessagesWithNoLeader() {
966 new ShardTestKit(getSystem()) {
968 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
969 .shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
970 final TestActorRef<Shard> shard = actorFactory.createTestActor(
971 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
972 "testTransactionMessagesWithNoLeader");
974 waitUntilNoLeader(shard);
976 final TransactionIdentifier txId = nextTransactionId();
977 shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
978 Failure failure = expectMsgClass(Failure.class);
979 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
981 shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
982 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
983 failure = expectMsgClass(Failure.class);
984 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
986 shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
987 failure = expectMsgClass(Failure.class);
988 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
994 public void testReadyWithReadWriteImmediateCommit() throws Exception {
995 testReadyWithImmediateCommit(true);
999 public void testReadyWithWriteOnlyImmediateCommit() throws Exception {
1000 testReadyWithImmediateCommit(false);
1003 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception {
1004 new ShardTestKit(getSystem()) {
1006 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1007 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1008 "testReadyWithImmediateCommit-" + readWrite);
1010 waitUntilLeader(shard);
1012 final TransactionIdentifier transactionID = nextTransactionId();
1013 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1015 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1016 containerNode, true), getRef());
1018 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true),
1022 expectMsgClass(duration("5 seconds"), CommitTransactionReply.class);
1024 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1025 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1031 public void testReadyLocalTransactionWithImmediateCommit() throws Exception {
1032 new ShardTestKit(getSystem()) {
1034 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1035 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1036 "testReadyLocalTransactionWithImmediateCommit");
1038 waitUntilLeader(shard);
1040 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1042 final DataTreeModification modification = dataStore.newModification();
1044 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1045 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1046 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1047 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1049 final TransactionIdentifier txId = nextTransactionId();
1050 modification.ready();
1051 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1053 shard.tell(readyMessage, getRef());
1055 expectMsgClass(CommitTransactionReply.class);
1057 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1058 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1064 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception {
1065 new ShardTestKit(getSystem()) {
1067 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1068 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1069 "testReadyLocalTransactionWithThreePhaseCommit");
1071 waitUntilLeader(shard);
1073 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1075 final DataTreeModification modification = dataStore.newModification();
1077 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1078 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1079 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1080 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1082 final TransactionIdentifier txId = nextTransactionId();
1083 modification.ready();
1084 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1086 shard.tell(readyMessage, getRef());
1088 expectMsgClass(ReadyTransactionReply.class);
1090 // Send the CanCommitTransaction message.
1092 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1093 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1094 .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
1095 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1097 // Send the CanCommitTransaction message.
1099 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1100 expectMsgClass(CommitTransactionReply.class);
1102 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1103 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1109 public void testReadWriteCommitWithPersistenceDisabled() throws Exception {
1110 dataStoreContextBuilder.persistent(false);
1111 new ShardTestKit(getSystem()) {
1113 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1114 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1115 "testCommitWithPersistenceDisabled");
1117 waitUntilLeader(shard);
1119 // Setup a simulated transactions with a mock cohort.
1121 final FiniteDuration duration = duration("5 seconds");
1123 final TransactionIdentifier transactionID = nextTransactionId();
1124 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1125 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false),
1127 expectMsgClass(duration, ReadyTransactionReply.class);
1129 // Send the CanCommitTransaction message.
1131 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1132 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1133 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1134 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1136 // Send the CanCommitTransaction message.
1138 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1139 expectMsgClass(duration, CommitTransactionReply.class);
1141 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1142 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1148 public void testReadWriteCommitWhenTransactionHasModifications() throws Exception {
1149 testCommitWhenTransactionHasModifications(true);
1153 public void testWriteOnlyCommitWhenTransactionHasModifications() throws Exception {
1154 testCommitWhenTransactionHasModifications(false);
1157 private void testCommitWhenTransactionHasModifications(final boolean readWrite) throws Exception {
1158 new ShardTestKit(getSystem()) {
1160 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1161 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1162 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1163 "testCommitWhenTransactionHasModifications-" + readWrite);
1165 waitUntilLeader(shard);
1167 final FiniteDuration duration = duration("5 seconds");
1168 final TransactionIdentifier transactionID = nextTransactionId();
1171 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1172 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1174 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1175 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1178 expectMsgClass(duration, ReadyTransactionReply.class);
1180 // Send the CanCommitTransaction message.
1182 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1183 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1184 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1185 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1187 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1188 expectMsgClass(duration, CommitTransactionReply.class);
1190 final InOrder inOrder = inOrder(dataTree);
1191 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1192 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1193 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1195 // Purge request is scheduled as asynchronous, wait for two heartbeats to let it propagate into
1197 Thread.sleep(HEARTBEAT_MILLIS * 2);
1199 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1200 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1202 // Use MBean for verification
1203 // Committed transaction count should increase as usual
1204 assertEquals(1, shardStats.getCommittedTransactionsCount());
1206 // Commit index should advance as we do not have an empty
1208 assertEquals(1, shardStats.getCommitIndex());
1214 public void testCommitPhaseFailure() throws Exception {
1215 new ShardTestKit(getSystem()) {
1217 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1218 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1219 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1220 "testCommitPhaseFailure");
1222 waitUntilLeader(shard);
1224 final FiniteDuration duration = duration("5 seconds");
1225 final Timeout timeout = new Timeout(duration);
1227 // Setup 2 simulated transactions with mock cohorts. The first
1231 doThrow(new RuntimeException("mock commit failure")).when(dataTree)
1232 .commit(any(DataTreeCandidate.class));
1234 final TransactionIdentifier transactionID1 = nextTransactionId();
1235 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1236 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1237 expectMsgClass(duration, ReadyTransactionReply.class);
1239 final TransactionIdentifier transactionID2 = nextTransactionId();
1240 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1241 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1242 expectMsgClass(duration, ReadyTransactionReply.class);
1244 // Send the CanCommitTransaction message for the first Tx.
1246 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1247 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1248 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1249 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1251 // Send the CanCommitTransaction message for the 2nd Tx. This
1252 // should get queued and
1253 // processed after the first Tx completes.
1255 final Future<Object> canCommitFuture = Patterns.ask(shard,
1256 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1258 // Send the CommitTransaction message for the first Tx. This
1259 // should send back an error
1260 // and trigger the 2nd Tx to proceed.
1262 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1263 expectMsgClass(duration, akka.actor.Status.Failure.class);
1265 // Wait for the 2nd Tx to complete the canCommit phase.
1267 final CountDownLatch latch = new CountDownLatch(1);
1268 canCommitFuture.onComplete(new OnComplete<Object>() {
1270 public void onComplete(final Throwable failure, final Object resp) {
1273 }, getSystem().dispatcher());
1275 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1277 final InOrder inOrder = inOrder(dataTree);
1278 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1279 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1281 // FIXME: this invocation is done on the result of validate(). To test it, we need to make sure mock
1282 // validate performs wrapping and we capture that mock
1283 // inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1285 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1291 public void testPreCommitPhaseFailure() throws Exception {
1292 new ShardTestKit(getSystem()) {
1294 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1295 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1296 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1297 "testPreCommitPhaseFailure");
1299 waitUntilLeader(shard);
1301 final FiniteDuration duration = duration("5 seconds");
1302 final Timeout timeout = new Timeout(duration);
1304 doThrow(new RuntimeException("mock preCommit failure")).when(dataTree)
1305 .prepare(any(DataTreeModification.class));
1307 final TransactionIdentifier transactionID1 = nextTransactionId();
1308 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1309 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1310 expectMsgClass(duration, ReadyTransactionReply.class);
1312 final TransactionIdentifier transactionID2 = nextTransactionId();
1313 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1314 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1315 expectMsgClass(duration, ReadyTransactionReply.class);
1317 // Send the CanCommitTransaction message for the first Tx.
1319 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1320 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1321 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1322 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1324 // Send the CanCommitTransaction message for the 2nd Tx. This
1325 // should get queued and
1326 // processed after the first Tx completes.
1328 final Future<Object> canCommitFuture = Patterns.ask(shard,
1329 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1331 // Send the CommitTransaction message for the first Tx. This
1332 // should send back an error
1333 // and trigger the 2nd Tx to proceed.
1335 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1336 expectMsgClass(duration, akka.actor.Status.Failure.class);
1338 // Wait for the 2nd Tx to complete the canCommit phase.
1340 final CountDownLatch latch = new CountDownLatch(1);
1341 canCommitFuture.onComplete(new OnComplete<Object>() {
1343 public void onComplete(final Throwable failure, final Object resp) {
1346 }, getSystem().dispatcher());
1348 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1350 final InOrder inOrder = inOrder(dataTree);
1351 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1352 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1353 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1359 public void testCanCommitPhaseFailure() 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 "testCanCommitPhaseFailure");
1367 waitUntilLeader(shard);
1369 final FiniteDuration duration = duration("5 seconds");
1370 final TransactionIdentifier transactionID1 = nextTransactionId();
1372 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1373 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1375 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1376 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1377 expectMsgClass(duration, ReadyTransactionReply.class);
1379 // Send the CanCommitTransaction message.
1381 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1382 expectMsgClass(duration, akka.actor.Status.Failure.class);
1384 // Send another can commit to ensure the failed one got cleaned
1387 final TransactionIdentifier transactionID2 = nextTransactionId();
1388 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1389 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1390 expectMsgClass(duration, ReadyTransactionReply.class);
1392 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1393 final CanCommitTransactionReply reply = CanCommitTransactionReply
1394 .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
1395 assertEquals("getCanCommit", true, reply.getCanCommit());
1401 public void testImmediateCommitWithCanCommitPhaseFailure() throws Exception {
1402 testImmediateCommitWithCanCommitPhaseFailure(true);
1403 testImmediateCommitWithCanCommitPhaseFailure(false);
1406 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Exception {
1407 new ShardTestKit(getSystem()) {
1409 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1410 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1411 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1412 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1414 waitUntilLeader(shard);
1416 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1417 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1419 final FiniteDuration duration = duration("5 seconds");
1421 final TransactionIdentifier transactionID1 = nextTransactionId();
1424 shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
1425 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1427 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1428 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1431 expectMsgClass(duration, akka.actor.Status.Failure.class);
1433 // Send another can commit to ensure the failed one got cleaned
1436 final TransactionIdentifier transactionID2 = nextTransactionId();
1438 shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
1439 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1441 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1442 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1445 expectMsgClass(duration, CommitTransactionReply.class);
1451 public void testAbortWithCommitPending() throws Exception {
1452 new ShardTestKit(getSystem()) {
1454 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
1456 void persistPayload(final Identifier id, final Payload payload,
1457 final boolean batchHint) {
1458 // Simulate an AbortTransaction message occurring during
1459 // replication, after
1460 // persisting and before finishing the commit to the
1463 doAbortTransaction(id, null);
1464 super.persistPayload(id, payload, batchHint);
1468 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1469 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1470 "testAbortWithCommitPending");
1472 waitUntilLeader(shard);
1474 final FiniteDuration duration = duration("5 seconds");
1476 final TransactionIdentifier transactionID = nextTransactionId();
1478 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1479 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1480 expectMsgClass(duration, ReadyTransactionReply.class);
1482 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1483 expectMsgClass(duration, CanCommitTransactionReply.class);
1485 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1486 expectMsgClass(duration, CommitTransactionReply.class);
1488 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1490 // Since we're simulating an abort occurring during replication
1491 // and before finish commit,
1492 // the data should still get written to the in-memory store
1493 // since we've gotten past
1494 // canCommit and preCommit and persisted the data.
1495 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1501 public void testTransactionCommitTimeout() throws Exception {
1502 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1503 new ShardTestKit(getSystem()) {
1505 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1506 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1507 "testTransactionCommitTimeout");
1509 waitUntilLeader(shard);
1511 final FiniteDuration duration = duration("5 seconds");
1513 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1514 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1515 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1517 // Ready 2 Tx's - the first will timeout
1519 final TransactionIdentifier transactionID1 = nextTransactionId();
1521 prepareBatchedModifications(transactionID1,
1522 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1523 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1524 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
1526 expectMsgClass(duration, ReadyTransactionReply.class);
1528 final TransactionIdentifier transactionID2 = nextTransactionId();
1529 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1530 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1532 prepareBatchedModifications(transactionID2, listNodePath,
1533 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false),
1535 expectMsgClass(duration, ReadyTransactionReply.class);
1537 // canCommit 1st Tx. We don't send the commit so it should
1540 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1541 expectMsgClass(duration, CanCommitTransactionReply.class);
1543 // canCommit the 2nd Tx - it should complete after the 1st Tx
1546 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1547 expectMsgClass(duration, CanCommitTransactionReply.class);
1549 // Try to commit the 1st Tx - should fail as it's not the
1552 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1553 expectMsgClass(duration, akka.actor.Status.Failure.class);
1555 // Commit the 2nd Tx.
1557 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1558 expectMsgClass(duration, CommitTransactionReply.class);
1560 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1561 assertNotNull(listNodePath + " not found", node);
1568 // public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1569 // dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1571 // new ShardTestKit(getSystem()) {{
1572 // final TestActorRef<Shard> shard = actorFactory.createTestActor(
1573 // newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1574 // "testTransactionCommitQueueCapacityExceeded");
1576 // waitUntilLeader(shard);
1578 // final FiniteDuration duration = duration("5 seconds");
1580 // final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1582 // final TransactionIdentifier transactionID1 = nextTransactionId();
1583 // final MutableCompositeModification modification1 = new MutableCompositeModification();
1584 // final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1585 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID1,
1588 // final TransactionIdentifier transactionID2 = nextTransactionId();
1589 // final MutableCompositeModification modification2 = new MutableCompositeModification();
1590 // final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1591 // TestModel.OUTER_LIST_PATH,
1592 // ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), transactionID2,
1595 // final TransactionIdentifier transactionID3 = nextTransactionId();
1596 // final MutableCompositeModification modification3 = new MutableCompositeModification();
1597 // final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1598 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID3,
1601 // // Ready the Tx's
1603 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1,
1604 // modification1), getRef());
1605 // expectMsgClass(duration, ReadyTransactionReply.class);
1607 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2,
1608 // modification2), getRef());
1609 // expectMsgClass(duration, ReadyTransactionReply.class);
1611 // // The 3rd Tx should exceed queue capacity and fail.
1613 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3,
1614 // modification3), getRef());
1615 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1617 // // canCommit 1st Tx.
1619 // shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1620 // expectMsgClass(duration, CanCommitTransactionReply.class);
1622 // // canCommit the 2nd Tx - it should get queued.
1624 // shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1626 // // canCommit the 3rd Tx - should exceed queue capacity and fail.
1628 // shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1629 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1634 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Exception {
1635 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1636 new ShardTestKit(getSystem()) {
1638 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1639 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1640 "testTransactionCommitWithPriorExpiredCohortEntries");
1642 waitUntilLeader(shard);
1644 final FiniteDuration duration = duration("5 seconds");
1646 final TransactionIdentifier transactionID1 = nextTransactionId();
1647 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1648 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1649 expectMsgClass(duration, ReadyTransactionReply.class);
1651 final TransactionIdentifier transactionID2 = nextTransactionId();
1652 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1653 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1654 expectMsgClass(duration, ReadyTransactionReply.class);
1656 final TransactionIdentifier transactionID3 = nextTransactionId();
1657 shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1658 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1659 expectMsgClass(duration, ReadyTransactionReply.class);
1661 // All Tx's are readied. We'll send canCommit for the last one
1662 // but not the others. The others
1663 // should expire from the queue and the last one should be
1666 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1667 expectMsgClass(duration, CanCommitTransactionReply.class);
1673 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Exception {
1674 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1675 new ShardTestKit(getSystem()) {
1677 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1678 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1679 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1681 waitUntilLeader(shard);
1683 final FiniteDuration duration = duration("5 seconds");
1685 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1687 final TransactionIdentifier transactionID1 = nextTransactionId();
1688 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1689 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1690 expectMsgClass(duration, ReadyTransactionReply.class);
1692 // CanCommit the first Tx so it's the current in-progress Tx.
1694 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1695 expectMsgClass(duration, CanCommitTransactionReply.class);
1697 // Ready the second Tx.
1699 final TransactionIdentifier transactionID2 = nextTransactionId();
1700 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1701 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1702 expectMsgClass(duration, ReadyTransactionReply.class);
1704 // Ready the third Tx.
1706 final TransactionIdentifier transactionID3 = nextTransactionId();
1707 final DataTreeModification modification3 = dataStore.newModification();
1708 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1709 .apply(modification3);
1710 modification3.ready();
1711 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3,
1713 shard.tell(readyMessage, getRef());
1715 // Commit the first Tx. After completing, the second should
1716 // expire from the queue and the third
1719 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1720 expectMsgClass(duration, CommitTransactionReply.class);
1722 // Expect commit reply from the third Tx.
1724 expectMsgClass(duration, CommitTransactionReply.class);
1726 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1727 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1733 public void testCanCommitBeforeReadyFailure() throws Exception {
1734 new ShardTestKit(getSystem()) {
1736 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1737 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1738 "testCanCommitBeforeReadyFailure");
1740 shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
1741 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1747 public void testAbortAfterCanCommit() throws Exception {
1748 new ShardTestKit(getSystem()) {
1750 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1751 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterCanCommit");
1753 waitUntilLeader(shard);
1755 final FiniteDuration duration = duration("5 seconds");
1756 final Timeout timeout = new Timeout(duration);
1758 // Ready 2 transactions - the first one will be aborted.
1760 final TransactionIdentifier transactionID1 = nextTransactionId();
1761 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1762 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1763 expectMsgClass(duration, ReadyTransactionReply.class);
1765 final TransactionIdentifier transactionID2 = nextTransactionId();
1766 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1767 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1768 expectMsgClass(duration, ReadyTransactionReply.class);
1770 // Send the CanCommitTransaction message for the first Tx.
1772 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1773 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1774 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1775 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1777 // Send the CanCommitTransaction message for the 2nd Tx. This
1778 // should get queued and
1779 // processed after the first Tx completes.
1781 final Future<Object> canCommitFuture = Patterns.ask(shard,
1782 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1784 // Send the AbortTransaction message for the first Tx. This
1785 // should trigger the 2nd
1788 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1789 expectMsgClass(duration, AbortTransactionReply.class);
1791 // Wait for the 2nd Tx to complete the canCommit phase.
1793 canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture, duration);
1794 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1800 public void testAbortAfterReady() throws Exception {
1801 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1802 new ShardTestKit(getSystem()) {
1804 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1805 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1807 waitUntilLeader(shard);
1809 final FiniteDuration duration = duration("5 seconds");
1813 final TransactionIdentifier transactionID1 = nextTransactionId();
1814 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1815 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1816 expectMsgClass(duration, ReadyTransactionReply.class);
1818 // Send the AbortTransaction message.
1820 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1821 expectMsgClass(duration, AbortTransactionReply.class);
1823 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1825 // Now send CanCommitTransaction - should fail.
1827 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1828 final Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
1829 assertTrue("Failure type", failure instanceof IllegalStateException);
1831 // Ready and CanCommit another and verify success.
1833 final TransactionIdentifier transactionID2 = nextTransactionId();
1834 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1835 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1836 expectMsgClass(duration, ReadyTransactionReply.class);
1838 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1839 expectMsgClass(duration, CanCommitTransactionReply.class);
1845 public void testAbortQueuedTransaction() throws Exception {
1846 new ShardTestKit(getSystem()) {
1848 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1849 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1851 waitUntilLeader(shard);
1853 final FiniteDuration duration = duration("5 seconds");
1857 final TransactionIdentifier transactionID1 = nextTransactionId();
1858 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1859 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1860 expectMsgClass(duration, ReadyTransactionReply.class);
1862 final TransactionIdentifier transactionID2 = nextTransactionId();
1863 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1864 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1865 expectMsgClass(duration, ReadyTransactionReply.class);
1867 final TransactionIdentifier transactionID3 = nextTransactionId();
1869 newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
1870 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1),
1872 expectMsgClass(duration, ReadyTransactionReply.class);
1874 // Abort the second tx while it's queued.
1876 shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1877 expectMsgClass(duration, AbortTransactionReply.class);
1879 // Commit the other 2.
1881 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1882 expectMsgClass(duration, CanCommitTransactionReply.class);
1884 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1885 expectMsgClass(duration, CommitTransactionReply.class);
1887 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1888 expectMsgClass(duration, CanCommitTransactionReply.class);
1890 shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1891 expectMsgClass(duration, CommitTransactionReply.class);
1893 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1899 public void testCreateSnapshotWithNonPersistentData() throws Exception {
1900 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1904 public void testCreateSnapshot() throws Exception {
1905 testCreateSnapshot(true, "testCreateSnapshot");
1908 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception {
1909 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1911 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1912 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
1913 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
1918 public void saveSnapshot(final Object obj) {
1919 savedSnapshot.set(obj);
1920 super.saveSnapshot(obj);
1924 dataStoreContextBuilder.persistent(persistent);
1926 class TestShard extends Shard {
1928 protected TestShard(final AbstractBuilder<?, ?> builder) {
1930 setPersistence(new TestPersistentDataProvider(super.persistence()));
1934 public void handleCommand(final Object message) {
1935 super.handleCommand(message);
1937 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
1938 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
1939 latch.get().countDown();
1944 public RaftActorContext getRaftActorContext() {
1945 return super.getRaftActorContext();
1949 new ShardTestKit(getSystem()) {
1951 final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
1953 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1954 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1957 waitUntilLeader(shard);
1958 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1960 final NormalizedNode<?, ?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
1962 // Trigger creation of a snapshot by ensuring
1963 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
1964 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1965 awaitAndValidateSnapshot(expectedRoot);
1967 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1968 awaitAndValidateSnapshot(expectedRoot);
1971 private void awaitAndValidateSnapshot(final NormalizedNode<?, ?> expectedRoot)
1972 throws InterruptedException, IOException {
1973 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1975 assertTrue("Invalid saved snapshot " + savedSnapshot.get(), savedSnapshot.get() instanceof Snapshot);
1977 verifySnapshot((Snapshot) savedSnapshot.get(), expectedRoot);
1979 latch.set(new CountDownLatch(1));
1980 savedSnapshot.set(null);
1983 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?, ?> expectedRoot)
1984 throws IOException {
1985 final NormalizedNode<?, ?> actual = ((ShardSnapshotState)snapshot.getState()).getSnapshot()
1986 .getRootNode().get();
1987 assertEquals("Root node", expectedRoot, actual);
1993 * This test simply verifies that the applySnapShot logic will work.
1996 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
1997 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
1998 store.setSchemaContext(SCHEMA_CONTEXT);
2000 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
2001 putTransaction.write(TestModel.TEST_PATH,
2002 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2003 commitTransaction(store, putTransaction);
2006 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
2008 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2010 writeTransaction.delete(YangInstanceIdentifier.EMPTY);
2011 writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
2013 commitTransaction(store, writeTransaction);
2015 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
2017 assertEquals(expected, actual);
2021 public void testRecoveryApplicable() {
2023 final DatastoreContext persistentContext = DatastoreContext.newBuilder()
2024 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2026 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext)
2027 .schemaContextProvider(() -> SCHEMA_CONTEXT).props();
2029 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder()
2030 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2032 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext)
2033 .schemaContextProvider(() -> SCHEMA_CONTEXT).props();
2035 new ShardTestKit(getSystem()) {
2037 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2039 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2041 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2043 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2049 public void testOnDatastoreContext() {
2050 new ShardTestKit(getSystem()) {
2052 dataStoreContextBuilder.persistent(true);
2054 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(),
2055 "testOnDatastoreContext");
2057 assertEquals("isRecoveryApplicable", true,
2058 shard.underlyingActor().persistence().isRecoveryApplicable());
2060 waitUntilLeader(shard);
2062 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2064 assertEquals("isRecoveryApplicable", false,
2065 shard.underlyingActor().persistence().isRecoveryApplicable());
2067 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2069 assertEquals("isRecoveryApplicable", true,
2070 shard.underlyingActor().persistence().isRecoveryApplicable());
2076 public void testRegisterRoleChangeListener() throws Exception {
2077 new ShardTestKit(getSystem()) {
2079 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2080 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2081 "testRegisterRoleChangeListener");
2083 waitUntilLeader(shard);
2085 final TestActorRef<MessageCollectorActor> listener =
2086 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2088 shard.tell(new RegisterRoleChangeListener(), listener);
2090 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2092 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2093 ShardLeaderStateChanged.class);
2094 assertEquals("getLocalShardDataTree present", true,
2095 leaderStateChanged.getLocalShardDataTree().isPresent());
2096 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2097 leaderStateChanged.getLocalShardDataTree().get());
2099 MessageCollectorActor.clearMessages(listener);
2101 // Force a leader change
2103 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2105 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2106 ShardLeaderStateChanged.class);
2107 assertEquals("getLocalShardDataTree present", false,
2108 leaderStateChanged.getLocalShardDataTree().isPresent());
2114 public void testFollowerInitialSyncStatus() throws Exception {
2115 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2116 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2117 "testFollowerInitialSyncStatus");
2119 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false,
2120 "member-1-shard-inventory-operational"));
2122 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2124 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true,
2125 "member-1-shard-inventory-operational"));
2127 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2131 public void testClusteredDataChangeListenerWithDelayedRegistration() throws Exception {
2132 new ShardTestKit(getSystem()) {
2134 final String testName = "testClusteredDataChangeListenerWithDelayedRegistration";
2135 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2136 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2138 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2139 final MockDataChangeListener listener = new MockDataChangeListener(1);
2140 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
2141 actorFactory.generateActorId(testName + "-DataChangeListener"));
2143 setupInMemorySnapshotStore();
2145 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2146 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2147 actorFactory.generateActorId(testName + "-shard"));
2149 waitUntilNoLeader(shard);
2151 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true),
2153 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2154 RegisterChangeListenerReply.class);
2155 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2157 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2158 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2160 listener.waitForChangeEvents();
2166 public void testClusteredDataChangeListenerRegistration() throws Exception {
2167 new ShardTestKit(getSystem()) {
2169 final String testName = "testClusteredDataChangeListenerRegistration";
2170 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2171 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2173 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2174 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2176 final TestActorRef<Shard> followerShard = actorFactory
2177 .createTestActor(Shard.builder().id(followerShardID)
2178 .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
2179 .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2180 "akka://test/user/" + leaderShardID.toString()))
2181 .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
2182 .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2184 final TestActorRef<Shard> leaderShard = actorFactory
2185 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
2186 .peerAddresses(Collections.singletonMap(followerShardID.toString(),
2187 "akka://test/user/" + followerShardID.toString()))
2188 .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
2189 .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2191 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2192 final String leaderPath = waitUntilLeader(followerShard);
2193 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2195 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2196 final MockDataChangeListener listener = new MockDataChangeListener(1);
2197 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
2198 actorFactory.generateActorId(testName + "-DataChangeListener"));
2201 new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true),
2203 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2204 RegisterChangeListenerReply.class);
2205 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2207 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2209 listener.waitForChangeEvents();
2215 public void testClusteredDataTreeChangeListenerWithDelayedRegistration() throws Exception {
2216 new ShardTestKit(getSystem()) {
2218 final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistration";
2219 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2220 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2222 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2223 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
2224 TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2226 setupInMemorySnapshotStore();
2228 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2229 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2230 actorFactory.generateActorId(testName + "-shard"));
2232 waitUntilNoLeader(shard);
2234 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2235 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2236 RegisterDataTreeChangeListenerReply.class);
2237 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2239 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2240 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2242 listener.waitForChangeEvents();
2248 public void testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed() throws Exception {
2249 new ShardTestKit(getSystem()) {
2251 final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed";
2252 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2253 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2255 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(0);
2256 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
2257 TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2259 setupInMemorySnapshotStore();
2261 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2262 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2263 actorFactory.generateActorId(testName + "-shard"));
2265 waitUntilNoLeader(shard);
2267 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2268 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2269 RegisterDataTreeChangeListenerReply.class);
2270 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2272 final ActorSelection regActor = getSystem().actorSelection(reply.getListenerRegistrationPath());
2273 regActor.tell(CloseDataTreeNotificationListenerRegistration.getInstance(), getRef());
2274 expectMsgClass(CloseDataTreeNotificationListenerRegistrationReply.class);
2276 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2277 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2279 listener.expectNoMoreChanges("Received unexpected change after close");
2285 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2286 new ShardTestKit(getSystem()) {
2288 final String testName = "testClusteredDataTreeChangeListenerRegistration";
2289 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2290 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2292 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2293 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2295 final TestActorRef<Shard> followerShard = actorFactory
2296 .createTestActor(Shard.builder().id(followerShardID)
2297 .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
2298 .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2299 "akka://test/user/" + leaderShardID.toString()))
2300 .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
2301 .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2303 final TestActorRef<Shard> leaderShard = actorFactory
2304 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
2305 .peerAddresses(Collections.singletonMap(followerShardID.toString(),
2306 "akka://test/user/" + followerShardID.toString()))
2307 .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
2308 .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2310 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2311 final String leaderPath = waitUntilLeader(followerShard);
2312 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2314 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2315 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2316 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
2317 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2319 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2320 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2321 RegisterDataTreeChangeListenerReply.class);
2322 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2324 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2326 listener.waitForChangeEvents();
2332 public void testServerRemoved() throws Exception {
2333 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2335 final ActorRef shard = parent.underlyingActor().context().actorOf(
2336 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2337 "testServerRemoved");
2339 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2341 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);