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();
204 Uninterruptibles.awaitUninterruptibly(
205 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
206 self.tell(message, self);
210 onFirstElectionTimeout.countDown();
212 super.handleCommand(message);
219 setupInMemorySnapshotStore();
221 final YangInstanceIdentifier path = TestModel.TEST_PATH;
222 final MockDataChangeListener listener = new MockDataChangeListener(1);
223 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
224 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
226 final TestActorRef<Shard> shard = actorFactory.createTestActor(
227 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
228 "testRegisterChangeListenerWhenNotLeaderInitially");
230 new ShardTestKit(getSystem()) {
232 // Wait until the shard receives the first ElectionTimeout
234 assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
236 // Now send the RegisterChangeListener and wait for the reply.
237 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.SUBTREE, false),
240 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
241 RegisterDataTreeNotificationListenerReply.class);
242 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
244 // Sanity check - verify the shard is not the leader yet.
245 shard.tell(FindLeader.INSTANCE, getRef());
246 final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
247 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
249 // Signal the onChangeListenerRegistered latch to tell the
250 // thread above to proceed
251 // with the election process.
252 onChangeListenerRegistered.countDown();
254 // Wait for the shard to become the leader and notify our
255 // listener with the existing
256 // data in the store.
257 listener.waitForChangeEvents(path);
263 public void testRegisterDataTreeChangeListener() throws Exception {
264 new ShardTestKit(getSystem()) {
266 final TestActorRef<Shard> shard = actorFactory.createTestActor(
267 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
268 "testRegisterDataTreeChangeListener");
270 waitUntilLeader(shard);
272 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
274 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
275 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
276 TestModel.TEST_PATH), "testRegisterDataTreeChangeListener-DataTreeChangeListener");
278 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
280 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("3 seconds"),
281 RegisterDataTreeNotificationListenerReply.class);
282 final String replyPath = reply.getListenerRegistrationPath().toString();
283 assertTrue("Incorrect reply path: " + replyPath,
284 replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
286 final YangInstanceIdentifier path = TestModel.TEST_PATH;
287 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
289 listener.waitForChangeEvents();
294 @SuppressWarnings("serial")
296 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
297 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
298 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
299 final Creator<Shard> creator = new Creator<Shard>() {
300 boolean firstElectionTimeout = true;
303 public Shard create() throws Exception {
304 return new Shard(newShardBuilder()) {
306 public void handleCommand(final Object message) {
307 if (message instanceof ElectionTimeout && firstElectionTimeout) {
308 firstElectionTimeout = false;
309 final ActorRef self = getSelf();
313 Uninterruptibles.awaitUninterruptibly(
314 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
315 self.tell(message, self);
319 onFirstElectionTimeout.countDown();
321 super.handleCommand(message);
328 setupInMemorySnapshotStore();
330 final YangInstanceIdentifier path = TestModel.TEST_PATH;
331 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
332 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
333 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
335 final TestActorRef<Shard> shard = actorFactory.createTestActor(
336 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
337 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
339 new ShardTestKit(getSystem()) {
341 assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
343 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
344 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
345 RegisterDataTreeNotificationListenerReply.class);
346 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
348 shard.tell(FindLeader.INSTANCE, getRef());
349 final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
350 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
352 onChangeListenerRegistered.countDown();
354 // TODO: investigate why we do not receive data chage events
355 listener.waitForChangeEvents();
361 public void testCreateTransaction() {
362 new ShardTestKit(getSystem()) {
364 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
366 waitUntilLeader(shard);
368 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
370 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
371 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
373 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
374 CreateTransactionReply.class);
376 final String path = reply.getTransactionPath().toString();
377 assertTrue("Unexpected transaction path " + path, path.startsWith(String.format(
378 "akka://test/user/testCreateTransaction/shard-%s-%s:ShardTransactionTest@0:",
379 shardID.getShardName(), shardID.getMemberName().getName())));
385 public void testCreateTransactionOnChain() {
386 new ShardTestKit(getSystem()) {
388 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
390 waitUntilLeader(shard);
392 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
393 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
395 final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
396 CreateTransactionReply.class);
398 final String path = reply.getTransactionPath().toString();
399 assertTrue("Unexpected transaction path " + path, path.startsWith(String.format(
400 "akka://test/user/testCreateTransactionOnChain/shard-%s-%s:ShardTransactionTest@0:",
401 shardID.getShardName(), shardID.getMemberName().getName())));
407 public void testPeerAddressResolved() throws Exception {
408 new ShardTestKit(getSystem()) {
410 final ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"),
412 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder()
413 .peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null))
414 .props().withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
416 final String address = "akka://foobar";
417 shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
419 shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
420 final OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
421 assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
427 public void testApplySnapshot() throws Exception {
429 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps()
430 .withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplySnapshot");
432 ShardTestKit.waitUntilLeader(shard);
434 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
435 store.setSchemaContext(SCHEMA_CONTEXT);
437 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
438 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
439 .withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
440 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
442 writeToStore(store, TestModel.TEST_PATH, container);
444 final YangInstanceIdentifier root = YangInstanceIdentifier.EMPTY;
445 final NormalizedNode<?,?> expected = readStore(store, root);
447 final Snapshot snapshot = Snapshot.create(
448 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(expected)),
449 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4, -1, null, null);
451 shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
453 final Stopwatch sw = Stopwatch.createStarted();
454 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
455 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
458 assertEquals("Root node", expected, readStore(shard, root));
460 } catch (final AssertionError e) {
465 fail("Snapshot was not applied");
469 public void testApplyState() throws Exception {
470 final TestActorRef<Shard> shard = actorFactory.createTestActor(
471 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");
473 ShardTestKit.waitUntilLeader(shard);
475 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
476 store.setSchemaContext(SCHEMA_CONTEXT);
478 final DataTreeModification writeMod = store.takeSnapshot().newModification();
479 final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
480 writeMod.write(TestModel.TEST_PATH, node);
483 final TransactionIdentifier tx = nextTransactionId();
484 shard.underlyingActor().applyState(null, null, payloadForModification(store, writeMod, tx));
486 final Stopwatch sw = Stopwatch.createStarted();
487 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
488 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
490 final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
491 if (actual != null) {
492 assertEquals("Applied state", node, actual);
497 fail("State was not applied");
501 public void testDataTreeCandidateRecovery() throws Exception {
502 // Set up the InMemorySnapshotStore.
503 final DataTree source = setupInMemorySnapshotStore();
505 final DataTreeModification writeMod = source.takeSnapshot().newModification();
506 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
508 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
510 // Set up the InMemoryJournal.
511 InMemoryJournal.addEntry(shardID.toString(), 1, new SimpleReplicatedLogEntry(0, 1,
512 payloadForModification(source, writeMod, nextTransactionId())));
514 final int nListEntries = 16;
515 final Set<Integer> listEntryKeys = new HashSet<>();
517 // Add some ModificationPayload entries
518 for (int i = 1; i <= nListEntries; i++) {
519 listEntryKeys.add(Integer.valueOf(i));
521 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
522 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
524 final DataTreeModification mod = source.takeSnapshot().newModification();
525 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
528 InMemoryJournal.addEntry(shardID.toString(), i + 1, new SimpleReplicatedLogEntry(i, 1,
529 payloadForModification(source, mod, nextTransactionId())));
532 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
533 new ApplyJournalEntries(nListEntries));
535 testRecovery(listEntryKeys);
539 @SuppressWarnings("checkstyle:IllegalCatch")
540 public void testConcurrentThreePhaseCommits() throws Exception {
541 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
542 final CountDownLatch commitLatch = new CountDownLatch(2);
544 final long timeoutSec = 5;
545 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
546 final Timeout timeout = new Timeout(duration);
548 final TestActorRef<Shard> shard = actorFactory.createTestActor(
549 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
550 "testConcurrentThreePhaseCommits");
552 class OnFutureComplete extends OnComplete<Object> {
553 private final Class<?> expRespType;
555 OnFutureComplete(final Class<?> expRespType) {
556 this.expRespType = expRespType;
560 public void onComplete(final Throwable error, final Object resp) {
562 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
565 assertEquals("Commit response type", expRespType, resp.getClass());
567 } catch (final Exception e) {
573 void onSuccess(final Object resp) throws Exception {
577 class OnCommitFutureComplete extends OnFutureComplete {
578 OnCommitFutureComplete() {
579 super(CommitTransactionReply.class);
583 public void onComplete(final Throwable error, final Object resp) {
584 super.onComplete(error, resp);
585 commitLatch.countDown();
589 class OnCanCommitFutureComplete extends OnFutureComplete {
590 private final TransactionIdentifier transactionID;
592 OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
593 super(CanCommitTransactionReply.class);
594 this.transactionID = transactionID;
598 void onSuccess(final Object resp) throws Exception {
599 final CanCommitTransactionReply canCommitReply =
600 CanCommitTransactionReply.fromSerializable(resp);
601 assertEquals("Can commit", true, canCommitReply.getCanCommit());
603 final Future<Object> commitFuture = Patterns.ask(shard,
604 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
605 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
609 new ShardTestKit(getSystem()) {
611 waitUntilLeader(shard);
613 final TransactionIdentifier transactionID1 = nextTransactionId();
614 final TransactionIdentifier transactionID2 = nextTransactionId();
615 final TransactionIdentifier transactionID3 = nextTransactionId();
617 final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
618 shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
619 final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
620 final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
621 final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
623 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
624 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
625 final ReadyTransactionReply readyReply = ReadyTransactionReply
626 .fromSerializable(expectMsgClass(duration, ReadyTransactionReply.class));
627 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
628 // Send the CanCommitTransaction message for the first Tx.
630 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
631 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
632 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
633 assertEquals("Can commit", true, canCommitReply.getCanCommit());
635 // Ready 2 more Tx's.
637 shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
638 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
639 expectMsgClass(duration, ReadyTransactionReply.class);
642 prepareBatchedModifications(transactionID3,
643 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
644 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
645 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
647 expectMsgClass(duration, ReadyTransactionReply.class);
649 // Send the CanCommitTransaction message for the next 2 Tx's.
650 // These should get queued and
651 // processed after the first Tx completes.
653 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
654 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
656 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
657 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
659 // Send the CommitTransaction message for the first Tx. After it
660 // completes, it should
661 // trigger the 2nd Tx to proceed which should in turn then
664 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
665 expectMsgClass(duration, CommitTransactionReply.class);
667 // Wait for the next 2 Tx's to complete.
669 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2), getSystem().dispatcher());
671 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3), getSystem().dispatcher());
673 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
675 if (caughtEx.get() != null) {
676 Throwables.propagateIfInstanceOf(caughtEx.get(), Exception.class);
677 Throwables.propagate(caughtEx.get());
680 assertEquals("Commits complete", true, done);
682 // final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
683 // cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
684 // cohort3.getPreCommit(), cohort3.getCommit());
685 // inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
686 // inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
687 // inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
688 // inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
689 // inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
690 // inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
691 // inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
692 // inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
693 // inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
695 // Verify data in the data store.
697 verifyOuterListEntry(shard, 1);
699 verifyLastApplied(shard, 2);
705 public void testBatchedModificationsWithNoCommitOnReady() throws Exception {
706 new ShardTestKit(getSystem()) {
708 final TestActorRef<Shard> shard = actorFactory.createTestActor(
709 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
710 "testBatchedModificationsWithNoCommitOnReady");
712 waitUntilLeader(shard);
714 final TransactionIdentifier transactionID = nextTransactionId();
715 final FiniteDuration duration = duration("5 seconds");
717 // Send a BatchedModifications to start a transaction.
719 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
720 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
721 expectMsgClass(duration, BatchedModificationsReply.class);
723 // Send a couple more BatchedModifications.
726 newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
727 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
729 expectMsgClass(duration, BatchedModificationsReply.class);
731 shard.tell(newBatchedModifications(transactionID,
732 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
733 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
734 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3),
736 expectMsgClass(duration, ReadyTransactionReply.class);
738 // Send the CanCommitTransaction message.
740 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
741 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
742 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
743 assertEquals("Can commit", true, canCommitReply.getCanCommit());
745 // Send the CommitTransaction message.
747 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
748 expectMsgClass(duration, CommitTransactionReply.class);
750 // Verify data in the data store.
752 verifyOuterListEntry(shard, 1);
758 public void testBatchedModificationsWithCommitOnReady() throws Exception {
759 new ShardTestKit(getSystem()) {
761 final TestActorRef<Shard> shard = actorFactory.createTestActor(
762 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
763 "testBatchedModificationsWithCommitOnReady");
765 waitUntilLeader(shard);
767 final TransactionIdentifier transactionID = nextTransactionId();
768 final FiniteDuration duration = duration("5 seconds");
770 // Send a BatchedModifications to start a transaction.
772 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
773 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
774 expectMsgClass(duration, BatchedModificationsReply.class);
776 // Send a couple more BatchedModifications.
778 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
779 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
781 expectMsgClass(duration, BatchedModificationsReply.class);
783 shard.tell(newBatchedModifications(transactionID,
784 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
785 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
786 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3),
789 expectMsgClass(duration, CommitTransactionReply.class);
791 // Verify data in the data store.
793 verifyOuterListEntry(shard, 1);
798 @Test(expected = IllegalStateException.class)
799 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
800 new ShardTestKit(getSystem()) {
802 final TestActorRef<Shard> shard = actorFactory.createTestActor(
803 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
804 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
806 waitUntilLeader(shard);
808 final TransactionIdentifier transactionID = nextTransactionId();
809 final BatchedModifications batched = new BatchedModifications(transactionID,
810 DataStoreVersions.CURRENT_VERSION);
811 batched.setReady(true);
812 batched.setTotalMessagesSent(2);
814 shard.tell(batched, getRef());
816 final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
818 if (failure != null) {
819 Throwables.propagateIfInstanceOf(failure.cause(), Exception.class);
820 Throwables.propagate(failure.cause());
827 public void testBatchedModificationsWithOperationFailure() throws Exception {
828 new ShardTestKit(getSystem()) {
830 final TestActorRef<Shard> shard = actorFactory.createTestActor(
831 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
832 "testBatchedModificationsWithOperationFailure");
834 waitUntilLeader(shard);
836 // Test merge with invalid data. An exception should occur when
837 // the merge is applied. Note that
838 // write will not validate the children for performance reasons.
840 final TransactionIdentifier transactionID = nextTransactionId();
842 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
843 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
844 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
846 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
847 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
848 shard.tell(batched, getRef());
849 Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
851 final Throwable cause = failure.cause();
853 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
854 batched.setReady(true);
855 batched.setTotalMessagesSent(2);
857 shard.tell(batched, getRef());
859 failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
860 assertEquals("Failure cause", cause, failure.cause());
866 public void testBatchedModificationsOnTransactionChain() throws Exception {
867 new ShardTestKit(getSystem()) {
869 final TestActorRef<Shard> shard = actorFactory.createTestActor(
870 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
871 "testBatchedModificationsOnTransactionChain");
873 waitUntilLeader(shard);
875 final LocalHistoryIdentifier historyId = nextHistoryId();
876 final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
877 final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
879 final FiniteDuration duration = duration("5 seconds");
881 // Send a BatchedModifications to start a chained write
882 // transaction and ready it.
884 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
885 final YangInstanceIdentifier path = TestModel.TEST_PATH;
886 shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
887 expectMsgClass(duration, ReadyTransactionReply.class);
889 // Create a read Tx on the same chain.
891 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
892 DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
894 final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"),
895 CreateTransactionReply.class);
897 getSystem().actorSelection(createReply.getTransactionPath())
898 .tell(new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
899 final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
900 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
902 // Commit the write transaction.
904 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
905 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
906 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
907 assertEquals("Can commit", true, canCommitReply.getCanCommit());
909 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
910 expectMsgClass(duration, CommitTransactionReply.class);
912 // Verify data in the data store.
914 final NormalizedNode<?, ?> actualNode = readStore(shard, path);
915 assertEquals("Stored node", containerNode, actualNode);
921 public void testOnBatchedModificationsWhenNotLeader() {
922 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
923 new ShardTestKit(getSystem()) {
925 final Creator<Shard> creator = new Creator<Shard>() {
926 private static final long serialVersionUID = 1L;
929 public Shard create() throws Exception {
930 return new Shard(newShardBuilder()) {
932 protected boolean isLeader() {
933 return overrideLeaderCalls.get() ? false : super.isLeader();
937 public ActorSelection getLeader() {
938 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path())
945 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
946 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
947 "testOnBatchedModificationsWhenNotLeader");
949 waitUntilLeader(shard);
951 overrideLeaderCalls.set(true);
953 final BatchedModifications batched = new BatchedModifications(nextTransactionId(),
954 DataStoreVersions.CURRENT_VERSION);
956 shard.tell(batched, ActorRef.noSender());
958 expectMsgEquals(batched);
964 public void testTransactionMessagesWithNoLeader() {
965 new ShardTestKit(getSystem()) {
967 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
968 .shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
969 final TestActorRef<Shard> shard = actorFactory.createTestActor(
970 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
971 "testTransactionMessagesWithNoLeader");
973 waitUntilNoLeader(shard);
975 final TransactionIdentifier txId = nextTransactionId();
976 shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
977 Failure failure = expectMsgClass(Failure.class);
978 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
980 shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
981 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
982 failure = expectMsgClass(Failure.class);
983 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
985 shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
986 failure = expectMsgClass(Failure.class);
987 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
993 public void testReadyWithReadWriteImmediateCommit() throws Exception {
994 testReadyWithImmediateCommit(true);
998 public void testReadyWithWriteOnlyImmediateCommit() throws Exception {
999 testReadyWithImmediateCommit(false);
1002 private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception {
1003 new ShardTestKit(getSystem()) {
1005 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1006 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1007 "testReadyWithImmediateCommit-" + readWrite);
1009 waitUntilLeader(shard);
1011 final TransactionIdentifier transactionID = nextTransactionId();
1012 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1014 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1015 containerNode, true), getRef());
1017 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true),
1021 expectMsgClass(duration("5 seconds"), CommitTransactionReply.class);
1023 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1024 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1030 public void testReadyLocalTransactionWithImmediateCommit() throws Exception {
1031 new ShardTestKit(getSystem()) {
1033 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1034 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1035 "testReadyLocalTransactionWithImmediateCommit");
1037 waitUntilLeader(shard);
1039 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1041 final DataTreeModification modification = dataStore.newModification();
1043 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1044 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1045 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1046 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1048 final TransactionIdentifier txId = nextTransactionId();
1049 modification.ready();
1050 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
1052 shard.tell(readyMessage, getRef());
1054 expectMsgClass(CommitTransactionReply.class);
1056 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1057 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1063 public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception {
1064 new ShardTestKit(getSystem()) {
1066 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1067 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1068 "testReadyLocalTransactionWithThreePhaseCommit");
1070 waitUntilLeader(shard);
1072 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1074 final DataTreeModification modification = dataStore.newModification();
1076 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1077 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
1078 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
1079 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
1081 final TransactionIdentifier txId = nextTransactionId();
1082 modification.ready();
1083 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
1085 shard.tell(readyMessage, getRef());
1087 expectMsgClass(ReadyTransactionReply.class);
1089 // Send the CanCommitTransaction message.
1091 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1092 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1093 .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
1094 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1096 // Send the CanCommitTransaction message.
1098 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
1099 expectMsgClass(CommitTransactionReply.class);
1101 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
1102 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
1108 public void testReadWriteCommitWithPersistenceDisabled() throws Exception {
1109 dataStoreContextBuilder.persistent(false);
1110 new ShardTestKit(getSystem()) {
1112 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1113 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1114 "testCommitWithPersistenceDisabled");
1116 waitUntilLeader(shard);
1118 // Setup a simulated transactions with a mock cohort.
1120 final FiniteDuration duration = duration("5 seconds");
1122 final TransactionIdentifier transactionID = nextTransactionId();
1123 final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1124 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false),
1126 expectMsgClass(duration, ReadyTransactionReply.class);
1128 // Send the CanCommitTransaction message.
1130 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1131 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1132 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1133 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1135 // Send the CanCommitTransaction message.
1137 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1138 expectMsgClass(duration, CommitTransactionReply.class);
1140 final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
1141 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
1147 public void testReadWriteCommitWhenTransactionHasModifications() throws Exception {
1148 testCommitWhenTransactionHasModifications(true);
1152 public void testWriteOnlyCommitWhenTransactionHasModifications() throws Exception {
1153 testCommitWhenTransactionHasModifications(false);
1156 private void testCommitWhenTransactionHasModifications(final boolean readWrite) throws Exception {
1157 new ShardTestKit(getSystem()) {
1159 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1160 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1161 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1162 "testCommitWhenTransactionHasModifications-" + readWrite);
1164 waitUntilLeader(shard);
1166 final FiniteDuration duration = duration("5 seconds");
1167 final TransactionIdentifier transactionID = nextTransactionId();
1170 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
1171 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1173 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1174 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1177 expectMsgClass(duration, ReadyTransactionReply.class);
1179 // Send the CanCommitTransaction message.
1181 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1182 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1183 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1184 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1186 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1187 expectMsgClass(duration, CommitTransactionReply.class);
1189 final InOrder inOrder = inOrder(dataTree);
1190 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1191 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1192 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1194 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
1195 final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
1197 // Use MBean for verification
1198 // Committed transaction count should increase as usual
1199 assertEquals(1, shardStats.getCommittedTransactionsCount());
1201 // Commit index should advance as we do not have an empty
1203 assertEquals(0, shardStats.getCommitIndex());
1209 public void testCommitPhaseFailure() throws Exception {
1210 new ShardTestKit(getSystem()) {
1212 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1213 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1214 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1215 "testCommitPhaseFailure");
1217 waitUntilLeader(shard);
1219 final FiniteDuration duration = duration("5 seconds");
1220 final Timeout timeout = new Timeout(duration);
1222 // Setup 2 simulated transactions with mock cohorts. The first
1226 doThrow(new RuntimeException("mock commit failure")).when(dataTree)
1227 .commit(any(DataTreeCandidate.class));
1229 final TransactionIdentifier transactionID1 = nextTransactionId();
1230 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1231 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1232 expectMsgClass(duration, ReadyTransactionReply.class);
1234 final TransactionIdentifier transactionID2 = nextTransactionId();
1235 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1236 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1237 expectMsgClass(duration, ReadyTransactionReply.class);
1239 // Send the CanCommitTransaction message for the first Tx.
1241 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1242 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1243 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1244 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1246 // Send the CanCommitTransaction message for the 2nd Tx. This
1247 // should get queued and
1248 // processed after the first Tx completes.
1250 final Future<Object> canCommitFuture = Patterns.ask(shard,
1251 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1253 // Send the CommitTransaction message for the first Tx. This
1254 // should send back an error
1255 // and trigger the 2nd Tx to proceed.
1257 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1258 expectMsgClass(duration, akka.actor.Status.Failure.class);
1260 // Wait for the 2nd Tx to complete the canCommit phase.
1262 final CountDownLatch latch = new CountDownLatch(1);
1263 canCommitFuture.onComplete(new OnComplete<Object>() {
1265 public void onComplete(final Throwable failure, final Object resp) {
1268 }, getSystem().dispatcher());
1270 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1272 final InOrder inOrder = inOrder(dataTree);
1273 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1274 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1276 // FIXME: this invocation is done on the result of validate(). To test it, we need to make sure mock
1277 // validate performs wrapping and we capture that mock
1278 // inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1280 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1286 public void testPreCommitPhaseFailure() throws Exception {
1287 new ShardTestKit(getSystem()) {
1289 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1290 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1291 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1292 "testPreCommitPhaseFailure");
1294 waitUntilLeader(shard);
1296 final FiniteDuration duration = duration("5 seconds");
1297 final Timeout timeout = new Timeout(duration);
1299 doThrow(new RuntimeException("mock preCommit failure")).when(dataTree)
1300 .prepare(any(DataTreeModification.class));
1302 final TransactionIdentifier transactionID1 = nextTransactionId();
1303 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1304 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1305 expectMsgClass(duration, ReadyTransactionReply.class);
1307 final TransactionIdentifier transactionID2 = nextTransactionId();
1308 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1309 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1310 expectMsgClass(duration, ReadyTransactionReply.class);
1312 // Send the CanCommitTransaction message for the first Tx.
1314 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1315 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1316 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1317 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1319 // Send the CanCommitTransaction message for the 2nd Tx. This
1320 // should get queued and
1321 // processed after the first Tx completes.
1323 final Future<Object> canCommitFuture = Patterns.ask(shard,
1324 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1326 // Send the CommitTransaction message for the first Tx. This
1327 // should send back an error
1328 // and trigger the 2nd Tx to proceed.
1330 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1331 expectMsgClass(duration, akka.actor.Status.Failure.class);
1333 // Wait for the 2nd Tx to complete the canCommit phase.
1335 final CountDownLatch latch = new CountDownLatch(1);
1336 canCommitFuture.onComplete(new OnComplete<Object>() {
1338 public void onComplete(final Throwable failure, final Object resp) {
1341 }, getSystem().dispatcher());
1343 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1345 final InOrder inOrder = inOrder(dataTree);
1346 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1347 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1348 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1354 public void testCanCommitPhaseFailure() throws Exception {
1355 new ShardTestKit(getSystem()) {
1357 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1358 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1359 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1360 "testCanCommitPhaseFailure");
1362 waitUntilLeader(shard);
1364 final FiniteDuration duration = duration("5 seconds");
1365 final TransactionIdentifier transactionID1 = nextTransactionId();
1367 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1368 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1370 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1371 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1372 expectMsgClass(duration, ReadyTransactionReply.class);
1374 // Send the CanCommitTransaction message.
1376 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1377 expectMsgClass(duration, akka.actor.Status.Failure.class);
1379 // Send another can commit to ensure the failed one got cleaned
1382 final TransactionIdentifier transactionID2 = nextTransactionId();
1383 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1384 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1385 expectMsgClass(duration, ReadyTransactionReply.class);
1387 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1388 final CanCommitTransactionReply reply = CanCommitTransactionReply
1389 .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
1390 assertEquals("getCanCommit", true, reply.getCanCommit());
1396 public void testImmediateCommitWithCanCommitPhaseFailure() throws Exception {
1397 testImmediateCommitWithCanCommitPhaseFailure(true);
1398 testImmediateCommitWithCanCommitPhaseFailure(false);
1401 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Exception {
1402 new ShardTestKit(getSystem()) {
1404 final TipProducingDataTree dataTree = createDelegatingMockDataTree();
1405 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1406 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1407 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1409 waitUntilLeader(shard);
1411 doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
1412 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1414 final FiniteDuration duration = duration("5 seconds");
1416 final TransactionIdentifier transactionID1 = nextTransactionId();
1419 shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
1420 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1422 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1423 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1426 expectMsgClass(duration, akka.actor.Status.Failure.class);
1428 // Send another can commit to ensure the failed one got cleaned
1431 final TransactionIdentifier transactionID2 = nextTransactionId();
1433 shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
1434 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1436 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1437 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1440 expectMsgClass(duration, CommitTransactionReply.class);
1446 public void testAbortWithCommitPending() throws Exception {
1447 new ShardTestKit(getSystem()) {
1449 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
1451 void persistPayload(final Identifier id, final Payload payload,
1452 final boolean batchHint) {
1453 // Simulate an AbortTransaction message occurring during
1454 // replication, after
1455 // persisting and before finishing the commit to the
1458 doAbortTransaction(id, null);
1459 super.persistPayload(id, payload, batchHint);
1463 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1464 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1465 "testAbortWithCommitPending");
1467 waitUntilLeader(shard);
1469 final FiniteDuration duration = duration("5 seconds");
1471 final TransactionIdentifier transactionID = nextTransactionId();
1473 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1474 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1475 expectMsgClass(duration, ReadyTransactionReply.class);
1477 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1478 expectMsgClass(duration, CanCommitTransactionReply.class);
1480 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
1481 expectMsgClass(duration, CommitTransactionReply.class);
1483 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1485 // Since we're simulating an abort occurring during replication
1486 // and before finish commit,
1487 // the data should still get written to the in-memory store
1488 // since we've gotten past
1489 // canCommit and preCommit and persisted the data.
1490 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1496 public void testTransactionCommitTimeout() throws Exception {
1497 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1498 new ShardTestKit(getSystem()) {
1500 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1501 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1502 "testTransactionCommitTimeout");
1504 waitUntilLeader(shard);
1506 final FiniteDuration duration = duration("5 seconds");
1508 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1509 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1510 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1512 // Ready 2 Tx's - the first will timeout
1514 final TransactionIdentifier transactionID1 = nextTransactionId();
1516 prepareBatchedModifications(transactionID1,
1517 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1518 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1519 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
1521 expectMsgClass(duration, ReadyTransactionReply.class);
1523 final TransactionIdentifier transactionID2 = nextTransactionId();
1524 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1525 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1527 prepareBatchedModifications(transactionID2, listNodePath,
1528 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false),
1530 expectMsgClass(duration, ReadyTransactionReply.class);
1532 // canCommit 1st Tx. We don't send the commit so it should
1535 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1536 expectMsgClass(duration, CanCommitTransactionReply.class);
1538 // canCommit the 2nd Tx - it should complete after the 1st Tx
1541 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1542 expectMsgClass(duration, CanCommitTransactionReply.class);
1544 // Try to commit the 1st Tx - should fail as it's not the
1547 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1548 expectMsgClass(duration, akka.actor.Status.Failure.class);
1550 // Commit the 2nd Tx.
1552 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1553 expectMsgClass(duration, CommitTransactionReply.class);
1555 final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1556 assertNotNull(listNodePath + " not found", node);
1563 // public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1564 // dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1566 // new ShardTestKit(getSystem()) {{
1567 // final TestActorRef<Shard> shard = actorFactory.createTestActor(
1568 // newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1569 // "testTransactionCommitQueueCapacityExceeded");
1571 // waitUntilLeader(shard);
1573 // final FiniteDuration duration = duration("5 seconds");
1575 // final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1577 // final TransactionIdentifier transactionID1 = nextTransactionId();
1578 // final MutableCompositeModification modification1 = new MutableCompositeModification();
1579 // final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1580 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID1,
1583 // final TransactionIdentifier transactionID2 = nextTransactionId();
1584 // final MutableCompositeModification modification2 = new MutableCompositeModification();
1585 // final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1586 // TestModel.OUTER_LIST_PATH,
1587 // ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), transactionID2,
1590 // final TransactionIdentifier transactionID3 = nextTransactionId();
1591 // final MutableCompositeModification modification3 = new MutableCompositeModification();
1592 // final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1593 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID3,
1596 // // Ready the Tx's
1598 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1,
1599 // modification1), getRef());
1600 // expectMsgClass(duration, ReadyTransactionReply.class);
1602 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2,
1603 // modification2), getRef());
1604 // expectMsgClass(duration, ReadyTransactionReply.class);
1606 // // The 3rd Tx should exceed queue capacity and fail.
1608 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3,
1609 // modification3), getRef());
1610 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1612 // // canCommit 1st Tx.
1614 // shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1615 // expectMsgClass(duration, CanCommitTransactionReply.class);
1617 // // canCommit the 2nd Tx - it should get queued.
1619 // shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1621 // // canCommit the 3rd Tx - should exceed queue capacity and fail.
1623 // shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1624 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1629 public void testTransactionCommitWithPriorExpiredCohortEntries() throws Exception {
1630 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1631 new ShardTestKit(getSystem()) {
1633 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1634 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1635 "testTransactionCommitWithPriorExpiredCohortEntries");
1637 waitUntilLeader(shard);
1639 final FiniteDuration duration = duration("5 seconds");
1641 final TransactionIdentifier transactionID1 = nextTransactionId();
1642 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1643 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1644 expectMsgClass(duration, ReadyTransactionReply.class);
1646 final TransactionIdentifier transactionID2 = nextTransactionId();
1647 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1648 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1649 expectMsgClass(duration, ReadyTransactionReply.class);
1651 final TransactionIdentifier transactionID3 = nextTransactionId();
1652 shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1653 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1654 expectMsgClass(duration, ReadyTransactionReply.class);
1656 // All Tx's are readied. We'll send canCommit for the last one
1657 // but not the others. The others
1658 // should expire from the queue and the last one should be
1661 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1662 expectMsgClass(duration, CanCommitTransactionReply.class);
1668 public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Exception {
1669 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1670 new ShardTestKit(getSystem()) {
1672 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1673 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1674 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1676 waitUntilLeader(shard);
1678 final FiniteDuration duration = duration("5 seconds");
1680 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1682 final TransactionIdentifier transactionID1 = nextTransactionId();
1683 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1684 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1685 expectMsgClass(duration, ReadyTransactionReply.class);
1687 // CanCommit the first Tx so it's the current in-progress Tx.
1689 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1690 expectMsgClass(duration, CanCommitTransactionReply.class);
1692 // Ready the second Tx.
1694 final TransactionIdentifier transactionID2 = nextTransactionId();
1695 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1696 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
1697 expectMsgClass(duration, ReadyTransactionReply.class);
1699 // Ready the third Tx.
1701 final TransactionIdentifier transactionID3 = nextTransactionId();
1702 final DataTreeModification modification3 = dataStore.newModification();
1703 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1704 .apply(modification3);
1705 modification3.ready();
1706 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3,
1708 shard.tell(readyMessage, getRef());
1710 // Commit the first Tx. After completing, the second should
1711 // expire from the queue and the third
1714 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1715 expectMsgClass(duration, CommitTransactionReply.class);
1717 // Expect commit reply from the third Tx.
1719 expectMsgClass(duration, CommitTransactionReply.class);
1721 final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
1722 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1728 public void testCanCommitBeforeReadyFailure() throws Exception {
1729 new ShardTestKit(getSystem()) {
1731 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1732 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1733 "testCanCommitBeforeReadyFailure");
1735 shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
1736 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1742 public void testAbortAfterCanCommit() throws Exception {
1743 new ShardTestKit(getSystem()) {
1745 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1746 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterCanCommit");
1748 waitUntilLeader(shard);
1750 final FiniteDuration duration = duration("5 seconds");
1751 final Timeout timeout = new Timeout(duration);
1753 // Ready 2 transactions - the first one will be aborted.
1755 final TransactionIdentifier transactionID1 = nextTransactionId();
1756 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1757 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1758 expectMsgClass(duration, ReadyTransactionReply.class);
1760 final TransactionIdentifier transactionID2 = nextTransactionId();
1761 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1762 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1763 expectMsgClass(duration, ReadyTransactionReply.class);
1765 // Send the CanCommitTransaction message for the first Tx.
1767 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1768 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1769 .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
1770 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1772 // Send the CanCommitTransaction message for the 2nd Tx. This
1773 // should get queued and
1774 // processed after the first Tx completes.
1776 final Future<Object> canCommitFuture = Patterns.ask(shard,
1777 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1779 // Send the AbortTransaction message for the first Tx. This
1780 // should trigger the 2nd
1783 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1784 expectMsgClass(duration, AbortTransactionReply.class);
1786 // Wait for the 2nd Tx to complete the canCommit phase.
1788 canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture, duration);
1789 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1795 public void testAbortAfterReady() throws Exception {
1796 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1797 new ShardTestKit(getSystem()) {
1799 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1800 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1802 waitUntilLeader(shard);
1804 final FiniteDuration duration = duration("5 seconds");
1808 final TransactionIdentifier transactionID1 = nextTransactionId();
1809 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1810 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1811 expectMsgClass(duration, ReadyTransactionReply.class);
1813 // Send the AbortTransaction message.
1815 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1816 expectMsgClass(duration, AbortTransactionReply.class);
1818 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1820 // Now send CanCommitTransaction - should fail.
1822 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1823 final Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
1824 assertTrue("Failure type", failure instanceof IllegalStateException);
1826 // Ready and CanCommit another and verify success.
1828 final TransactionIdentifier transactionID2 = nextTransactionId();
1829 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1830 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1831 expectMsgClass(duration, ReadyTransactionReply.class);
1833 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1834 expectMsgClass(duration, CanCommitTransactionReply.class);
1840 public void testAbortQueuedTransaction() throws Exception {
1841 new ShardTestKit(getSystem()) {
1843 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1844 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1846 waitUntilLeader(shard);
1848 final FiniteDuration duration = duration("5 seconds");
1852 final TransactionIdentifier transactionID1 = nextTransactionId();
1853 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1854 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1855 expectMsgClass(duration, ReadyTransactionReply.class);
1857 final TransactionIdentifier transactionID2 = nextTransactionId();
1858 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1859 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
1860 expectMsgClass(duration, ReadyTransactionReply.class);
1862 final TransactionIdentifier transactionID3 = nextTransactionId();
1864 newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
1865 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1),
1867 expectMsgClass(duration, ReadyTransactionReply.class);
1869 // Abort the second tx while it's queued.
1871 shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1872 expectMsgClass(duration, AbortTransactionReply.class);
1874 // Commit the other 2.
1876 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1877 expectMsgClass(duration, CanCommitTransactionReply.class);
1879 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1880 expectMsgClass(duration, CommitTransactionReply.class);
1882 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1883 expectMsgClass(duration, CanCommitTransactionReply.class);
1885 shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1886 expectMsgClass(duration, CommitTransactionReply.class);
1888 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1894 public void testCreateSnapshotWithNonPersistentData() throws Exception {
1895 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1899 public void testCreateSnapshot() throws Exception {
1900 testCreateSnapshot(true, "testCreateSnapshot");
1903 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception {
1904 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1906 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1907 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
1908 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
1913 public void saveSnapshot(final Object obj) {
1914 savedSnapshot.set(obj);
1915 super.saveSnapshot(obj);
1919 dataStoreContextBuilder.persistent(persistent);
1921 class TestShard extends Shard {
1923 protected TestShard(final AbstractBuilder<?, ?> builder) {
1925 setPersistence(new TestPersistentDataProvider(super.persistence()));
1929 public void handleCommand(final Object message) {
1930 super.handleCommand(message);
1932 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
1933 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
1934 latch.get().countDown();
1939 public RaftActorContext getRaftActorContext() {
1940 return super.getRaftActorContext();
1944 new ShardTestKit(getSystem()) {
1946 final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
1948 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
1949 .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1952 waitUntilLeader(shard);
1953 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1955 final NormalizedNode<?, ?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
1957 // Trigger creation of a snapshot by ensuring
1958 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
1959 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1960 awaitAndValidateSnapshot(expectedRoot);
1962 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1963 awaitAndValidateSnapshot(expectedRoot);
1966 private void awaitAndValidateSnapshot(final NormalizedNode<?, ?> expectedRoot)
1967 throws InterruptedException, IOException {
1968 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1970 assertTrue("Invalid saved snapshot " + savedSnapshot.get(), savedSnapshot.get() instanceof Snapshot);
1972 verifySnapshot((Snapshot) savedSnapshot.get(), expectedRoot);
1974 latch.set(new CountDownLatch(1));
1975 savedSnapshot.set(null);
1978 private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?, ?> expectedRoot)
1979 throws IOException {
1980 final NormalizedNode<?, ?> actual = ((ShardSnapshotState)snapshot.getState()).getSnapshot()
1981 .getRootNode().get();
1982 assertEquals("Root node", expectedRoot, actual);
1988 * This test simply verifies that the applySnapShot logic will work.
1991 public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
1992 final DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
1993 store.setSchemaContext(SCHEMA_CONTEXT);
1995 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
1996 putTransaction.write(TestModel.TEST_PATH,
1997 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1998 commitTransaction(store, putTransaction);
2001 final NormalizedNode<?, ?> expected = readStore(store, YangInstanceIdentifier.EMPTY);
2003 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
2005 writeTransaction.delete(YangInstanceIdentifier.EMPTY);
2006 writeTransaction.write(YangInstanceIdentifier.EMPTY, expected);
2008 commitTransaction(store, writeTransaction);
2010 final NormalizedNode<?, ?> actual = readStore(store, YangInstanceIdentifier.EMPTY);
2012 assertEquals(expected, actual);
2016 public void testRecoveryApplicable() {
2018 final DatastoreContext persistentContext = DatastoreContext.newBuilder()
2019 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
2021 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext)
2022 .schemaContext(SCHEMA_CONTEXT).props();
2024 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder()
2025 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
2027 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext)
2028 .schemaContext(SCHEMA_CONTEXT).props();
2030 new ShardTestKit(getSystem()) {
2032 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
2034 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
2036 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
2038 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
2044 public void testOnDatastoreContext() {
2045 new ShardTestKit(getSystem()) {
2047 dataStoreContextBuilder.persistent(true);
2049 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(),
2050 "testOnDatastoreContext");
2052 assertEquals("isRecoveryApplicable", true,
2053 shard.underlyingActor().persistence().isRecoveryApplicable());
2055 waitUntilLeader(shard);
2057 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
2059 assertEquals("isRecoveryApplicable", false,
2060 shard.underlyingActor().persistence().isRecoveryApplicable());
2062 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
2064 assertEquals("isRecoveryApplicable", true,
2065 shard.underlyingActor().persistence().isRecoveryApplicable());
2071 public void testRegisterRoleChangeListener() throws Exception {
2072 new ShardTestKit(getSystem()) {
2074 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2075 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2076 "testRegisterRoleChangeListener");
2078 waitUntilLeader(shard);
2080 final TestActorRef<MessageCollectorActor> listener =
2081 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
2083 shard.tell(new RegisterRoleChangeListener(), listener);
2085 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
2087 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2088 ShardLeaderStateChanged.class);
2089 assertEquals("getLocalShardDataTree present", true,
2090 leaderStateChanged.getLocalShardDataTree().isPresent());
2091 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
2092 leaderStateChanged.getLocalShardDataTree().get());
2094 MessageCollectorActor.clearMessages(listener);
2096 // Force a leader change
2098 shard.tell(new RequestVote(10000, "member2", 50, 50), getRef());
2100 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
2101 ShardLeaderStateChanged.class);
2102 assertEquals("getLocalShardDataTree present", false,
2103 leaderStateChanged.getLocalShardDataTree().isPresent());
2109 public void testFollowerInitialSyncStatus() throws Exception {
2110 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2111 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
2112 "testFollowerInitialSyncStatus");
2114 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false,
2115 "member-1-shard-inventory-operational"));
2117 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2119 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true,
2120 "member-1-shard-inventory-operational"));
2122 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
2126 public void testClusteredDataChangeListenerWithDelayedRegistration() throws Exception {
2127 new ShardTestKit(getSystem()) {
2129 final String testName = "testClusteredDataChangeListenerWithDelayedRegistration";
2130 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2131 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2133 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2134 final MockDataChangeListener listener = new MockDataChangeListener(1);
2135 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
2136 actorFactory.generateActorId(testName + "-DataChangeListener"));
2138 setupInMemorySnapshotStore();
2140 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2141 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2142 actorFactory.generateActorId(testName + "-shard"));
2144 waitUntilNoLeader(shard);
2146 shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true),
2148 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
2149 RegisterDataTreeNotificationListenerReply.class);
2150 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2152 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2153 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2155 listener.waitForChangeEvents();
2161 public void testClusteredDataChangeListenerRegistration() throws Exception {
2162 new ShardTestKit(getSystem()) {
2164 final String testName = "testClusteredDataChangeListenerRegistration";
2165 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2166 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2168 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2169 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2171 final TestActorRef<Shard> followerShard = actorFactory
2172 .createTestActor(Shard.builder().id(followerShardID)
2173 .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
2174 .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2175 "akka://test/user/" + leaderShardID.toString()))
2176 .schemaContext(SCHEMA_CONTEXT).props()
2177 .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2179 final TestActorRef<Shard> leaderShard = actorFactory
2180 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
2181 .peerAddresses(Collections.singletonMap(followerShardID.toString(),
2182 "akka://test/user/" + followerShardID.toString()))
2183 .schemaContext(SCHEMA_CONTEXT).props()
2184 .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2186 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2187 final String leaderPath = waitUntilLeader(followerShard);
2188 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2190 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2191 final MockDataChangeListener listener = new MockDataChangeListener(1);
2192 final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
2193 actorFactory.generateActorId(testName + "-DataChangeListener"));
2196 new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true),
2198 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
2199 RegisterDataTreeNotificationListenerReply.class);
2200 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2202 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2204 listener.waitForChangeEvents();
2210 public void testClusteredDataTreeChangeListenerWithDelayedRegistration() throws Exception {
2211 new ShardTestKit(getSystem()) {
2213 final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistration";
2214 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2215 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2217 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2218 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
2219 TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2221 setupInMemorySnapshotStore();
2223 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2224 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2225 actorFactory.generateActorId(testName + "-shard"));
2227 waitUntilNoLeader(shard);
2229 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2230 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
2231 RegisterDataTreeNotificationListenerReply.class);
2232 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2234 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2235 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2237 listener.waitForChangeEvents();
2243 public void testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed() throws Exception {
2244 new ShardTestKit(getSystem()) {
2246 final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed";
2247 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
2248 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
2250 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(0);
2251 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
2252 TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2254 setupInMemorySnapshotStore();
2256 final TestActorRef<Shard> shard = actorFactory.createTestActor(
2257 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2258 actorFactory.generateActorId(testName + "-shard"));
2260 waitUntilNoLeader(shard);
2262 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2263 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
2264 RegisterDataTreeNotificationListenerReply.class);
2265 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2267 final ActorSelection regActor = getSystem().actorSelection(reply.getListenerRegistrationPath());
2268 regActor.tell(CloseDataTreeNotificationListenerRegistration.getInstance(), getRef());
2269 expectMsgClass(CloseDataTreeNotificationListenerRegistrationReply.class);
2271 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
2272 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
2274 listener.expectNoMoreChanges("Received unexpected change after close");
2280 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
2281 new ShardTestKit(getSystem()) {
2283 final String testName = "testClusteredDataTreeChangeListenerRegistration";
2284 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
2285 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
2287 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
2288 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
2290 final TestActorRef<Shard> followerShard = actorFactory
2291 .createTestActor(Shard.builder().id(followerShardID)
2292 .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
2293 .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
2294 "akka://test/user/" + leaderShardID.toString()))
2295 .schemaContext(SCHEMA_CONTEXT).props()
2296 .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
2298 final TestActorRef<Shard> leaderShard = actorFactory
2299 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
2300 .peerAddresses(Collections.singletonMap(followerShardID.toString(),
2301 "akka://test/user/" + followerShardID.toString()))
2302 .schemaContext(SCHEMA_CONTEXT).props()
2303 .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
2305 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
2306 final String leaderPath = waitUntilLeader(followerShard);
2307 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
2309 final YangInstanceIdentifier path = TestModel.TEST_PATH;
2310 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
2311 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
2312 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
2314 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
2315 final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"),
2316 RegisterDataTreeNotificationListenerReply.class);
2317 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
2319 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
2321 listener.waitForChangeEvents();
2327 public void testServerRemoved() throws Exception {
2328 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props());
2330 final ActorRef shard = parent.underlyingActor().context().actorOf(
2331 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2332 "testServerRemoved");
2334 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2336 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);