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.CommitTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
64 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
65 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
66 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
67 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
68 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
70 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
71 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
72 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
73 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
74 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListenerReply;
75 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
76 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
77 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
78 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
79 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
80 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
81 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
82 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
83 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
84 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
85 import org.opendaylight.controller.cluster.raft.RaftActorContext;
86 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
87 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
88 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
89 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
90 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
91 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
92 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
93 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
94 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
95 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
96 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
97 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
98 import org.opendaylight.controller.cluster.raft.persisted.SimpleReplicatedLogEntry;
99 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
100 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
101 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
102 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
103 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
104 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
105 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
106 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
107 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
108 import org.opendaylight.yangtools.concepts.Identifier;
109 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
110 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
114 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
117 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
118 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
119 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
120 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
121 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
122 import scala.concurrent.Await;
123 import scala.concurrent.Future;
124 import scala.concurrent.duration.FiniteDuration;
126 public class ShardTest extends AbstractShardTest {
127 private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in "
128 + "InMemorySnapshotStore and journal recovery seq number will start from 1";
131 public void testRegisterChangeListener() throws Exception {
132 new ShardTestKit(getSystem()) {
134 final TestActorRef<Shard> shard = actorFactory.createTestActor(
135 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
136 "testRegisterChangeListener");
138 waitUntilLeader(shard);
140 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
142 final MockDataChangeListener listener = new MockDataChangeListener(1);
143 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener,
144 TestModel.TEST_PATH), "testRegisterChangeListener-DataChangeListener");
146 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH, dclActor,
147 AsyncDataBroker.DataChangeScope.BASE, true), getRef());
149 final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
150 RegisterChangeListenerReply.class);
151 final String replyPath = reply.getListenerRegistrationPath().toString();
152 assertTrue("Incorrect reply path: " + replyPath,
153 replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
155 final YangInstanceIdentifier path = TestModel.TEST_PATH;
156 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
158 listener.waitForChangeEvents(path);
163 @SuppressWarnings("serial")
165 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
166 // This test tests the timing window in which a change listener is registered before the
167 // shard becomes the leader. We verify that the listener is registered and notified of the
168 // existing data when the shard becomes the leader.
169 // For this test, we want to send the RegisterChangeListener message after the shard
170 // has recovered from persistence and before it becomes the leader. So we subclass
171 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
172 // we know that the shard has been initialized to a follower and has started the
173 // election process. The following 2 CountDownLatches are used to coordinate the
174 // ElectionTimeout with the sending of the RegisterChangeListener message.
175 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
176 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
177 final Creator<Shard> creator = new Creator<Shard>() {
178 boolean firstElectionTimeout = true;
181 public Shard create() throws Exception {
182 // Use a non persistent provider because this test actually invokes persist on the journal
183 // this will cause all other messages to not be queued properly after that.
184 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
185 // it does do a persist)
186 return new Shard(newShardBuilder()) {
188 public void handleCommand(final Object message) {
189 if (message instanceof ElectionTimeout && firstElectionTimeout) {
190 // Got the first ElectionTimeout. We don't forward it to the
191 // base Shard yet until we've sent the RegisterChangeListener
192 // message. So we signal the onFirstElectionTimeout latch to tell
193 // the main thread to send the RegisterChangeListener message and
194 // start a thread to wait on the onChangeListenerRegistered latch,
195 // which the main thread signals after it has sent the message.
196 // After the onChangeListenerRegistered is triggered, we send the
197 // original ElectionTimeout message to proceed with the election.
198 firstElectionTimeout = false;
199 final ActorRef self = getSelf();
203 Uninterruptibles.awaitUninterruptibly(
204 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
205 self.tell(message, self);
209 onFirstElectionTimeout.countDown();
211 super.handleCommand(message);
218 setupInMemorySnapshotStore();
220 final YangInstanceIdentifier path = TestModel.TEST_PATH;
221 final MockDataChangeListener listener = new MockDataChangeListener(1);
222 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
223 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
225 final TestActorRef<Shard> shard = actorFactory.createTestActor(
226 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
227 "testRegisterChangeListenerWhenNotLeaderInitially");
229 new ShardTestKit(getSystem()) {
231 // Wait until the shard receives the first ElectionTimeout
233 assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
235 // Now send the RegisterChangeListener and wait for the reply.
236 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.SUBTREE, false),
239 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
240 RegisterChangeListenerReply.class);
241 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
243 // Sanity check - verify the shard is not the leader yet.
244 shard.tell(FindLeader.INSTANCE, getRef());
245 final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
246 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
248 // Signal the onChangeListenerRegistered latch to tell the
249 // thread above to proceed
250 // with the election process.
251 onChangeListenerRegistered.countDown();
253 // Wait for the shard to become the leader and notify our
254 // listener with the existing
255 // data in the store.
256 listener.waitForChangeEvents(path);
262 public void testRegisterDataTreeChangeListener() throws Exception {
263 new ShardTestKit(getSystem()) {
265 final TestActorRef<Shard> shard = actorFactory.createTestActor(
266 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
267 "testRegisterDataTreeChangeListener");
269 waitUntilLeader(shard);
271 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
273 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
274 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
275 TestModel.TEST_PATH), "testRegisterDataTreeChangeListener-DataTreeChangeListener");
277 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
279 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
280 RegisterDataTreeChangeListenerReply.class);
281 final String replyPath = reply.getListenerRegistrationPath().toString();
282 assertTrue("Incorrect reply path: " + replyPath,
283 replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
285 final YangInstanceIdentifier path = TestModel.TEST_PATH;
286 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
288 listener.waitForChangeEvents();
293 @SuppressWarnings("serial")
295 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
296 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
297 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
298 final Creator<Shard> creator = new Creator<Shard>() {
299 boolean firstElectionTimeout = true;
302 public Shard create() throws Exception {
303 return new Shard(newShardBuilder()) {
305 public void handleCommand(final Object message) {
306 if (message instanceof ElectionTimeout && firstElectionTimeout) {
307 firstElectionTimeout = false;
308 final ActorRef self = getSelf();
312 Uninterruptibles.awaitUninterruptibly(
313 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
314 self.tell(message, self);
318 onFirstElectionTimeout.countDown();
320 super.handleCommand(message);
327 setupInMemorySnapshotStore();
329 final YangInstanceIdentifier path = TestModel.TEST_PATH;
330 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
331 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
332 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
334 final TestActorRef<Shard> shard = actorFactory.createTestActor(
335 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
336 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
338 new ShardTestKit(getSystem()) {
340 assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
342 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
343 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
344 RegisterDataTreeChangeListenerReply.class);
345 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
347 shard.tell(FindLeader.INSTANCE, getRef());
348 final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
349 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
351 onChangeListenerRegistered.countDown();
353 // TODO: investigate why we do not receive data chage events
354 listener.waitForChangeEvents();
360 public void testCreateTransaction() {
361 new ShardTestKit(getSystem()) {
363 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
365 waitUntilLeader(shard);
367 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
369 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
370 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
372 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
373 CreateTransactionReply.class);
375 final String path = reply.getTransactionPath().toString();
376 assertTrue("Unexpected transaction path " + path, path
377 .startsWith("akka://test/user/testCreateTransaction/shard-member-1:ShardTransactionTest@0:"));
383 public void testCreateTransactionOnChain() {
384 new ShardTestKit(getSystem()) {
386 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
388 waitUntilLeader(shard);
390 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
391 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
393 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
394 CreateTransactionReply.class);
396 final String path = reply.getTransactionPath().toString();
397 assertTrue("Unexpected transaction path " + path, path.startsWith(
398 "akka://test/user/testCreateTransactionOnChain/shard-member-1:ShardTransactionTest@0:"));
404 public void testPeerAddressResolved() throws Exception {
405 new ShardTestKit(getSystem()) {
407 final ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"),
409 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder()
410 .peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null))
411 .props().withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
413 final String address = "akka://foobar";
414 shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
416 shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
417 final OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
418 assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
424 public void testApplySnapshot() throws Exception {
426 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps()
427 .withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplySnapshot");
429 ShardTestKit.waitUntilLeader(shard);
431 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
432 store.setSchemaContext(SCHEMA_CONTEXT);
434 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
435 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
436 .withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
437 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
439 writeToStore(store, TestModel.TEST_PATH, container);
441 final YangInstanceIdentifier root = YangInstanceIdentifier.EMPTY;
442 final NormalizedNode<?,?> expected = readStore(store, root);
444 final Snapshot snapshot = Snapshot.create(
445 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(expected)),
446 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4, -1, null, null);
448 shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
450 final Stopwatch sw = Stopwatch.createStarted();
451 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
452 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
455 assertEquals("Root node", expected, readStore(shard, root));
457 } catch (final AssertionError e) {
462 fail("Snapshot was not applied");
466 public void testApplyState() throws Exception {
467 final TestActorRef<Shard> shard = actorFactory.createTestActor(
468 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");
470 ShardTestKit.waitUntilLeader(shard);
472 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
473 store.setSchemaContext(SCHEMA_CONTEXT);
475 final DataTreeModification writeMod = store.takeSnapshot().newModification();
476 final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
477 writeMod.write(TestModel.TEST_PATH, node);
480 final TransactionIdentifier tx = nextTransactionId();
481 shard.underlyingActor().applyState(null, null, payloadForModification(store, writeMod, tx));
483 final Stopwatch sw = Stopwatch.createStarted();
484 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
485 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
487 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
488 if (actual != null) {
489 assertEquals("Applied state", node, actual);
494 fail("State was not applied");
498 public void testDataTreeCandidateRecovery() throws Exception {
499 // Set up the InMemorySnapshotStore.
500 final DataTree source = setupInMemorySnapshotStore();
502 final DataTreeModification writeMod = source.takeSnapshot().newModification();
503 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
505 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
507 // Set up the InMemoryJournal.
508 InMemoryJournal.addEntry(shardID.toString(), 1, new SimpleReplicatedLogEntry(0, 1,
509 payloadForModification(source, writeMod, nextTransactionId())));
511 final int nListEntries = 16;
512 final Set<Integer> listEntryKeys = new HashSet<>();
514 // Add some ModificationPayload entries
515 for (int i = 1; i <= nListEntries; i++) {
516 listEntryKeys.add(Integer.valueOf(i));
518 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
519 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
521 final DataTreeModification mod = source.takeSnapshot().newModification();
522 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
525 InMemoryJournal.addEntry(shardID.toString(), i + 1, new SimpleReplicatedLogEntry(i, 1,
526 payloadForModification(source, mod, nextTransactionId())));
529 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
530 new ApplyJournalEntries(nListEntries));
532 testRecovery(listEntryKeys);
536 @SuppressWarnings("checkstyle:IllegalCatch")
537 public void testConcurrentThreePhaseCommits() throws Exception {
538 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
539 final CountDownLatch commitLatch = new CountDownLatch(2);
541 final long timeoutSec = 5;
542 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
543 final Timeout timeout = new Timeout(duration);
545 final TestActorRef<Shard> shard = actorFactory.createTestActor(
546 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
547 "testConcurrentThreePhaseCommits");
549 class OnFutureComplete extends OnComplete<Object> {
550 private final Class<?> expRespType;
552 OnFutureComplete(final Class<?> expRespType) {
553 this.expRespType = expRespType;
557 public void onComplete(final Throwable error, final Object resp) {
559 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
562 assertEquals("Commit response type", expRespType, resp.getClass());
564 } catch (final Exception e) {
570 void onSuccess(final Object resp) throws Exception {
574 class OnCommitFutureComplete extends OnFutureComplete {
575 OnCommitFutureComplete() {
576 super(CommitTransactionReply.class);
580 public void onComplete(final Throwable error, final Object resp) {
581 super.onComplete(error, resp);
582 commitLatch.countDown();
586 class OnCanCommitFutureComplete extends OnFutureComplete {
587 private final TransactionIdentifier transactionID;
589 OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
590 super(CanCommitTransactionReply.class);
591 this.transactionID = transactionID;
595 void onSuccess(final Object resp) throws Exception {
596 final CanCommitTransactionReply canCommitReply =
597 CanCommitTransactionReply.fromSerializable(resp);
598 assertEquals("Can commit", true, canCommitReply.getCanCommit());
600 final Future<Object> commitFuture = Patterns.ask(shard,
601 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
602 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
606 new ShardTestKit(getSystem()) {
608 waitUntilLeader(shard);
610 final TransactionIdentifier transactionID1 = nextTransactionId();
611 final TransactionIdentifier transactionID2 = nextTransactionId();
612 final TransactionIdentifier transactionID3 = nextTransactionId();
614 final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
615 shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
616 final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
617 final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
618 final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
620 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
621 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
622 final ReadyTransactionReply readyReply = ReadyTransactionReply
623 .fromSerializable(expectMsgClass(duration, ReadyTransactionReply.class));
624 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
626 // Send the CanCommitTransaction message for the first Tx.
628 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
629 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
630 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
631 assertEquals("Can commit", true, canCommitReply.getCanCommit());
633 // Ready 2 more Tx's.
635 shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
636 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
637 expectMsgClass(duration, ReadyTransactionReply.class);
640 prepareBatchedModifications(transactionID3,
641 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
642 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
643 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
645 expectMsgClass(duration, ReadyTransactionReply.class);
647 // Send the CanCommitTransaction message for the next 2 Tx's.
648 // These should get queued and
649 // processed after the first Tx completes.
651 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
652 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
654 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
655 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
657 // Send the CommitTransaction message for the first Tx. After it
658 // completes, it should
659 // trigger the 2nd Tx to proceed which should in turn then
662 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
663 expectMsgClass(duration, CommitTransactionReply.class);
665 // Wait for the next 2 Tx's to complete.
667 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2), getSystem().dispatcher());
669 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3), getSystem().dispatcher());
671 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
673 if (caughtEx.get() != null) {
674 Throwables.propagateIfInstanceOf(caughtEx.get(), Exception.class);
675 Throwables.propagate(caughtEx.get());
678 assertEquals("Commits complete", true, done);
680 // final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
681 // cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
682 // cohort3.getPreCommit(), cohort3.getCommit());
683 // inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
684 // inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
685 // inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
686 // inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
687 // inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
688 // inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
689 // inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
690 // inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
691 // inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
693 // Verify data in the data store.
695 verifyOuterListEntry(shard, 1);
697 verifyLastApplied(shard, 2);
703 public void testBatchedModificationsWithNoCommitOnReady() throws Exception {
704 new ShardTestKit(getSystem()) {
706 final TestActorRef<Shard> shard = actorFactory.createTestActor(
707 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
708 "testBatchedModificationsWithNoCommitOnReady");
710 waitUntilLeader(shard);
712 final TransactionIdentifier transactionID = nextTransactionId();
713 final FiniteDuration duration = duration("5 seconds");
715 // Send a BatchedModifications to start a transaction.
717 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
718 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
719 expectMsgClass(duration, BatchedModificationsReply.class);
721 // Send a couple more BatchedModifications.
724 newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
725 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
727 expectMsgClass(duration, BatchedModificationsReply.class);
729 shard.tell(newBatchedModifications(transactionID,
730 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
731 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
732 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3),
734 expectMsgClass(duration, ReadyTransactionReply.class);
736 // Send the CanCommitTransaction message.
738 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
739 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
740 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
741 assertEquals("Can commit", true, canCommitReply.getCanCommit());
743 // Send the CommitTransaction message.
745 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
746 expectMsgClass(duration, CommitTransactionReply.class);
748 // Verify data in the data store.
750 verifyOuterListEntry(shard, 1);
756 public void testBatchedModificationsWithCommitOnReady() throws Exception {
757 new ShardTestKit(getSystem()) {
759 final TestActorRef<Shard> shard = actorFactory.createTestActor(
760 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
761 "testBatchedModificationsWithCommitOnReady");
763 waitUntilLeader(shard);
765 final TransactionIdentifier transactionID = nextTransactionId();
766 final FiniteDuration duration = duration("5 seconds");
768 // Send a BatchedModifications to start a transaction.
770 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
771 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
772 expectMsgClass(duration, BatchedModificationsReply.class);
774 // Send a couple more BatchedModifications.
776 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
777 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
779 expectMsgClass(duration, BatchedModificationsReply.class);
781 shard.tell(newBatchedModifications(transactionID,
782 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
783 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
784 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3),
787 expectMsgClass(duration, CommitTransactionReply.class);
789 // Verify data in the data store.
791 verifyOuterListEntry(shard, 1);
796 @Test(expected = IllegalStateException.class)
797 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
798 new ShardTestKit(getSystem()) {
800 final TestActorRef<Shard> shard = actorFactory.createTestActor(
801 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
802 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
804 waitUntilLeader(shard);
806 final TransactionIdentifier transactionID = nextTransactionId();
807 final BatchedModifications batched = new BatchedModifications(transactionID,
808 DataStoreVersions.CURRENT_VERSION);
809 batched.setReady(true);
810 batched.setTotalMessagesSent(2);
812 shard.tell(batched, getRef());
814 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
816 if (failure != null) {
817 Throwables.propagateIfInstanceOf(failure.cause(), Exception.class);
818 Throwables.propagate(failure.cause());
825 public void testBatchedModificationsWithOperationFailure() throws Exception {
826 new ShardTestKit(getSystem()) {
828 final TestActorRef<Shard> shard = actorFactory.createTestActor(
829 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
830 "testBatchedModificationsWithOperationFailure");
832 waitUntilLeader(shard);
834 // Test merge with invalid data. An exception should occur when
835 // the merge is applied. Note that
836 // write will not validate the children for performance reasons.
838 final TransactionIdentifier transactionID = nextTransactionId();
840 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
841 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
842 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
844 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
845 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
846 shard.tell(batched, getRef());
847 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
849 final Throwable cause = failure.cause();
851 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
852 batched.setReady(true);
853 batched.setTotalMessagesSent(2);
855 shard.tell(batched, getRef());
857 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
858 assertEquals("Failure cause", cause, failure.cause());
864 public void testBatchedModificationsOnTransactionChain() throws Exception {
865 new ShardTestKit(getSystem()) {
867 final TestActorRef<Shard> shard = actorFactory.createTestActor(
868 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
869 "testBatchedModificationsOnTransactionChain");
871 waitUntilLeader(shard);
873 final LocalHistoryIdentifier historyId = nextHistoryId();
874 final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
875 final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
877 final FiniteDuration duration = duration("5 seconds");
879 // Send a BatchedModifications to start a chained write
880 // transaction and ready it.
882 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
883 final YangInstanceIdentifier path = TestModel.TEST_PATH;
884 shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
885 expectMsgClass(duration, ReadyTransactionReply.class);
887 // Create a read Tx on the same chain.
889 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
890 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
892 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"),
893 CreateTransactionReply.class);
895 getSystem().actorSelection(createReply.getTransactionPath())
896 .tell(new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
897 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
898 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
900 // Commit the write transaction.
902 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
903 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
904 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
905 assertEquals("Can commit", true, canCommitReply.getCanCommit());
907 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
908 expectMsgClass(duration, CommitTransactionReply.class);
910 // Verify data in the data store.
912 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
913 assertEquals("Stored node", containerNode, actualNode);
919 public void testOnBatchedModificationsWhenNotLeader() {
920 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
921 new ShardTestKit(getSystem()) {
923 final Creator<Shard> creator = new Creator<Shard>() {
924 private static final long serialVersionUID = 1L;
927 public Shard create() throws Exception {
928 return new Shard(newShardBuilder()) {
930 protected boolean isLeader() {
931 return overrideLeaderCalls.get() ? false : super.isLeader();
935 public ActorSelection getLeader() {
936 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path())
943 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
944 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
945 "testOnBatchedModificationsWhenNotLeader");
947 waitUntilLeader(shard);
949 overrideLeaderCalls.set(true);
951 final BatchedModifications batched = new BatchedModifications(nextTransactionId(),
952 DataStoreVersions.CURRENT_VERSION);
954 shard.tell(batched, ActorRef.noSender());
956 expectMsgEquals(batched);
962 public void testTransactionMessagesWithNoLeader() {
963 new ShardTestKit(getSystem()) {
965 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
966 .shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
967 final TestActorRef<Shard> shard = actorFactory.createTestActor(
968 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
969 "testTransactionMessagesWithNoLeader");
971 waitUntilNoLeader(shard);
973 final TransactionIdentifier txId = nextTransactionId();
974 shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
975 Failure failure = expectMsgClass(Failure.class);
976 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
978 shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
979 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
980 failure = expectMsgClass(Failure.class);
981 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
983 shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
984 failure = expectMsgClass(Failure.class);
985 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
991 public void testReadyWithReadWriteImmediateCommit() throws Exception {
992 testReadyWithImmediateCommit(true);
996 public void testReadyWithWriteOnlyImmediateCommit() throws Exception {
997 testReadyWithImmediateCommit(false);
1000 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception {
1001 new ShardTestKit(getSystem()) {
1003 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1004 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1005 "testReadyWithImmediateCommit-" + readWrite);
1007 waitUntilLeader(shard);
1009 final TransactionIdentifier transactionID = nextTransactionId();
1010 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1012 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1013 containerNode, true), getRef());
1015 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true),
1019 expectMsgClass(duration("5 seconds"), CommitTransactionReply.class);
1021 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1022 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1028 public void testReadyLocalTransactionWithImmediateCommit() throws Exception {
1029 new ShardTestKit(getSystem()) {
1031 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1032 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1033 "testReadyLocalTransactionWithImmediateCommit");
1035 waitUntilLeader(shard);
1037 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1039 final DataTreeModification modification = dataStore.newModification();
1041 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1042 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1043 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1044 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1046 final TransactionIdentifier txId = nextTransactionId();
1047 modification.ready();
1048 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1050 shard.tell(readyMessage, getRef());
1052 expectMsgClass(CommitTransactionReply.class);
1054 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1055 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1061 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception {
1062 new ShardTestKit(getSystem()) {
1064 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1065 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1066 "testReadyLocalTransactionWithThreePhaseCommit");
1068 waitUntilLeader(shard);
1070 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1072 final DataTreeModification modification = dataStore.newModification();
1074 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1075 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1076 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1077 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1079 final TransactionIdentifier txId = nextTransactionId();
1080 modification.ready();
1081 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1083 shard.tell(readyMessage, getRef());
1085 expectMsgClass(ReadyTransactionReply.class);
1087 // Send the CanCommitTransaction message.
1089 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1090 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1091 .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
1092 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1094 // Send the CanCommitTransaction message.
1096 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1097 expectMsgClass(CommitTransactionReply.class);
1099 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1100 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1106 public void testReadWriteCommitWithPersistenceDisabled() throws Exception {
1107 dataStoreContextBuilder.persistent(false);
1108 new ShardTestKit(getSystem()) {
1110 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1111 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1112 "testCommitWithPersistenceDisabled");
1114 waitUntilLeader(shard);
1116 // Setup a simulated transactions with a mock cohort.
1118 final FiniteDuration duration = duration("5 seconds");
1120 final TransactionIdentifier transactionID = nextTransactionId();
1121 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1122 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false),
1124 expectMsgClass(duration, ReadyTransactionReply.class);
1126 // Send the CanCommitTransaction message.
1128 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1129 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1130 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1131 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1133 // Send the CanCommitTransaction message.
1135 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1136 expectMsgClass(duration, CommitTransactionReply.class);
1138 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1139 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1145 public void testReadWriteCommitWhenTransactionHasModifications() throws Exception {
1146 testCommitWhenTransactionHasModifications(true);
1150 public void testWriteOnlyCommitWhenTransactionHasModifications() throws Exception {
1151 testCommitWhenTransactionHasModifications(false);
1154 private void testCommitWhenTransactionHasModifications(final boolean readWrite) throws Exception {
1155 new ShardTestKit(getSystem()) {
1157 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1158 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1159 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1160 "testCommitWhenTransactionHasModifications-" + readWrite);
1162 waitUntilLeader(shard);
1164 final FiniteDuration duration = duration("5 seconds");
1165 final TransactionIdentifier transactionID = nextTransactionId();
1168 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1169 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1171 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1172 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1175 expectMsgClass(duration, ReadyTransactionReply.class);
1177 // Send the CanCommitTransaction message.
1179 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1180 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1181 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1182 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1184 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1185 expectMsgClass(duration, CommitTransactionReply.class);
1187 final InOrder inOrder = inOrder(dataTree);
1188 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1189 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1190 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1192 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1193 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1195 // Use MBean for verification
1196 // Committed transaction count should increase as usual
1197 assertEquals(1, shardStats.getCommittedTransactionsCount());
1199 // Commit index should advance as we do not have an empty
1201 assertEquals(0, shardStats.getCommitIndex());
1207 public void testCommitPhaseFailure() throws Exception {
1208 new ShardTestKit(getSystem()) {
1210 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1211 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1212 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1213 "testCommitPhaseFailure");
1215 waitUntilLeader(shard);
1217 final FiniteDuration duration = duration("5 seconds");
1218 final Timeout timeout = new Timeout(duration);
1220 // Setup 2 simulated transactions with mock cohorts. The first
1224 doThrow(new RuntimeException("mock commit failure")).when(dataTree)
1225 .commit(any(DataTreeCandidate.class));
1227 final TransactionIdentifier transactionID1 = nextTransactionId();
1228 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1229 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1230 expectMsgClass(duration, ReadyTransactionReply.class);
1232 final TransactionIdentifier transactionID2 = nextTransactionId();
1233 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1234 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1235 expectMsgClass(duration, ReadyTransactionReply.class);
1237 // Send the CanCommitTransaction message for the first Tx.
1239 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1240 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1241 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1242 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1244 // Send the CanCommitTransaction message for the 2nd Tx. This
1245 // should get queued and
1246 // processed after the first Tx completes.
1248 final Future<Object> canCommitFuture = Patterns.ask(shard,
1249 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1251 // Send the CommitTransaction message for the first Tx. This
1252 // should send back an error
1253 // and trigger the 2nd Tx to proceed.
1255 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1256 expectMsgClass(duration, akka.actor.Status.Failure.class);
1258 // Wait for the 2nd Tx to complete the canCommit phase.
1260 final CountDownLatch latch = new CountDownLatch(1);
1261 canCommitFuture.onComplete(new OnComplete<Object>() {
1263 public void onComplete(final Throwable failure, final Object resp) {
1266 }, getSystem().dispatcher());
1268 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1270 final InOrder inOrder = inOrder(dataTree);
1271 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1272 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1274 // FIXME: this invocation is done on the result of validate(). To test it, we need to make sure mock
1275 // validate performs wrapping and we capture that mock
1276 // inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1278 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1284 public void testPreCommitPhaseFailure() throws Exception {
1285 new ShardTestKit(getSystem()) {
1287 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1288 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1289 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1290 "testPreCommitPhaseFailure");
1292 waitUntilLeader(shard);
1294 final FiniteDuration duration = duration("5 seconds");
1295 final Timeout timeout = new Timeout(duration);
1297 doThrow(new RuntimeException("mock preCommit failure")).when(dataTree)
1298 .prepare(any(DataTreeModification.class));
1300 final TransactionIdentifier transactionID1 = nextTransactionId();
1301 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1302 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1303 expectMsgClass(duration, ReadyTransactionReply.class);
1305 final TransactionIdentifier transactionID2 = nextTransactionId();
1306 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1307 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1308 expectMsgClass(duration, ReadyTransactionReply.class);
1310 // Send the CanCommitTransaction message for the first Tx.
1312 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1313 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1314 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1315 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1317 // Send the CanCommitTransaction message for the 2nd Tx. This
1318 // should get queued and
1319 // processed after the first Tx completes.
1321 final Future<Object> canCommitFuture = Patterns.ask(shard,
1322 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1324 // Send the CommitTransaction message for the first Tx. This
1325 // should send back an error
1326 // and trigger the 2nd Tx to proceed.
1328 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1329 expectMsgClass(duration, akka.actor.Status.Failure.class);
1331 // Wait for the 2nd Tx to complete the canCommit phase.
1333 final CountDownLatch latch = new CountDownLatch(1);
1334 canCommitFuture.onComplete(new OnComplete<Object>() {
1336 public void onComplete(final Throwable failure, final Object resp) {
1339 }, getSystem().dispatcher());
1341 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1343 final InOrder inOrder = inOrder(dataTree);
1344 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1345 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1346 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1352 public void testCanCommitPhaseFailure() throws Exception {
1353 new ShardTestKit(getSystem()) {
1355 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1356 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1357 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1358 "testCanCommitPhaseFailure");
1360 waitUntilLeader(shard);
1362 final FiniteDuration duration = duration("5 seconds");
1363 final TransactionIdentifier transactionID1 = nextTransactionId();
1365 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1366 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1368 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1369 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1370 expectMsgClass(duration, ReadyTransactionReply.class);
1372 // Send the CanCommitTransaction message.
1374 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1375 expectMsgClass(duration, akka.actor.Status.Failure.class);
1377 // Send another can commit to ensure the failed one got cleaned
1380 final TransactionIdentifier transactionID2 = nextTransactionId();
1381 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1382 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1383 expectMsgClass(duration, ReadyTransactionReply.class);
1385 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1386 final CanCommitTransactionReply reply = CanCommitTransactionReply
1387 .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
1388 assertEquals("getCanCommit", true, reply.getCanCommit());
1394 public void testImmediateCommitWithCanCommitPhaseFailure() throws Exception {
1395 testImmediateCommitWithCanCommitPhaseFailure(true);
1396 testImmediateCommitWithCanCommitPhaseFailure(false);
1399 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Exception {
1400 new ShardTestKit(getSystem()) {
1402 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1403 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1404 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1405 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1407 waitUntilLeader(shard);
1409 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1410 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1412 final FiniteDuration duration = duration("5 seconds");
1414 final TransactionIdentifier transactionID1 = nextTransactionId();
1417 shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
1418 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1420 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1421 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1424 expectMsgClass(duration, akka.actor.Status.Failure.class);
1426 // Send another can commit to ensure the failed one got cleaned
1429 final TransactionIdentifier transactionID2 = nextTransactionId();
1431 shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
1432 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1434 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1435 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1438 expectMsgClass(duration, CommitTransactionReply.class);
1444 public void testAbortWithCommitPending() throws Exception {
1445 new ShardTestKit(getSystem()) {
1447 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
1449 void persistPayload(final Identifier id, final Payload payload,
1450 final boolean batchHint) {
1451 // Simulate an AbortTransaction message occurring during
1452 // replication, after
1453 // persisting and before finishing the commit to the
1456 doAbortTransaction(id, null);
1457 super.persistPayload(id, payload, batchHint);
1461 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1462 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1463 "testAbortWithCommitPending");
1465 waitUntilLeader(shard);
1467 final FiniteDuration duration = duration("5 seconds");
1469 final TransactionIdentifier transactionID = nextTransactionId();
1471 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1472 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1473 expectMsgClass(duration, ReadyTransactionReply.class);
1475 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1476 expectMsgClass(duration, CanCommitTransactionReply.class);
1478 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1479 expectMsgClass(duration, CommitTransactionReply.class);
1481 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1483 // Since we're simulating an abort occurring during replication
1484 // and before finish commit,
1485 // the data should still get written to the in-memory store
1486 // since we've gotten past
1487 // canCommit and preCommit and persisted the data.
1488 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1494 public void testTransactionCommitTimeout() throws Exception {
1495 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1496 new ShardTestKit(getSystem()) {
1498 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1499 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1500 "testTransactionCommitTimeout");
1502 waitUntilLeader(shard);
1504 final FiniteDuration duration = duration("5 seconds");
1506 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1507 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1508 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1510 // Ready 2 Tx's - the first will timeout
1512 final TransactionIdentifier transactionID1 = nextTransactionId();
1514 prepareBatchedModifications(transactionID1,
1515 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1516 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1517 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
1519 expectMsgClass(duration, ReadyTransactionReply.class);
1521 final TransactionIdentifier transactionID2 = nextTransactionId();
1522 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1523 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1525 prepareBatchedModifications(transactionID2, listNodePath,
1526 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false),
1528 expectMsgClass(duration, ReadyTransactionReply.class);
1530 // canCommit 1st Tx. We don't send the commit so it should
1533 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1534 expectMsgClass(duration, CanCommitTransactionReply.class);
1536 // canCommit the 2nd Tx - it should complete after the 1st Tx
1539 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1540 expectMsgClass(duration, CanCommitTransactionReply.class);
1542 // Try to commit the 1st Tx - should fail as it's not the
1545 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1546 expectMsgClass(duration, akka.actor.Status.Failure.class);
1548 // Commit the 2nd Tx.
1550 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1551 expectMsgClass(duration, CommitTransactionReply.class);
1553 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1554 assertNotNull(listNodePath + " not found", node);
1561 // public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1562 // dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1564 // new ShardTestKit(getSystem()) {{
1565 // final TestActorRef<Shard> shard = actorFactory.createTestActor(
1566 // newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1567 // "testTransactionCommitQueueCapacityExceeded");
1569 // waitUntilLeader(shard);
1571 // final FiniteDuration duration = duration("5 seconds");
1573 // final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1575 // final TransactionIdentifier transactionID1 = nextTransactionId();
1576 // final MutableCompositeModification modification1 = new MutableCompositeModification();
1577 // final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1578 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID1,
1581 // final TransactionIdentifier transactionID2 = nextTransactionId();
1582 // final MutableCompositeModification modification2 = new MutableCompositeModification();
1583 // final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1584 // TestModel.OUTER_LIST_PATH,
1585 // ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), transactionID2,
1588 // final TransactionIdentifier transactionID3 = nextTransactionId();
1589 // final MutableCompositeModification modification3 = new MutableCompositeModification();
1590 // final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1591 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID3,
1594 // // Ready the Tx's
1596 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1,
1597 // modification1), getRef());
1598 // expectMsgClass(duration, ReadyTransactionReply.class);
1600 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2,
1601 // modification2), getRef());
1602 // expectMsgClass(duration, ReadyTransactionReply.class);
1604 // // The 3rd Tx should exceed queue capacity and fail.
1606 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3,
1607 // modification3), getRef());
1608 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1610 // // canCommit 1st Tx.
1612 // shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1613 // expectMsgClass(duration, CanCommitTransactionReply.class);
1615 // // canCommit the 2nd Tx - it should get queued.
1617 // shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1619 // // canCommit the 3rd Tx - should exceed queue capacity and fail.
1621 // shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1622 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1627 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Exception {
1628 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1629 new ShardTestKit(getSystem()) {
1631 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1632 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1633 "testTransactionCommitWithPriorExpiredCohortEntries");
1635 waitUntilLeader(shard);
1637 final FiniteDuration duration = duration("5 seconds");
1639 final TransactionIdentifier transactionID1 = nextTransactionId();
1640 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1641 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1642 expectMsgClass(duration, ReadyTransactionReply.class);
1644 final TransactionIdentifier transactionID2 = nextTransactionId();
1645 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1646 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1647 expectMsgClass(duration, ReadyTransactionReply.class);
1649 final TransactionIdentifier transactionID3 = nextTransactionId();
1650 shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1651 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1652 expectMsgClass(duration, ReadyTransactionReply.class);
1654 // All Tx's are readied. We'll send canCommit for the last one
1655 // but not the others. The others
1656 // should expire from the queue and the last one should be
1659 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1660 expectMsgClass(duration, CanCommitTransactionReply.class);
1666 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Exception {
1667 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1668 new ShardTestKit(getSystem()) {
1670 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1671 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1672 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1674 waitUntilLeader(shard);
1676 final FiniteDuration duration = duration("5 seconds");
1678 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1680 final TransactionIdentifier transactionID1 = nextTransactionId();
1681 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1682 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1683 expectMsgClass(duration, ReadyTransactionReply.class);
1685 // CanCommit the first Tx so it's the current in-progress Tx.
1687 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1688 expectMsgClass(duration, CanCommitTransactionReply.class);
1690 // Ready the second Tx.
1692 final TransactionIdentifier transactionID2 = nextTransactionId();
1693 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1694 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1695 expectMsgClass(duration, ReadyTransactionReply.class);
1697 // Ready the third Tx.
1699 final TransactionIdentifier transactionID3 = nextTransactionId();
1700 final DataTreeModification modification3 = dataStore.newModification();
1701 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1702 .apply(modification3);
1703 modification3.ready();
1704 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3,
1706 shard.tell(readyMessage, getRef());
1708 // Commit the first Tx. After completing, the second should
1709 // expire from the queue and the third
1712 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1713 expectMsgClass(duration, CommitTransactionReply.class);
1715 // Expect commit reply from the third Tx.
1717 expectMsgClass(duration, CommitTransactionReply.class);
1719 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1720 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1726 public void testCanCommitBeforeReadyFailure() throws Exception {
1727 new ShardTestKit(getSystem()) {
1729 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1730 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1731 "testCanCommitBeforeReadyFailure");
1733 shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
1734 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1740 public void testAbortAfterCanCommit() throws Exception {
1741 new ShardTestKit(getSystem()) {
1743 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1744 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterCanCommit");
1746 waitUntilLeader(shard);
1748 final FiniteDuration duration = duration("5 seconds");
1749 final Timeout timeout = new Timeout(duration);
1751 // Ready 2 transactions - the first one will be aborted.
1753 final TransactionIdentifier transactionID1 = nextTransactionId();
1754 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1755 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1756 expectMsgClass(duration, ReadyTransactionReply.class);
1758 final TransactionIdentifier transactionID2 = nextTransactionId();
1759 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1760 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1761 expectMsgClass(duration, ReadyTransactionReply.class);
1763 // Send the CanCommitTransaction message for the first Tx.
1765 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1766 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1767 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1768 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1770 // Send the CanCommitTransaction message for the 2nd Tx. This
1771 // should get queued and
1772 // processed after the first Tx completes.
1774 final Future<Object> canCommitFuture = Patterns.ask(shard,
1775 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1777 // Send the AbortTransaction message for the first Tx. This
1778 // should trigger the 2nd
1781 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1782 expectMsgClass(duration, AbortTransactionReply.class);
1784 // Wait for the 2nd Tx to complete the canCommit phase.
1786 canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture, duration);
1787 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1793 public void testAbortAfterReady() throws Exception {
1794 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1795 new ShardTestKit(getSystem()) {
1797 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1798 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1800 waitUntilLeader(shard);
1802 final FiniteDuration duration = duration("5 seconds");
1806 final TransactionIdentifier transactionID1 = nextTransactionId();
1807 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1808 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1809 expectMsgClass(duration, ReadyTransactionReply.class);
1811 // Send the AbortTransaction message.
1813 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1814 expectMsgClass(duration, AbortTransactionReply.class);
1816 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1818 // Now send CanCommitTransaction - should fail.
1820 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1821 final Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
1822 assertTrue("Failure type", failure instanceof IllegalStateException);
1824 // Ready and CanCommit another and verify success.
1826 final TransactionIdentifier transactionID2 = nextTransactionId();
1827 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1828 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1829 expectMsgClass(duration, ReadyTransactionReply.class);
1831 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1832 expectMsgClass(duration, CanCommitTransactionReply.class);
1838 public void testAbortQueuedTransaction() throws Exception {
1839 new ShardTestKit(getSystem()) {
1841 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1842 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1844 waitUntilLeader(shard);
1846 final FiniteDuration duration = duration("5 seconds");
1850 final TransactionIdentifier transactionID1 = nextTransactionId();
1851 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1852 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1853 expectMsgClass(duration, ReadyTransactionReply.class);
1855 final TransactionIdentifier transactionID2 = nextTransactionId();
1856 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1857 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1858 expectMsgClass(duration, ReadyTransactionReply.class);
1860 final TransactionIdentifier transactionID3 = nextTransactionId();
1862 newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
1863 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1),
1865 expectMsgClass(duration, ReadyTransactionReply.class);
1867 // Abort the second tx while it's queued.
1869 shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1870 expectMsgClass(duration, AbortTransactionReply.class);
1872 // Commit the other 2.
1874 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1875 expectMsgClass(duration, CanCommitTransactionReply.class);
1877 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1878 expectMsgClass(duration, CommitTransactionReply.class);
1880 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1881 expectMsgClass(duration, CanCommitTransactionReply.class);
1883 shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1884 expectMsgClass(duration, CommitTransactionReply.class);
1886 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1892 public void testCreateSnapshotWithNonPersistentData() throws Exception {
1893 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1897 public void testCreateSnapshot() throws Exception {
1898 testCreateSnapshot(true, "testCreateSnapshot");
1901 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception {
1902 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1904 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1905 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
1906 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
1911 public void saveSnapshot(final Object obj) {
1912 savedSnapshot.set(obj);
1913 super.saveSnapshot(obj);
1917 dataStoreContextBuilder.persistent(persistent);
1919 class TestShard extends Shard {
1921 protected TestShard(final AbstractBuilder<?, ?> builder) {
1923 setPersistence(new TestPersistentDataProvider(super.persistence()));
1927 public void handleCommand(final Object message) {
1928 super.handleCommand(message);
1930 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
1931 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
1932 latch.get().countDown();
1937 public RaftActorContext getRaftActorContext() {
1938 return super.getRaftActorContext();
1942 new ShardTestKit(getSystem()) {
1944 final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
1946 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1947 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1950 waitUntilLeader(shard);
1951 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1953 final NormalizedNode<?, ?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
1955 // Trigger creation of a snapshot by ensuring
1956 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
1957 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1958 awaitAndValidateSnapshot(expectedRoot);
1960 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1961 awaitAndValidateSnapshot(expectedRoot);
1964 private void awaitAndValidateSnapshot(final NormalizedNode<?, ?> expectedRoot)
1965 throws InterruptedException, IOException {
1966 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1968 assertTrue("Invalid saved snapshot " + savedSnapshot.get(), savedSnapshot.get() instanceof Snapshot);
1970 verifySnapshot((Snapshot) savedSnapshot.get(), expectedRoot);
1972 latch.set(new CountDownLatch(1));
1973 savedSnapshot.set(null);
1976 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?, ?> expectedRoot)
1977 throws IOException {
1978 final NormalizedNode<?, ?> actual = ((ShardSnapshotState)snapshot.getState()).getSnapshot()
1979 .getRootNode().get();
1980 assertEquals("Root node", expectedRoot, actual);
1986 * This test simply verifies that the applySnapShot logic will work.
1989 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
1990 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
1991 store.setSchemaContext(SCHEMA_CONTEXT);
1993 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
1994 putTransaction.write(TestModel.TEST_PATH,
1995 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1996 commitTransaction(store, putTransaction);
1999 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
2001 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2003 writeTransaction.delete(YangInstanceIdentifier.EMPTY);
2004 writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
2006 commitTransaction(store, writeTransaction);
2008 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
2010 assertEquals(expected, actual);
2014 public void testRecoveryApplicable() {
2016 final DatastoreContext persistentContext = DatastoreContext.newBuilder()
2017 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2019 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext)
2020 .schemaContext(SCHEMA_CONTEXT).props();
2022 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder()
2023 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2025 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext)
2026 .schemaContext(SCHEMA_CONTEXT).props();
2028 new ShardTestKit(getSystem()) {
2030 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2032 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2034 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2036 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2042 public void testOnDatastoreContext() {
2043 new ShardTestKit(getSystem()) {
2045 dataStoreContextBuilder.persistent(true);
2047 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(),
2048 "testOnDatastoreContext");
2050 assertEquals("isRecoveryApplicable", true,
2051 shard.underlyingActor().persistence().isRecoveryApplicable());
2053 waitUntilLeader(shard);
2055 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2057 assertEquals("isRecoveryApplicable", false,
2058 shard.underlyingActor().persistence().isRecoveryApplicable());
2060 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2062 assertEquals("isRecoveryApplicable", true,
2063 shard.underlyingActor().persistence().isRecoveryApplicable());
2069 public void testRegisterRoleChangeListener() throws Exception {
2070 new ShardTestKit(getSystem()) {
2072 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2073 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2074 "testRegisterRoleChangeListener");
2076 waitUntilLeader(shard);
2078 final TestActorRef<MessageCollectorActor> listener =
2079 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2081 shard.tell(new RegisterRoleChangeListener(), listener);
2083 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2085 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2086 ShardLeaderStateChanged.class);
2087 assertEquals("getLocalShardDataTree present", true,
2088 leaderStateChanged.getLocalShardDataTree().isPresent());
2089 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2090 leaderStateChanged.getLocalShardDataTree().get());
2092 MessageCollectorActor.clearMessages(listener);
2094 // Force a leader change
2096 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2098 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2099 ShardLeaderStateChanged.class);
2100 assertEquals("getLocalShardDataTree present", false,
2101 leaderStateChanged.getLocalShardDataTree().isPresent());
2107 public void testFollowerInitialSyncStatus() throws Exception {
2108 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2109 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2110 "testFollowerInitialSyncStatus");
2112 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false,
2113 "member-1-shard-inventory-operational"));
2115 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2117 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true,
2118 "member-1-shard-inventory-operational"));
2120 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2124 public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
2125 new ShardTestKit(getSystem()) {
2127 final String testName = "testClusteredDataChangeListenerDelayedRegistration";
2128 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2129 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2131 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2132 final MockDataChangeListener listener = new MockDataChangeListener(1);
2133 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
2134 actorFactory.generateActorId(testName + "-DataChangeListener"));
2136 setupInMemorySnapshotStore();
2138 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2139 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2140 actorFactory.generateActorId(testName + "-shard"));
2142 waitUntilNoLeader(shard);
2144 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true),
2146 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2147 RegisterChangeListenerReply.class);
2148 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2150 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2151 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2153 listener.waitForChangeEvents();
2159 public void testClusteredDataChangeListenerRegistration() throws Exception {
2160 new ShardTestKit(getSystem()) {
2162 final String testName = "testClusteredDataChangeListenerRegistration";
2163 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2164 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2166 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2167 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2169 final TestActorRef<Shard> followerShard = actorFactory
2170 .createTestActor(Shard.builder().id(followerShardID)
2171 .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
2172 .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2173 "akka://test/user/" + leaderShardID.toString()))
2174 .schemaContext(SCHEMA_CONTEXT).props()
2175 .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2177 final TestActorRef<Shard> leaderShard = actorFactory
2178 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
2179 .peerAddresses(Collections.singletonMap(followerShardID.toString(),
2180 "akka://test/user/" + followerShardID.toString()))
2181 .schemaContext(SCHEMA_CONTEXT).props()
2182 .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2184 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2185 final String leaderPath = waitUntilLeader(followerShard);
2186 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2188 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2189 final MockDataChangeListener listener = new MockDataChangeListener(1);
2190 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
2191 actorFactory.generateActorId(testName + "-DataChangeListener"));
2194 new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true),
2196 final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2197 RegisterChangeListenerReply.class);
2198 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
2200 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2202 listener.waitForChangeEvents();
2208 public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
2209 new ShardTestKit(getSystem()) {
2211 final String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
2212 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2213 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2215 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2216 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
2217 TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2219 setupInMemorySnapshotStore();
2221 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2222 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2223 actorFactory.generateActorId(testName + "-shard"));
2225 waitUntilNoLeader(shard);
2227 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2228 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2229 RegisterDataTreeChangeListenerReply.class);
2230 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2232 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2233 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2235 listener.waitForChangeEvents();
2241 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2242 new ShardTestKit(getSystem()) {
2244 final String testName = "testClusteredDataTreeChangeListenerRegistration";
2245 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2246 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2248 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2249 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2251 final TestActorRef<Shard> followerShard = actorFactory
2252 .createTestActor(Shard.builder().id(followerShardID)
2253 .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
2254 .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2255 "akka://test/user/" + leaderShardID.toString()))
2256 .schemaContext(SCHEMA_CONTEXT).props()
2257 .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2259 final TestActorRef<Shard> leaderShard = actorFactory
2260 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
2261 .peerAddresses(Collections.singletonMap(followerShardID.toString(),
2262 "akka://test/user/" + followerShardID.toString()))
2263 .schemaContext(SCHEMA_CONTEXT).props()
2264 .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2266 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2267 final String leaderPath = waitUntilLeader(followerShard);
2268 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2270 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2271 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2272 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
2273 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2275 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2276 final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
2277 RegisterDataTreeChangeListenerReply.class);
2278 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2280 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2282 listener.waitForChangeEvents();
2288 public void testServerRemoved() throws Exception {
2289 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2291 final ActorRef shard = parent.underlyingActor().context().actorOf(
2292 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2293 "testServerRemoved");
2295 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2297 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);