2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.cluster.datastore;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertSame;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
17 import static org.mockito.Matchers.any;
18 import static org.mockito.Mockito.doThrow;
19 import static org.mockito.Mockito.inOrder;
20 import static org.mockito.Mockito.mock;
21 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
23 import akka.actor.ActorRef;
24 import akka.actor.ActorSelection;
25 import akka.actor.Props;
26 import akka.actor.Status.Failure;
27 import akka.dispatch.Dispatchers;
28 import akka.dispatch.OnComplete;
29 import akka.japi.Creator;
30 import akka.pattern.Patterns;
31 import akka.persistence.SaveSnapshotSuccess;
32 import akka.testkit.TestActorRef;
33 import akka.util.Timeout;
34 import com.google.common.base.Stopwatch;
35 import com.google.common.base.Throwables;
36 import com.google.common.util.concurrent.Uninterruptibles;
37 import java.io.IOException;
38 import java.util.Collections;
39 import java.util.HashSet;
42 import java.util.concurrent.CountDownLatch;
43 import java.util.concurrent.TimeUnit;
44 import java.util.concurrent.atomic.AtomicBoolean;
45 import java.util.concurrent.atomic.AtomicReference;
46 import org.junit.Test;
47 import org.mockito.InOrder;
48 import org.opendaylight.controller.cluster.DataPersistenceProvider;
49 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
50 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
51 import org.opendaylight.controller.cluster.access.concepts.MemberName;
52 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
53 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
54 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
55 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
56 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
57 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
58 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
59 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
60 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
61 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
62 import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistration;
63 import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistrationReply;
64 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
65 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
68 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
70 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
71 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
73 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
74 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply;
76 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
77 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
78 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
79 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
80 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
81 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
82 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
83 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
84 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
85 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
86 import org.opendaylight.controller.cluster.raft.RaftActorContext;
87 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
88 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
89 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
90 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
91 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
92 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
93 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
94 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
95 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
96 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
97 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
98 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
99 import org.opendaylight.controller.cluster.raft.persisted.SimpleReplicatedLogEntry;
100 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
101 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
102 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
103 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
104 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
105 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
106 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
107 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
108 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
109 import org.opendaylight.yangtools.concepts.Identifier;
110 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
111 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
117 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
118 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
119 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
120 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
121 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
122 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
123 import scala.concurrent.Await;
124 import scala.concurrent.Future;
125 import scala.concurrent.duration.FiniteDuration;
127 public class ShardTest extends AbstractShardTest {
128 private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in "
129 + "InMemorySnapshotStore and journal recovery seq number will start from 1";
132 public void testRegisterChangeListener() throws Exception {
133 new ShardTestKit(getSystem()) {
135 final TestActorRef<Shard> shard = actorFactory.createTestActor(
136 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
137 "testRegisterChangeListener");
139 waitUntilLeader(shard);
141 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
143 final MockDataChangeListener listener = new MockDataChangeListener(1);
144 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener,
145 TestModel.TEST_PATH), "testRegisterChangeListener-DataChangeListener");
147 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH, dclActor,
148 AsyncDataBroker.DataChangeScope.BASE, true), getRef());
150 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("3 seconds"),
151 RegisterDataTreeNotificationListenerReply.class);
152 final String replyPath = reply.getListenerRegistrationPath().toString();
153 assertTrue("Incorrect reply path: " + replyPath,
154 replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
156 final YangInstanceIdentifier path = TestModel.TEST_PATH;
157 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
159 listener.waitForChangeEvents(path);
164 @SuppressWarnings("serial")
166 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
167 // This test tests the timing window in which a change listener is registered before the
168 // shard becomes the leader. We verify that the listener is registered and notified of the
169 // existing data when the shard becomes the leader.
170 // For this test, we want to send the RegisterChangeListener message after the shard
171 // has recovered from persistence and before it becomes the leader. So we subclass
172 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
173 // we know that the shard has been initialized to a follower and has started the
174 // election process. The following 2 CountDownLatches are used to coordinate the
175 // ElectionTimeout with the sending of the RegisterChangeListener message.
176 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
177 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
178 final Creator<Shard> creator = new Creator<Shard>() {
179 boolean firstElectionTimeout = true;
182 public Shard create() throws Exception {
183 // Use a non persistent provider because this test actually invokes persist on the journal
184 // this will cause all other messages to not be queued properly after that.
185 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
186 // it does do a persist)
187 return new Shard(newShardBuilder()) {
189 public void handleCommand(final Object message) {
190 if (message instanceof ElectionTimeout && firstElectionTimeout) {
191 // Got the first ElectionTimeout. We don't forward it to the
192 // base Shard yet until we've sent the RegisterChangeListener
193 // message. So we signal the onFirstElectionTimeout latch to tell
194 // the main thread to send the RegisterChangeListener message and
195 // start a thread to wait on the onChangeListenerRegistered latch,
196 // which the main thread signals after it has sent the message.
197 // After the onChangeListenerRegistered is triggered, we send the
198 // original ElectionTimeout message to proceed with the election.
199 firstElectionTimeout = false;
200 final ActorRef self = getSelf();
202 Uninterruptibles.awaitUninterruptibly(
203 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
204 self.tell(message, self);
207 onFirstElectionTimeout.countDown();
209 super.handleCommand(message);
216 setupInMemorySnapshotStore();
218 final YangInstanceIdentifier path = TestModel.TEST_PATH;
219 final MockDataChangeListener listener = new MockDataChangeListener(1);
220 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
221 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
223 final TestActorRef<Shard> shard = actorFactory.createTestActor(
224 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
225 "testRegisterChangeListenerWhenNotLeaderInitially");
227 new ShardTestKit(getSystem()) {
229 // Wait until the shard receives the first ElectionTimeout
231 assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
233 // Now send the RegisterChangeListener and wait for the reply.
234 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.SUBTREE, false),
237 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
238 RegisterDataTreeNotificationListenerReply.class);
239 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
241 // Sanity check - verify the shard is not the leader yet.
242 shard.tell(FindLeader.INSTANCE, getRef());
243 final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
244 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
246 // Signal the onChangeListenerRegistered latch to tell the
247 // thread above to proceed
248 // with the election process.
249 onChangeListenerRegistered.countDown();
251 // Wait for the shard to become the leader and notify our
252 // listener with the existing
253 // data in the store.
254 listener.waitForChangeEvents(path);
260 public void testRegisterDataTreeChangeListener() throws Exception {
261 new ShardTestKit(getSystem()) {
263 final TestActorRef<Shard> shard = actorFactory.createTestActor(
264 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
265 "testRegisterDataTreeChangeListener");
267 waitUntilLeader(shard);
269 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
271 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
272 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
273 TestModel.TEST_PATH), "testRegisterDataTreeChangeListener-DataTreeChangeListener");
275 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
277 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("3 seconds"),
278 RegisterDataTreeNotificationListenerReply.class);
279 final String replyPath = reply.getListenerRegistrationPath().toString();
280 assertTrue("Incorrect reply path: " + replyPath,
281 replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
283 final YangInstanceIdentifier path = TestModel.TEST_PATH;
284 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
286 listener.waitForChangeEvents();
291 @SuppressWarnings("serial")
293 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
294 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
295 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
296 final Creator<Shard> creator = new Creator<Shard>() {
297 boolean firstElectionTimeout = true;
300 public Shard create() throws Exception {
301 return new Shard(newShardBuilder()) {
303 public void handleCommand(final Object message) {
304 if (message instanceof ElectionTimeout && firstElectionTimeout) {
305 firstElectionTimeout = false;
306 final ActorRef self = getSelf();
308 Uninterruptibles.awaitUninterruptibly(
309 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
310 self.tell(message, self);
313 onFirstElectionTimeout.countDown();
315 super.handleCommand(message);
322 setupInMemorySnapshotStore();
324 final YangInstanceIdentifier path = TestModel.TEST_PATH;
325 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
326 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
327 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
329 final TestActorRef<Shard> shard = actorFactory.createTestActor(
330 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
331 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
333 new ShardTestKit(getSystem()) {
335 assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
337 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
338 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
339 RegisterDataTreeNotificationListenerReply.class);
340 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
342 shard.tell(FindLeader.INSTANCE, getRef());
343 final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
344 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
346 onChangeListenerRegistered.countDown();
348 // TODO: investigate why we do not receive data chage events
349 listener.waitForChangeEvents();
355 public void testCreateTransaction() {
356 new ShardTestKit(getSystem()) {
358 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
360 waitUntilLeader(shard);
362 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
364 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
365 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
367 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
368 CreateTransactionReply.class);
370 final String path = reply.getTransactionPath().toString();
371 assertTrue("Unexpected transaction path " + path, path.startsWith(String.format(
372 "akka://test/user/testCreateTransaction/shard-%s-%s:ShardTransactionTest@0:",
373 shardID.getShardName(), shardID.getMemberName().getName())));
379 public void testCreateTransactionOnChain() {
380 new ShardTestKit(getSystem()) {
382 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
384 waitUntilLeader(shard);
386 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
387 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
389 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
390 CreateTransactionReply.class);
392 final String path = reply.getTransactionPath().toString();
393 assertTrue("Unexpected transaction path " + path, path.startsWith(String.format(
394 "akka://test/user/testCreateTransactionOnChain/shard-%s-%s:ShardTransactionTest@0:",
395 shardID.getShardName(), shardID.getMemberName().getName())));
401 public void testPeerAddressResolved() throws Exception {
402 new ShardTestKit(getSystem()) {
404 final ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"),
406 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder()
407 .peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null))
408 .props().withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
410 final String address = "akka://foobar";
411 shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
413 shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
414 final OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
415 assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
421 public void testApplySnapshot() throws Exception {
423 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps()
424 .withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplySnapshot");
426 ShardTestKit.waitUntilLeader(shard);
428 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
429 store.setSchemaContext(SCHEMA_CONTEXT);
431 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
432 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
433 .withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
434 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
436 writeToStore(store, TestModel.TEST_PATH, container);
438 final YangInstanceIdentifier root = YangInstanceIdentifier.EMPTY;
439 final NormalizedNode<?,?> expected = readStore(store, root);
441 final Snapshot snapshot = Snapshot.create(
442 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(expected)),
443 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4, -1, null, null);
445 shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
447 final Stopwatch sw = Stopwatch.createStarted();
448 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
449 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
452 assertEquals("Root node", expected, readStore(shard, root));
454 } catch (final AssertionError e) {
459 fail("Snapshot was not applied");
463 public void testApplyState() throws Exception {
464 final TestActorRef<Shard> shard = actorFactory.createTestActor(
465 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");
467 ShardTestKit.waitUntilLeader(shard);
469 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
470 store.setSchemaContext(SCHEMA_CONTEXT);
472 final DataTreeModification writeMod = store.takeSnapshot().newModification();
473 final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
474 writeMod.write(TestModel.TEST_PATH, node);
477 final TransactionIdentifier tx = nextTransactionId();
478 shard.underlyingActor().applyState(null, null, payloadForModification(store, writeMod, tx));
480 final Stopwatch sw = Stopwatch.createStarted();
481 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
482 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
484 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
485 if (actual != null) {
486 assertEquals("Applied state", node, actual);
491 fail("State was not applied");
495 public void testDataTreeCandidateRecovery() throws Exception {
496 // Set up the InMemorySnapshotStore.
497 final DataTree source = setupInMemorySnapshotStore();
499 final DataTreeModification writeMod = source.takeSnapshot().newModification();
500 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
502 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
504 // Set up the InMemoryJournal.
505 InMemoryJournal.addEntry(shardID.toString(), 1, new SimpleReplicatedLogEntry(0, 1,
506 payloadForModification(source, writeMod, nextTransactionId())));
508 final int nListEntries = 16;
509 final Set<Integer> listEntryKeys = new HashSet<>();
511 // Add some ModificationPayload entries
512 for (int i = 1; i <= nListEntries; i++) {
513 listEntryKeys.add(Integer.valueOf(i));
515 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
516 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
518 final DataTreeModification mod = source.takeSnapshot().newModification();
519 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
522 InMemoryJournal.addEntry(shardID.toString(), i + 1, new SimpleReplicatedLogEntry(i, 1,
523 payloadForModification(source, mod, nextTransactionId())));
526 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
527 new ApplyJournalEntries(nListEntries));
529 testRecovery(listEntryKeys);
533 @SuppressWarnings("checkstyle:IllegalCatch")
534 public void testConcurrentThreePhaseCommits() throws Exception {
535 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
536 final CountDownLatch commitLatch = new CountDownLatch(2);
538 final long timeoutSec = 5;
539 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
540 final Timeout timeout = new Timeout(duration);
542 final TestActorRef<Shard> shard = actorFactory.createTestActor(
543 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
544 "testConcurrentThreePhaseCommits");
546 class OnFutureComplete extends OnComplete<Object> {
547 private final Class<?> expRespType;
549 OnFutureComplete(final Class<?> expRespType) {
550 this.expRespType = expRespType;
554 public void onComplete(final Throwable error, final Object resp) {
556 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
559 assertEquals("Commit response type", expRespType, resp.getClass());
561 } catch (final Exception e) {
567 void onSuccess(final Object resp) throws Exception {
571 class OnCommitFutureComplete extends OnFutureComplete {
572 OnCommitFutureComplete() {
573 super(CommitTransactionReply.class);
577 public void onComplete(final Throwable error, final Object resp) {
578 super.onComplete(error, resp);
579 commitLatch.countDown();
583 class OnCanCommitFutureComplete extends OnFutureComplete {
584 private final TransactionIdentifier transactionID;
586 OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
587 super(CanCommitTransactionReply.class);
588 this.transactionID = transactionID;
592 void onSuccess(final Object resp) throws Exception {
593 final CanCommitTransactionReply canCommitReply =
594 CanCommitTransactionReply.fromSerializable(resp);
595 assertEquals("Can commit", true, canCommitReply.getCanCommit());
597 final Future<Object> commitFuture = Patterns.ask(shard,
598 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
599 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
603 new ShardTestKit(getSystem()) {
605 waitUntilLeader(shard);
607 final TransactionIdentifier transactionID1 = nextTransactionId();
608 final TransactionIdentifier transactionID2 = nextTransactionId();
609 final TransactionIdentifier transactionID3 = nextTransactionId();
611 final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
612 shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
613 final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
614 final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
615 final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
617 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
618 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
619 final ReadyTransactionReply readyReply = ReadyTransactionReply
620 .fromSerializable(expectMsgClass(duration, ReadyTransactionReply.class));
621 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
622 // Send the CanCommitTransaction message for the first Tx.
624 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
625 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
626 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
627 assertEquals("Can commit", true, canCommitReply.getCanCommit());
629 // Ready 2 more Tx's.
631 shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
632 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
633 expectMsgClass(duration, ReadyTransactionReply.class);
636 prepareBatchedModifications(transactionID3,
637 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
638 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
639 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
641 expectMsgClass(duration, ReadyTransactionReply.class);
643 // Send the CanCommitTransaction message for the next 2 Tx's.
644 // These should get queued and
645 // processed after the first Tx completes.
647 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
648 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
650 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
651 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
653 // Send the CommitTransaction message for the first Tx. After it
654 // completes, it should
655 // trigger the 2nd Tx to proceed which should in turn then
658 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
659 expectMsgClass(duration, CommitTransactionReply.class);
661 // Wait for the next 2 Tx's to complete.
663 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2), getSystem().dispatcher());
665 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3), getSystem().dispatcher());
667 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
669 final Throwable t = caughtEx.get();
671 Throwables.propagateIfPossible(t, Exception.class);
672 throw new RuntimeException(t);
675 assertEquals("Commits complete", true, done);
677 // final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
678 // cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
679 // cohort3.getPreCommit(), cohort3.getCommit());
680 // inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
681 // inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
682 // inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
683 // inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
684 // inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
685 // inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
686 // inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
687 // inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
688 // inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
690 // Verify data in the data store.
692 verifyOuterListEntry(shard, 1);
694 verifyLastApplied(shard, 5);
700 public void testBatchedModificationsWithNoCommitOnReady() throws Exception {
701 new ShardTestKit(getSystem()) {
703 final TestActorRef<Shard> shard = actorFactory.createTestActor(
704 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
705 "testBatchedModificationsWithNoCommitOnReady");
707 waitUntilLeader(shard);
709 final TransactionIdentifier transactionID = nextTransactionId();
710 final FiniteDuration duration = duration("5 seconds");
712 // Send a BatchedModifications to start a transaction.
714 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
715 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
716 expectMsgClass(duration, BatchedModificationsReply.class);
718 // Send a couple more BatchedModifications.
721 newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
722 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
724 expectMsgClass(duration, BatchedModificationsReply.class);
726 shard.tell(newBatchedModifications(transactionID,
727 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
728 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
729 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3),
731 expectMsgClass(duration, ReadyTransactionReply.class);
733 // Send the CanCommitTransaction message.
735 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
736 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
737 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
738 assertEquals("Can commit", true, canCommitReply.getCanCommit());
740 // Send the CommitTransaction message.
742 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
743 expectMsgClass(duration, CommitTransactionReply.class);
745 // Verify data in the data store.
747 verifyOuterListEntry(shard, 1);
753 public void testBatchedModificationsWithCommitOnReady() throws Exception {
754 new ShardTestKit(getSystem()) {
756 final TestActorRef<Shard> shard = actorFactory.createTestActor(
757 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
758 "testBatchedModificationsWithCommitOnReady");
760 waitUntilLeader(shard);
762 final TransactionIdentifier transactionID = nextTransactionId();
763 final FiniteDuration duration = duration("5 seconds");
765 // Send a BatchedModifications to start a transaction.
767 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
768 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
769 expectMsgClass(duration, BatchedModificationsReply.class);
771 // Send a couple more BatchedModifications.
773 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
774 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
776 expectMsgClass(duration, BatchedModificationsReply.class);
778 shard.tell(newBatchedModifications(transactionID,
779 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
780 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
781 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3),
784 expectMsgClass(duration, CommitTransactionReply.class);
786 // Verify data in the data store.
788 verifyOuterListEntry(shard, 1);
793 @Test(expected = IllegalStateException.class)
794 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
795 new ShardTestKit(getSystem()) {
797 final TestActorRef<Shard> shard = actorFactory.createTestActor(
798 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
799 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
801 waitUntilLeader(shard);
803 final TransactionIdentifier transactionID = nextTransactionId();
804 final BatchedModifications batched = new BatchedModifications(transactionID,
805 DataStoreVersions.CURRENT_VERSION);
806 batched.setReady(true);
807 batched.setTotalMessagesSent(2);
809 shard.tell(batched, getRef());
811 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
813 if (failure != null) {
814 Throwables.propagateIfPossible(failure.cause(), Exception.class);
815 throw new RuntimeException(failure.cause());
822 public void testBatchedModificationsWithOperationFailure() throws Exception {
823 new ShardTestKit(getSystem()) {
825 final TestActorRef<Shard> shard = actorFactory.createTestActor(
826 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
827 "testBatchedModificationsWithOperationFailure");
829 waitUntilLeader(shard);
831 // Test merge with invalid data. An exception should occur when
832 // the merge is applied. Note that
833 // write will not validate the children for performance reasons.
835 final TransactionIdentifier transactionID = nextTransactionId();
837 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
838 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
839 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
841 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
842 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
843 shard.tell(batched, getRef());
844 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
846 final Throwable cause = failure.cause();
848 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
849 batched.setReady(true);
850 batched.setTotalMessagesSent(2);
852 shard.tell(batched, getRef());
854 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
855 assertEquals("Failure cause", cause, failure.cause());
861 public void testBatchedModificationsOnTransactionChain() throws Exception {
862 new ShardTestKit(getSystem()) {
864 final TestActorRef<Shard> shard = actorFactory.createTestActor(
865 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
866 "testBatchedModificationsOnTransactionChain");
868 waitUntilLeader(shard);
870 final LocalHistoryIdentifier historyId = nextHistoryId();
871 final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
872 final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
874 final FiniteDuration duration = duration("5 seconds");
876 // Send a BatchedModifications to start a chained write
877 // transaction and ready it.
879 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
880 final YangInstanceIdentifier path = TestModel.TEST_PATH;
881 shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
882 expectMsgClass(duration, ReadyTransactionReply.class);
884 // Create a read Tx on the same chain.
886 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
887 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
889 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"),
890 CreateTransactionReply.class);
892 getSystem().actorSelection(createReply.getTransactionPath())
893 .tell(new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
894 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
895 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
897 // Commit the write transaction.
899 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
900 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
901 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
902 assertEquals("Can commit", true, canCommitReply.getCanCommit());
904 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
905 expectMsgClass(duration, CommitTransactionReply.class);
907 // Verify data in the data store.
909 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
910 assertEquals("Stored node", containerNode, actualNode);
916 public void testOnBatchedModificationsWhenNotLeader() {
917 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
918 new ShardTestKit(getSystem()) {
920 final Creator<Shard> creator = new Creator<Shard>() {
921 private static final long serialVersionUID = 1L;
924 public Shard create() throws Exception {
925 return new Shard(newShardBuilder()) {
927 protected boolean isLeader() {
928 return overrideLeaderCalls.get() ? false : super.isLeader();
932 public ActorSelection getLeader() {
933 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path())
940 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
941 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
942 "testOnBatchedModificationsWhenNotLeader");
944 waitUntilLeader(shard);
946 overrideLeaderCalls.set(true);
948 final BatchedModifications batched = new BatchedModifications(nextTransactionId(),
949 DataStoreVersions.CURRENT_VERSION);
951 shard.tell(batched, ActorRef.noSender());
953 expectMsgEquals(batched);
959 public void testTransactionMessagesWithNoLeader() {
960 new ShardTestKit(getSystem()) {
962 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
963 .shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
964 final TestActorRef<Shard> shard = actorFactory.createTestActor(
965 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
966 "testTransactionMessagesWithNoLeader");
968 waitUntilNoLeader(shard);
970 final TransactionIdentifier txId = nextTransactionId();
971 shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
972 Failure failure = expectMsgClass(Failure.class);
973 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
975 shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
976 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
977 failure = expectMsgClass(Failure.class);
978 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
980 shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
981 failure = expectMsgClass(Failure.class);
982 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
988 public void testReadyWithReadWriteImmediateCommit() throws Exception {
989 testReadyWithImmediateCommit(true);
993 public void testReadyWithWriteOnlyImmediateCommit() throws Exception {
994 testReadyWithImmediateCommit(false);
997 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception {
998 new ShardTestKit(getSystem()) {
1000 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1001 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1002 "testReadyWithImmediateCommit-" + readWrite);
1004 waitUntilLeader(shard);
1006 final TransactionIdentifier transactionID = nextTransactionId();
1007 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1009 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1010 containerNode, true), getRef());
1012 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true),
1016 expectMsgClass(duration("5 seconds"), CommitTransactionReply.class);
1018 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1019 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1025 public void testReadyLocalTransactionWithImmediateCommit() throws Exception {
1026 new ShardTestKit(getSystem()) {
1028 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1029 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1030 "testReadyLocalTransactionWithImmediateCommit");
1032 waitUntilLeader(shard);
1034 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1036 final DataTreeModification modification = dataStore.newModification();
1038 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1039 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1040 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1041 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1043 final TransactionIdentifier txId = nextTransactionId();
1044 modification.ready();
1045 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1047 shard.tell(readyMessage, getRef());
1049 expectMsgClass(CommitTransactionReply.class);
1051 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1052 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1058 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception {
1059 new ShardTestKit(getSystem()) {
1061 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1062 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1063 "testReadyLocalTransactionWithThreePhaseCommit");
1065 waitUntilLeader(shard);
1067 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1069 final DataTreeModification modification = dataStore.newModification();
1071 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1072 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1073 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1074 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1076 final TransactionIdentifier txId = nextTransactionId();
1077 modification.ready();
1078 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1080 shard.tell(readyMessage, getRef());
1082 expectMsgClass(ReadyTransactionReply.class);
1084 // Send the CanCommitTransaction message.
1086 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1087 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1088 .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
1089 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1091 // Send the CanCommitTransaction message.
1093 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1094 expectMsgClass(CommitTransactionReply.class);
1096 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1097 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1103 public void testReadWriteCommitWithPersistenceDisabled() throws Exception {
1104 dataStoreContextBuilder.persistent(false);
1105 new ShardTestKit(getSystem()) {
1107 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1108 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1109 "testCommitWithPersistenceDisabled");
1111 waitUntilLeader(shard);
1113 // Setup a simulated transactions with a mock cohort.
1115 final FiniteDuration duration = duration("5 seconds");
1117 final TransactionIdentifier transactionID = nextTransactionId();
1118 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1119 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false),
1121 expectMsgClass(duration, ReadyTransactionReply.class);
1123 // Send the CanCommitTransaction message.
1125 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1126 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1127 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1128 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1130 // Send the CanCommitTransaction message.
1132 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1133 expectMsgClass(duration, CommitTransactionReply.class);
1135 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1136 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1142 public void testReadWriteCommitWhenTransactionHasModifications() throws Exception {
1143 testCommitWhenTransactionHasModifications(true);
1147 public void testWriteOnlyCommitWhenTransactionHasModifications() throws Exception {
1148 testCommitWhenTransactionHasModifications(false);
1151 private void testCommitWhenTransactionHasModifications(final boolean readWrite) throws Exception {
1152 new ShardTestKit(getSystem()) {
1154 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1155 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1156 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1157 "testCommitWhenTransactionHasModifications-" + readWrite);
1159 waitUntilLeader(shard);
1161 final FiniteDuration duration = duration("5 seconds");
1162 final TransactionIdentifier transactionID = nextTransactionId();
1165 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1166 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1168 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1169 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1172 expectMsgClass(duration, ReadyTransactionReply.class);
1174 // Send the CanCommitTransaction message.
1176 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1177 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1178 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1179 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1181 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1182 expectMsgClass(duration, CommitTransactionReply.class);
1184 final InOrder inOrder = inOrder(dataTree);
1185 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1186 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1187 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1189 // Purge request is scheduled as asynchronous, wait for two heartbeats to let it propagate into
1191 Thread.sleep(HEARTBEAT_MILLIS * 2);
1193 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1194 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1196 // Use MBean for verification
1197 // Committed transaction count should increase as usual
1198 assertEquals(1, shardStats.getCommittedTransactionsCount());
1200 // Commit index should advance as we do not have an empty
1202 assertEquals(1, shardStats.getCommitIndex());
1208 public void testCommitPhaseFailure() throws Exception {
1209 new ShardTestKit(getSystem()) {
1211 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1212 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1213 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1214 "testCommitPhaseFailure");
1216 waitUntilLeader(shard);
1218 final FiniteDuration duration = duration("5 seconds");
1219 final Timeout timeout = new Timeout(duration);
1221 // Setup 2 simulated transactions with mock cohorts. The first
1225 doThrow(new RuntimeException("mock commit failure")).when(dataTree)
1226 .commit(any(DataTreeCandidate.class));
1228 final TransactionIdentifier transactionID1 = nextTransactionId();
1229 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1230 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1231 expectMsgClass(duration, ReadyTransactionReply.class);
1233 final TransactionIdentifier transactionID2 = nextTransactionId();
1234 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1235 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1236 expectMsgClass(duration, ReadyTransactionReply.class);
1238 // Send the CanCommitTransaction message for the first Tx.
1240 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1241 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1242 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1243 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1245 // Send the CanCommitTransaction message for the 2nd Tx. This
1246 // should get queued and
1247 // processed after the first Tx completes.
1249 final Future<Object> canCommitFuture = Patterns.ask(shard,
1250 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1252 // Send the CommitTransaction message for the first Tx. This
1253 // should send back an error
1254 // and trigger the 2nd Tx to proceed.
1256 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1257 expectMsgClass(duration, akka.actor.Status.Failure.class);
1259 // Wait for the 2nd Tx to complete the canCommit phase.
1261 final CountDownLatch latch = new CountDownLatch(1);
1262 canCommitFuture.onComplete(new OnComplete<Object>() {
1264 public void onComplete(final Throwable failure, final Object resp) {
1267 }, getSystem().dispatcher());
1269 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1271 final InOrder inOrder = inOrder(dataTree);
1272 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1273 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1275 // FIXME: this invocation is done on the result of validate(). To test it, we need to make sure mock
1276 // validate performs wrapping and we capture that mock
1277 // inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1279 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1285 public void testPreCommitPhaseFailure() throws Exception {
1286 new ShardTestKit(getSystem()) {
1288 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1289 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1290 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1291 "testPreCommitPhaseFailure");
1293 waitUntilLeader(shard);
1295 final FiniteDuration duration = duration("5 seconds");
1296 final Timeout timeout = new Timeout(duration);
1298 doThrow(new RuntimeException("mock preCommit failure")).when(dataTree)
1299 .prepare(any(DataTreeModification.class));
1301 final TransactionIdentifier transactionID1 = nextTransactionId();
1302 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1303 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1304 expectMsgClass(duration, ReadyTransactionReply.class);
1306 final TransactionIdentifier transactionID2 = nextTransactionId();
1307 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1308 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1309 expectMsgClass(duration, ReadyTransactionReply.class);
1311 // Send the CanCommitTransaction message for the first Tx.
1313 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1314 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1315 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1316 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1318 // Send the CanCommitTransaction message for the 2nd Tx. This
1319 // should get queued and
1320 // processed after the first Tx completes.
1322 final Future<Object> canCommitFuture = Patterns.ask(shard,
1323 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1325 // Send the CommitTransaction message for the first Tx. This
1326 // should send back an error
1327 // and trigger the 2nd Tx to proceed.
1329 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1330 expectMsgClass(duration, akka.actor.Status.Failure.class);
1332 // Wait for the 2nd Tx to complete the canCommit phase.
1334 final CountDownLatch latch = new CountDownLatch(1);
1335 canCommitFuture.onComplete(new OnComplete<Object>() {
1337 public void onComplete(final Throwable failure, final Object resp) {
1340 }, getSystem().dispatcher());
1342 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1344 final InOrder inOrder = inOrder(dataTree);
1345 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1346 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1347 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1353 public void testCanCommitPhaseFailure() throws Exception {
1354 new ShardTestKit(getSystem()) {
1356 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1357 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1358 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1359 "testCanCommitPhaseFailure");
1361 waitUntilLeader(shard);
1363 final FiniteDuration duration = duration("5 seconds");
1364 final TransactionIdentifier transactionID1 = nextTransactionId();
1366 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1367 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1369 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1370 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1371 expectMsgClass(duration, ReadyTransactionReply.class);
1373 // Send the CanCommitTransaction message.
1375 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1376 expectMsgClass(duration, akka.actor.Status.Failure.class);
1378 // Send another can commit to ensure the failed one got cleaned
1381 final TransactionIdentifier transactionID2 = nextTransactionId();
1382 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1383 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1384 expectMsgClass(duration, ReadyTransactionReply.class);
1386 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1387 final CanCommitTransactionReply reply = CanCommitTransactionReply
1388 .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
1389 assertEquals("getCanCommit", true, reply.getCanCommit());
1395 public void testImmediateCommitWithCanCommitPhaseFailure() throws Exception {
1396 testImmediateCommitWithCanCommitPhaseFailure(true);
1397 testImmediateCommitWithCanCommitPhaseFailure(false);
1400 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Exception {
1401 new ShardTestKit(getSystem()) {
1403 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1404 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1405 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1406 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1408 waitUntilLeader(shard);
1410 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1411 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1413 final FiniteDuration duration = duration("5 seconds");
1415 final TransactionIdentifier transactionID1 = nextTransactionId();
1418 shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
1419 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1421 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1422 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1425 expectMsgClass(duration, akka.actor.Status.Failure.class);
1427 // Send another can commit to ensure the failed one got cleaned
1430 final TransactionIdentifier transactionID2 = nextTransactionId();
1432 shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
1433 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1435 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1436 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1439 expectMsgClass(duration, CommitTransactionReply.class);
1445 public void testAbortWithCommitPending() throws Exception {
1446 new ShardTestKit(getSystem()) {
1448 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
1450 void persistPayload(final Identifier id, final Payload payload,
1451 final boolean batchHint) {
1452 // Simulate an AbortTransaction message occurring during
1453 // replication, after
1454 // persisting and before finishing the commit to the
1457 doAbortTransaction(id, null);
1458 super.persistPayload(id, payload, batchHint);
1462 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1463 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1464 "testAbortWithCommitPending");
1466 waitUntilLeader(shard);
1468 final FiniteDuration duration = duration("5 seconds");
1470 final TransactionIdentifier transactionID = nextTransactionId();
1472 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1473 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1474 expectMsgClass(duration, ReadyTransactionReply.class);
1476 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1477 expectMsgClass(duration, CanCommitTransactionReply.class);
1479 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1480 expectMsgClass(duration, CommitTransactionReply.class);
1482 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1484 // Since we're simulating an abort occurring during replication
1485 // and before finish commit,
1486 // the data should still get written to the in-memory store
1487 // since we've gotten past
1488 // canCommit and preCommit and persisted the data.
1489 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1495 public void testTransactionCommitTimeout() throws Exception {
1496 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1497 new ShardTestKit(getSystem()) {
1499 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1500 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1501 "testTransactionCommitTimeout");
1503 waitUntilLeader(shard);
1505 final FiniteDuration duration = duration("5 seconds");
1507 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1508 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1509 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1511 // Ready 2 Tx's - the first will timeout
1513 final TransactionIdentifier transactionID1 = nextTransactionId();
1515 prepareBatchedModifications(transactionID1,
1516 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1517 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1518 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
1520 expectMsgClass(duration, ReadyTransactionReply.class);
1522 final TransactionIdentifier transactionID2 = nextTransactionId();
1523 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1524 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1526 prepareBatchedModifications(transactionID2, listNodePath,
1527 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false),
1529 expectMsgClass(duration, ReadyTransactionReply.class);
1531 // canCommit 1st Tx. We don't send the commit so it should
1534 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1535 expectMsgClass(duration, CanCommitTransactionReply.class);
1537 // canCommit the 2nd Tx - it should complete after the 1st Tx
1540 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1541 expectMsgClass(duration, CanCommitTransactionReply.class);
1543 // Try to commit the 1st Tx - should fail as it's not the
1546 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1547 expectMsgClass(duration, akka.actor.Status.Failure.class);
1549 // Commit the 2nd Tx.
1551 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1552 expectMsgClass(duration, CommitTransactionReply.class);
1554 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1555 assertNotNull(listNodePath + " not found", node);
1562 // public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1563 // dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1565 // new ShardTestKit(getSystem()) {{
1566 // final TestActorRef<Shard> shard = actorFactory.createTestActor(
1567 // newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1568 // "testTransactionCommitQueueCapacityExceeded");
1570 // waitUntilLeader(shard);
1572 // final FiniteDuration duration = duration("5 seconds");
1574 // final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1576 // final TransactionIdentifier transactionID1 = nextTransactionId();
1577 // final MutableCompositeModification modification1 = new MutableCompositeModification();
1578 // final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1579 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID1,
1582 // final TransactionIdentifier transactionID2 = nextTransactionId();
1583 // final MutableCompositeModification modification2 = new MutableCompositeModification();
1584 // final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1585 // TestModel.OUTER_LIST_PATH,
1586 // ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), transactionID2,
1589 // final TransactionIdentifier transactionID3 = nextTransactionId();
1590 // final MutableCompositeModification modification3 = new MutableCompositeModification();
1591 // final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1592 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID3,
1595 // // Ready the Tx's
1597 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1,
1598 // modification1), getRef());
1599 // expectMsgClass(duration, ReadyTransactionReply.class);
1601 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2,
1602 // modification2), getRef());
1603 // expectMsgClass(duration, ReadyTransactionReply.class);
1605 // // The 3rd Tx should exceed queue capacity and fail.
1607 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3,
1608 // modification3), getRef());
1609 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1611 // // canCommit 1st Tx.
1613 // shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1614 // expectMsgClass(duration, CanCommitTransactionReply.class);
1616 // // canCommit the 2nd Tx - it should get queued.
1618 // shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1620 // // canCommit the 3rd Tx - should exceed queue capacity and fail.
1622 // shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1623 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1628 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Exception {
1629 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1630 new ShardTestKit(getSystem()) {
1632 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1633 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1634 "testTransactionCommitWithPriorExpiredCohortEntries");
1636 waitUntilLeader(shard);
1638 final FiniteDuration duration = duration("5 seconds");
1640 final TransactionIdentifier transactionID1 = nextTransactionId();
1641 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1642 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1643 expectMsgClass(duration, ReadyTransactionReply.class);
1645 final TransactionIdentifier transactionID2 = nextTransactionId();
1646 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1647 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1648 expectMsgClass(duration, ReadyTransactionReply.class);
1650 final TransactionIdentifier transactionID3 = nextTransactionId();
1651 shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1652 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1653 expectMsgClass(duration, ReadyTransactionReply.class);
1655 // All Tx's are readied. We'll send canCommit for the last one
1656 // but not the others. The others
1657 // should expire from the queue and the last one should be
1660 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1661 expectMsgClass(duration, CanCommitTransactionReply.class);
1667 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Exception {
1668 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1669 new ShardTestKit(getSystem()) {
1671 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1672 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1673 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1675 waitUntilLeader(shard);
1677 final FiniteDuration duration = duration("5 seconds");
1679 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1681 final TransactionIdentifier transactionID1 = nextTransactionId();
1682 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1683 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1684 expectMsgClass(duration, ReadyTransactionReply.class);
1686 // CanCommit the first Tx so it's the current in-progress Tx.
1688 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1689 expectMsgClass(duration, CanCommitTransactionReply.class);
1691 // Ready the second Tx.
1693 final TransactionIdentifier transactionID2 = nextTransactionId();
1694 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1695 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1696 expectMsgClass(duration, ReadyTransactionReply.class);
1698 // Ready the third Tx.
1700 final TransactionIdentifier transactionID3 = nextTransactionId();
1701 final DataTreeModification modification3 = dataStore.newModification();
1702 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1703 .apply(modification3);
1704 modification3.ready();
1705 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3,
1707 shard.tell(readyMessage, getRef());
1709 // Commit the first Tx. After completing, the second should
1710 // expire from the queue and the third
1713 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1714 expectMsgClass(duration, CommitTransactionReply.class);
1716 // Expect commit reply from the third Tx.
1718 expectMsgClass(duration, CommitTransactionReply.class);
1720 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1721 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1727 public void testCanCommitBeforeReadyFailure() throws Exception {
1728 new ShardTestKit(getSystem()) {
1730 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1731 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1732 "testCanCommitBeforeReadyFailure");
1734 shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
1735 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1741 public void testAbortAfterCanCommit() throws Exception {
1742 new ShardTestKit(getSystem()) {
1744 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1745 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterCanCommit");
1747 waitUntilLeader(shard);
1749 final FiniteDuration duration = duration("5 seconds");
1750 final Timeout timeout = new Timeout(duration);
1752 // Ready 2 transactions - the first one will be aborted.
1754 final TransactionIdentifier transactionID1 = nextTransactionId();
1755 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1756 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1757 expectMsgClass(duration, ReadyTransactionReply.class);
1759 final TransactionIdentifier transactionID2 = nextTransactionId();
1760 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1761 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1762 expectMsgClass(duration, ReadyTransactionReply.class);
1764 // Send the CanCommitTransaction message for the first Tx.
1766 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1767 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1768 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1769 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1771 // Send the CanCommitTransaction message for the 2nd Tx. This
1772 // should get queued and
1773 // processed after the first Tx completes.
1775 final Future<Object> canCommitFuture = Patterns.ask(shard,
1776 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1778 // Send the AbortTransaction message for the first Tx. This
1779 // should trigger the 2nd
1782 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1783 expectMsgClass(duration, AbortTransactionReply.class);
1785 // Wait for the 2nd Tx to complete the canCommit phase.
1787 canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture, duration);
1788 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1794 public void testAbortAfterReady() throws Exception {
1795 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1796 new ShardTestKit(getSystem()) {
1798 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1799 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1801 waitUntilLeader(shard);
1803 final FiniteDuration duration = duration("5 seconds");
1807 final TransactionIdentifier transactionID1 = nextTransactionId();
1808 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1809 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1810 expectMsgClass(duration, ReadyTransactionReply.class);
1812 // Send the AbortTransaction message.
1814 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1815 expectMsgClass(duration, AbortTransactionReply.class);
1817 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1819 // Now send CanCommitTransaction - should fail.
1821 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1822 final Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
1823 assertTrue("Failure type", failure instanceof IllegalStateException);
1825 // Ready and CanCommit another and verify success.
1827 final TransactionIdentifier transactionID2 = nextTransactionId();
1828 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1829 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1830 expectMsgClass(duration, ReadyTransactionReply.class);
1832 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1833 expectMsgClass(duration, CanCommitTransactionReply.class);
1839 public void testAbortQueuedTransaction() throws Exception {
1840 new ShardTestKit(getSystem()) {
1842 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1843 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1845 waitUntilLeader(shard);
1847 final FiniteDuration duration = duration("5 seconds");
1851 final TransactionIdentifier transactionID1 = nextTransactionId();
1852 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1853 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1854 expectMsgClass(duration, ReadyTransactionReply.class);
1856 final TransactionIdentifier transactionID2 = nextTransactionId();
1857 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1858 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1859 expectMsgClass(duration, ReadyTransactionReply.class);
1861 final TransactionIdentifier transactionID3 = nextTransactionId();
1863 newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
1864 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1),
1866 expectMsgClass(duration, ReadyTransactionReply.class);
1868 // Abort the second tx while it's queued.
1870 shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1871 expectMsgClass(duration, AbortTransactionReply.class);
1873 // Commit the other 2.
1875 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1876 expectMsgClass(duration, CanCommitTransactionReply.class);
1878 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1879 expectMsgClass(duration, CommitTransactionReply.class);
1881 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1882 expectMsgClass(duration, CanCommitTransactionReply.class);
1884 shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1885 expectMsgClass(duration, CommitTransactionReply.class);
1887 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1893 public void testCreateSnapshotWithNonPersistentData() throws Exception {
1894 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1898 public void testCreateSnapshot() throws Exception {
1899 testCreateSnapshot(true, "testCreateSnapshot");
1902 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception {
1903 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1905 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1906 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
1907 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
1912 public void saveSnapshot(final Object obj) {
1913 savedSnapshot.set(obj);
1914 super.saveSnapshot(obj);
1918 dataStoreContextBuilder.persistent(persistent);
1920 class TestShard extends Shard {
1922 protected TestShard(final AbstractBuilder<?, ?> builder) {
1924 setPersistence(new TestPersistentDataProvider(super.persistence()));
1928 public void handleCommand(final Object message) {
1929 super.handleCommand(message);
1931 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
1932 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
1933 latch.get().countDown();
1938 public RaftActorContext getRaftActorContext() {
1939 return super.getRaftActorContext();
1943 new ShardTestKit(getSystem()) {
1945 final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
1947 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1948 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1951 waitUntilLeader(shard);
1952 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1954 final NormalizedNode<?, ?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
1956 // Trigger creation of a snapshot by ensuring
1957 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
1958 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1959 awaitAndValidateSnapshot(expectedRoot);
1961 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1962 awaitAndValidateSnapshot(expectedRoot);
1965 private void awaitAndValidateSnapshot(final NormalizedNode<?, ?> expectedRoot)
1966 throws InterruptedException, IOException {
1967 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1969 assertTrue("Invalid saved snapshot " + savedSnapshot.get(), savedSnapshot.get() instanceof Snapshot);
1971 verifySnapshot((Snapshot) savedSnapshot.get(), expectedRoot);
1973 latch.set(new CountDownLatch(1));
1974 savedSnapshot.set(null);
1977 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?, ?> expectedRoot)
1978 throws IOException {
1979 final NormalizedNode<?, ?> actual = ((ShardSnapshotState)snapshot.getState()).getSnapshot()
1980 .getRootNode().get();
1981 assertEquals("Root node", expectedRoot, actual);
1987 * This test simply verifies that the applySnapShot logic will work.
1990 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
1991 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
1992 store.setSchemaContext(SCHEMA_CONTEXT);
1994 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
1995 putTransaction.write(TestModel.TEST_PATH,
1996 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1997 commitTransaction(store, putTransaction);
2000 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
2002 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2004 writeTransaction.delete(YangInstanceIdentifier.EMPTY);
2005 writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
2007 commitTransaction(store, writeTransaction);
2009 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
2011 assertEquals(expected, actual);
2015 public void testRecoveryApplicable() {
2017 final DatastoreContext persistentContext = DatastoreContext.newBuilder()
2018 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2020 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext)
2021 .schemaContextProvider(() -> SCHEMA_CONTEXT).props();
2023 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder()
2024 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2026 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext)
2027 .schemaContextProvider(() -> SCHEMA_CONTEXT).props();
2029 new ShardTestKit(getSystem()) {
2031 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2033 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2035 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2037 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2043 public void testOnDatastoreContext() {
2044 new ShardTestKit(getSystem()) {
2046 dataStoreContextBuilder.persistent(true);
2048 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(),
2049 "testOnDatastoreContext");
2051 assertEquals("isRecoveryApplicable", true,
2052 shard.underlyingActor().persistence().isRecoveryApplicable());
2054 waitUntilLeader(shard);
2056 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2058 assertEquals("isRecoveryApplicable", false,
2059 shard.underlyingActor().persistence().isRecoveryApplicable());
2061 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2063 assertEquals("isRecoveryApplicable", true,
2064 shard.underlyingActor().persistence().isRecoveryApplicable());
2070 public void testRegisterRoleChangeListener() throws Exception {
2071 new ShardTestKit(getSystem()) {
2073 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2074 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2075 "testRegisterRoleChangeListener");
2077 waitUntilLeader(shard);
2079 final ActorRef listener = getSystem().actorOf(MessageCollectorActor.props());
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 testClusteredDataChangeListenerWithDelayedRegistration() throws Exception {
2125 new ShardTestKit(getSystem()) {
2127 final String testName = "testClusteredDataChangeListenerWithDelayedRegistration";
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 RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
2147 RegisterDataTreeNotificationListenerReply.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 .schemaContextProvider(() -> 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 .schemaContextProvider(() -> 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 RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
2197 RegisterDataTreeNotificationListenerReply.class);
2198 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2200 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2202 listener.waitForChangeEvents();
2208 public void testClusteredDataTreeChangeListenerWithDelayedRegistration() throws Exception {
2209 new ShardTestKit(getSystem()) {
2211 final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistration";
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 RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
2229 RegisterDataTreeNotificationListenerReply.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 testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed() throws Exception {
2242 new ShardTestKit(getSystem()) {
2244 final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed";
2245 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2246 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2248 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(0);
2249 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
2250 TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2252 setupInMemorySnapshotStore();
2254 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2255 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2256 actorFactory.generateActorId(testName + "-shard"));
2258 waitUntilNoLeader(shard);
2260 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2261 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
2262 RegisterDataTreeNotificationListenerReply.class);
2263 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2265 final ActorSelection regActor = getSystem().actorSelection(reply.getListenerRegistrationPath());
2266 regActor.tell(CloseDataTreeNotificationListenerRegistration.getInstance(), getRef());
2267 expectMsgClass(CloseDataTreeNotificationListenerRegistrationReply.class);
2269 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2270 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2272 listener.expectNoMoreChanges("Received unexpected change after close");
2278 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2279 new ShardTestKit(getSystem()) {
2281 final String testName = "testClusteredDataTreeChangeListenerRegistration";
2282 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2283 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2285 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2286 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2288 final TestActorRef<Shard> followerShard = actorFactory
2289 .createTestActor(Shard.builder().id(followerShardID)
2290 .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
2291 .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2292 "akka://test/user/" + leaderShardID.toString()))
2293 .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
2294 .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2296 final TestActorRef<Shard> leaderShard = actorFactory
2297 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
2298 .peerAddresses(Collections.singletonMap(followerShardID.toString(),
2299 "akka://test/user/" + followerShardID.toString()))
2300 .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
2301 .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2303 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2304 final String leaderPath = waitUntilLeader(followerShard);
2305 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2307 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2308 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2309 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
2310 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2312 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2313 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
2314 RegisterDataTreeNotificationListenerReply.class);
2315 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2317 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2319 listener.waitForChangeEvents();
2325 public void testServerRemoved() throws Exception {
2326 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props()
2327 .withDispatcher(Dispatchers.DefaultDispatcherId()));
2329 final ActorRef shard = parent.underlyingActor().context().actorOf(
2330 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2331 "testServerRemoved");
2333 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2335 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);