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
8 package org.opendaylight.controller.cluster.datastore;
10 import static org.hamcrest.CoreMatchers.containsString;
11 import static org.hamcrest.CoreMatchers.endsWith;
12 import static org.hamcrest.MatcherAssert.assertThat;
13 import static org.junit.Assert.assertEquals;
14 import static org.junit.Assert.assertFalse;
15 import static org.junit.Assert.assertNotNull;
16 import static org.junit.Assert.assertSame;
17 import static org.junit.Assert.assertTrue;
18 import static org.junit.Assert.fail;
19 import static org.mockito.ArgumentMatchers.any;
20 import static org.mockito.Mockito.doThrow;
21 import static org.mockito.Mockito.inOrder;
22 import static org.mockito.Mockito.mock;
23 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
25 import akka.actor.ActorRef;
26 import akka.actor.ActorSelection;
27 import akka.actor.Props;
28 import akka.actor.Status.Failure;
29 import akka.dispatch.Dispatchers;
30 import akka.dispatch.OnComplete;
31 import akka.japi.Creator;
32 import akka.pattern.Patterns;
33 import akka.persistence.SaveSnapshotSuccess;
34 import akka.testkit.TestActorRef;
35 import akka.util.Timeout;
36 import com.google.common.base.Stopwatch;
37 import com.google.common.base.Throwables;
38 import com.google.common.util.concurrent.Uninterruptibles;
39 import java.time.Duration;
40 import java.util.Collections;
41 import java.util.HashSet;
43 import java.util.Optional;
45 import java.util.concurrent.CountDownLatch;
46 import java.util.concurrent.TimeUnit;
47 import java.util.concurrent.atomic.AtomicBoolean;
48 import java.util.concurrent.atomic.AtomicReference;
49 import org.junit.Test;
50 import org.mockito.InOrder;
51 import org.opendaylight.controller.cluster.DataPersistenceProvider;
52 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
53 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
54 import org.opendaylight.controller.cluster.access.concepts.MemberName;
55 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
56 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
57 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
58 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
59 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
60 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
61 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
62 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
64 import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistration;
65 import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistrationReply;
66 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
68 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
69 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
70 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
71 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
72 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
73 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
74 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
76 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply;
77 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
78 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
79 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
80 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
81 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
82 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
83 import org.opendaylight.controller.cluster.datastore.utils.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.Payload;
97 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
98 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
99 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
100 import org.opendaylight.controller.cluster.raft.persisted.SimpleReplicatedLogEntry;
101 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
102 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
103 import org.opendaylight.controller.cluster.raft.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.yangtools.concepts.Identifier;
108 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
109 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
110 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
112 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
113 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
114 import org.opendaylight.yangtools.yang.data.tree.api.DataTree;
115 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
116 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeConfiguration;
117 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
118 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
119 import org.opendaylight.yangtools.yang.data.tree.impl.di.InMemoryDataTreeFactory;
120 import scala.concurrent.Await;
121 import scala.concurrent.Future;
122 import scala.concurrent.duration.FiniteDuration;
124 public class ShardTest extends AbstractShardTest {
125 private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in "
126 + "InMemorySnapshotStore and journal recovery seq number will start from 1";
129 public void testRegisterDataTreeChangeListener() throws Exception {
130 final ShardTestKit testKit = new ShardTestKit(getSystem());
131 final TestActorRef<Shard> shard = actorFactory.createTestActor(
132 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
133 "testRegisterDataTreeChangeListener");
135 ShardTestKit.waitUntilLeader(shard);
137 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
139 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
140 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
141 TestModel.TEST_PATH), "testRegisterDataTreeChangeListener-DataTreeChangeListener");
143 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), testKit.getRef());
145 final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(Duration.ofSeconds(3),
146 RegisterDataTreeNotificationListenerReply.class);
147 final String replyPath = reply.getListenerRegistrationPath().toString();
148 assertTrue("Incorrect reply path: " + replyPath,
149 replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
151 final YangInstanceIdentifier path = TestModel.TEST_PATH;
152 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
154 listener.waitForChangeEvents();
155 listener.verifyOnInitialDataEvent();
157 final MockDataTreeChangeListener listener2 = new MockDataTreeChangeListener(1);
158 final ActorRef dclActor2 = actorFactory.createActor(DataTreeChangeListenerActor.props(listener2,
159 TestModel.TEST_PATH), "testRegisterDataTreeChangeListener-DataTreeChangeListener2");
161 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor2, false), testKit.getRef());
163 testKit.expectMsgClass(Duration.ofSeconds(3), RegisterDataTreeNotificationListenerReply.class);
165 listener2.waitForChangeEvents();
166 listener2.verifyNoOnInitialDataEvent();
169 @SuppressWarnings("serial")
171 public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
172 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
173 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
174 final Creator<Shard> creator = new Creator<>() {
175 boolean firstElectionTimeout = true;
178 public Shard create() {
179 return new Shard(newShardBuilder()) {
181 public void handleCommand(final Object message) {
182 if (message instanceof ElectionTimeout && firstElectionTimeout) {
183 firstElectionTimeout = false;
184 final ActorRef self = getSelf();
186 Uninterruptibles.awaitUninterruptibly(
187 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
188 self.tell(message, self);
191 onFirstElectionTimeout.countDown();
193 super.handleCommand(message);
200 setupInMemorySnapshotStore();
202 final YangInstanceIdentifier path = TestModel.TEST_PATH;
203 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
204 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
205 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
207 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props.create(Shard.class,
208 new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
209 "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
211 final ShardTestKit testKit = new ShardTestKit(getSystem());
212 assertTrue("Got first ElectionTimeout", onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
214 shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), testKit.getRef());
215 final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(Duration.ofSeconds(5),
216 RegisterDataTreeNotificationListenerReply.class);
217 assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
219 shard.tell(FindLeader.INSTANCE, testKit.getRef());
220 final FindLeaderReply findLeadeReply = testKit.expectMsgClass(Duration.ofSeconds(5), FindLeaderReply.class);
221 assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
223 onChangeListenerRegistered.countDown();
225 // TODO: investigate why we do not receive data chage events
226 listener.waitForChangeEvents();
230 public void testCreateTransaction() {
231 final ShardTestKit testKit = new ShardTestKit(getSystem());
232 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
234 ShardTestKit.waitUntilLeader(shard);
236 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), testKit.getRef());
238 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
239 DataStoreVersions.CURRENT_VERSION).toSerializable(), testKit.getRef());
241 final CreateTransactionReply reply = testKit.expectMsgClass(Duration.ofSeconds(3),
242 CreateTransactionReply.class);
244 final String path = reply.getTransactionPath().toString();
245 assertThat(path, containsString(String.format("/user/testCreateTransaction/shard-%s-%s:ShardTransactionTest@0:",
246 shardID.getShardName(), shardID.getMemberName().getName())));
250 public void testCreateTransactionOnChain() {
251 final ShardTestKit testKit = new ShardTestKit(getSystem());
252 final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
254 ShardTestKit.waitUntilLeader(shard);
256 shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
257 DataStoreVersions.CURRENT_VERSION).toSerializable(), testKit.getRef());
259 final CreateTransactionReply reply = testKit.expectMsgClass(Duration.ofSeconds(3),
260 CreateTransactionReply.class);
262 final String path = reply.getTransactionPath().toString();
263 assertThat(path, containsString(String.format(
264 "/user/testCreateTransactionOnChain/shard-%s-%s:ShardTransactionTest@0:",
265 shardID.getShardName(), shardID.getMemberName().getName())));
269 public void testPeerAddressResolved() {
270 final ShardTestKit testKit = new ShardTestKit(getSystem());
271 final ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"),
273 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder()
274 .peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null))
275 .props().withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
277 final String address = "akka://foobar";
278 shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
280 shard.tell(GetOnDemandRaftState.INSTANCE, testKit.getRef());
281 final OnDemandRaftState state = testKit.expectMsgClass(OnDemandRaftState.class);
282 assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
286 public void testApplySnapshot() throws Exception {
288 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps()
289 .withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplySnapshot");
291 ShardTestKit.waitUntilLeader(shard);
293 final DataTree store = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL,
296 final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
297 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
298 .withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
299 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
301 writeToStore(store, TestModel.TEST_PATH, container);
303 final YangInstanceIdentifier root = YangInstanceIdentifier.empty();
304 final NormalizedNode expected = readStore(store, root);
306 final Snapshot snapshot = Snapshot.create(new ShardSnapshotState(new MetadataShardDataTreeSnapshot(expected)),
307 Collections.emptyList(), 1, 2, 3, 4, -1, null, null);
309 shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
311 final Stopwatch sw = Stopwatch.createStarted();
312 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
313 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
316 assertEquals("Root node", expected, readStore(shard, root));
318 } catch (final AssertionError e) {
323 fail("Snapshot was not applied");
327 public void testApplyState() throws Exception {
328 final TestActorRef<Shard> shard = actorFactory.createTestActor(
329 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplyState");
331 ShardTestKit.waitUntilLeader(shard);
333 final DataTree store = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL,
336 final DataTreeModification writeMod = store.takeSnapshot().newModification();
337 final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
338 writeMod.write(TestModel.TEST_PATH, node);
341 final TransactionIdentifier tx = nextTransactionId();
342 shard.underlyingActor().applyState(null, null, payloadForModification(store, writeMod, tx));
344 final Stopwatch sw = Stopwatch.createStarted();
345 while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
346 Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
348 final NormalizedNode actual = readStore(shard, TestModel.TEST_PATH);
349 if (actual != null) {
350 assertEquals("Applied state", node, actual);
355 fail("State was not applied");
359 public void testDataTreeCandidateRecovery() throws Exception {
360 // Set up the InMemorySnapshotStore.
361 final DataTree source = setupInMemorySnapshotStore();
363 final DataTreeModification writeMod = source.takeSnapshot().newModification();
364 writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
366 InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
368 // Set up the InMemoryJournal.
369 InMemoryJournal.addEntry(shardID.toString(), 1, new SimpleReplicatedLogEntry(0, 1,
370 payloadForModification(source, writeMod, nextTransactionId())));
372 final int nListEntries = 16;
373 final Set<Integer> listEntryKeys = new HashSet<>();
375 // Add some ModificationPayload entries
376 for (int i = 1; i <= nListEntries; i++) {
377 listEntryKeys.add(i);
379 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
380 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
382 final DataTreeModification mod = source.takeSnapshot().newModification();
383 mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
386 InMemoryJournal.addEntry(shardID.toString(), i + 1, new SimpleReplicatedLogEntry(i, 1,
387 payloadForModification(source, mod, nextTransactionId())));
390 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2,
391 new ApplyJournalEntries(nListEntries));
393 testRecovery(listEntryKeys, true);
397 @SuppressWarnings("checkstyle:IllegalCatch")
398 public void testConcurrentThreePhaseCommits() throws Exception {
399 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
400 final CountDownLatch commitLatch = new CountDownLatch(2);
402 final long timeoutSec = 5;
403 final Duration duration = Duration.ofSeconds(timeoutSec);
404 final Timeout timeout = Timeout.create(duration);
406 final TestActorRef<Shard> shard = actorFactory.createTestActor(
407 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
408 "testConcurrentThreePhaseCommits");
410 class OnFutureComplete extends OnComplete<Object> {
411 private final Class<?> expRespType;
413 OnFutureComplete(final Class<?> expRespType) {
414 this.expRespType = expRespType;
418 public void onComplete(final Throwable error, final Object resp) {
420 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
423 assertEquals("Commit response type", expRespType, resp.getClass());
425 } catch (final Exception e) {
431 void onSuccess(final Object resp) {
435 class OnCommitFutureComplete extends OnFutureComplete {
436 OnCommitFutureComplete() {
437 super(CommitTransactionReply.class);
441 public void onComplete(final Throwable error, final Object resp) {
442 super.onComplete(error, resp);
443 commitLatch.countDown();
447 class OnCanCommitFutureComplete extends OnFutureComplete {
448 private final TransactionIdentifier transactionID;
450 OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
451 super(CanCommitTransactionReply.class);
452 this.transactionID = transactionID;
456 void onSuccess(final Object resp) {
457 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(resp);
458 assertTrue("Can commit", canCommitReply.getCanCommit());
460 final Future<Object> commitFuture = Patterns.ask(shard,
461 new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
462 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
466 final ShardTestKit testKit = new ShardTestKit(getSystem());
467 ShardTestKit.waitUntilLeader(shard);
469 final TransactionIdentifier transactionID1 = nextTransactionId();
470 final TransactionIdentifier transactionID2 = nextTransactionId();
471 final TransactionIdentifier transactionID3 = nextTransactionId();
473 final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
474 shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
475 final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
476 final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
477 final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
479 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
480 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
481 final ReadyTransactionReply readyReply = ReadyTransactionReply
482 .fromSerializable(testKit.expectMsgClass(duration, ReadyTransactionReply.class));
484 String pathSuffix = shard.path().toString().replaceFirst("akka://test", "");
485 assertThat(readyReply.getCohortPath(), endsWith(pathSuffix));
486 // Send the CanCommitTransaction message for the first Tx.
488 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
489 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
490 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
491 assertTrue("Can commit", canCommitReply.getCanCommit());
493 // Ready 2 more Tx's.
495 shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
496 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), testKit.getRef());
497 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
500 prepareBatchedModifications(transactionID3,
501 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
502 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
503 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false), testKit.getRef());
504 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
506 // Send the CanCommitTransaction message for the next 2 Tx's.
507 // These should get queued and
508 // processed after the first Tx completes.
510 final Future<Object> canCommitFuture1 = Patterns.ask(shard,
511 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
513 final Future<Object> canCommitFuture2 = Patterns.ask(shard,
514 new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
516 // Send the CommitTransaction message for the first Tx. After it
517 // completes, it should
518 // trigger the 2nd Tx to proceed which should in turn then
521 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
522 testKit.expectMsgClass(duration, CommitTransactionReply.class);
524 // Wait for the next 2 Tx's to complete.
526 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2), getSystem().dispatcher());
528 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3), getSystem().dispatcher());
530 final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
532 final Throwable t = caughtEx.get();
534 Throwables.propagateIfPossible(t, Exception.class);
535 throw new RuntimeException(t);
538 assertTrue("Commits complete", done);
540 // final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
541 // cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
542 // cohort3.getPreCommit(), cohort3.getCommit());
543 // inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
544 // inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
545 // inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
546 // inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
547 // inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
548 // inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
549 // inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
550 // inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
551 // inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
553 // Verify data in the data store.
555 verifyOuterListEntry(shard, 1);
557 verifyLastApplied(shard, 3);
561 public void testBatchedModificationsWithNoCommitOnReady() {
562 final ShardTestKit testKit = new ShardTestKit(getSystem());
563 final TestActorRef<Shard> shard = actorFactory.createTestActor(
564 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
565 "testBatchedModificationsWithNoCommitOnReady");
567 ShardTestKit.waitUntilLeader(shard);
569 final TransactionIdentifier transactionID = nextTransactionId();
570 final Duration duration = Duration.ofSeconds(5);
572 // Send a BatchedModifications to start a transaction.
574 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
575 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), testKit.getRef());
576 testKit.expectMsgClass(duration, BatchedModificationsReply.class);
578 // Send a couple more BatchedModifications.
580 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
581 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
583 testKit.expectMsgClass(duration, BatchedModificationsReply.class);
585 shard.tell(newBatchedModifications(transactionID,
586 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
587 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
588 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3),
590 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
592 // Send the CanCommitTransaction message.
594 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
595 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
596 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
597 assertTrue("Can commit", canCommitReply.getCanCommit());
599 // Send the CommitTransaction message.
601 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
602 testKit.expectMsgClass(duration, CommitTransactionReply.class);
604 // Verify data in the data store.
606 verifyOuterListEntry(shard, 1);
610 public void testBatchedModificationsWithCommitOnReady() {
611 final ShardTestKit testKit = new ShardTestKit(getSystem());
612 final TestActorRef<Shard> shard = actorFactory.createTestActor(
613 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
614 "testBatchedModificationsWithCommitOnReady");
616 ShardTestKit.waitUntilLeader(shard);
618 final TransactionIdentifier transactionID = nextTransactionId();
619 final Duration duration = Duration.ofSeconds(5);
621 // Send a BatchedModifications to start a transaction.
623 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
624 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), testKit.getRef());
625 testKit.expectMsgClass(duration, BatchedModificationsReply.class);
627 // Send a couple more BatchedModifications.
629 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
630 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
632 testKit.expectMsgClass(duration, BatchedModificationsReply.class);
634 shard.tell(newBatchedModifications(transactionID,
635 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
636 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
637 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3),
640 testKit.expectMsgClass(duration, CommitTransactionReply.class);
642 // Verify data in the data store.
643 verifyOuterListEntry(shard, 1);
646 @Test(expected = IllegalStateException.class)
647 public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
648 final ShardTestKit testKit = new ShardTestKit(getSystem());
649 final TestActorRef<Shard> shard = actorFactory.createTestActor(
650 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
651 "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
653 ShardTestKit.waitUntilLeader(shard);
655 final TransactionIdentifier transactionID = nextTransactionId();
656 final BatchedModifications batched = new BatchedModifications(transactionID,
657 DataStoreVersions.CURRENT_VERSION);
659 batched.setTotalMessagesSent(2);
661 shard.tell(batched, testKit.getRef());
663 final Failure failure = testKit.expectMsgClass(Duration.ofSeconds(5), Failure.class);
665 if (failure != null) {
666 Throwables.propagateIfPossible(failure.cause(), Exception.class);
667 throw new RuntimeException(failure.cause());
672 public void testBatchedModificationsWithOperationFailure() {
673 final ShardTestKit testKit = new ShardTestKit(getSystem());
674 final TestActorRef<Shard> shard = actorFactory.createTestActor(
675 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
676 "testBatchedModificationsWithOperationFailure");
678 ShardTestKit.waitUntilLeader(shard);
680 // Test merge with invalid data. An exception should occur when
681 // the merge is applied. Note that
682 // write will not validate the children for performance reasons.
684 final TransactionIdentifier transactionID = nextTransactionId();
686 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
687 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
688 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
690 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
691 batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
692 shard.tell(batched, testKit.getRef());
693 Failure failure = testKit.expectMsgClass(Duration.ofSeconds(5), akka.actor.Status.Failure.class);
695 final Throwable cause = failure.cause();
697 batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
699 batched.setTotalMessagesSent(2);
701 shard.tell(batched, testKit.getRef());
703 failure = testKit.expectMsgClass(Duration.ofSeconds(5), akka.actor.Status.Failure.class);
704 assertEquals("Failure cause", cause, failure.cause());
708 public void testBatchedModificationsOnTransactionChain() {
709 final ShardTestKit testKit = new ShardTestKit(getSystem());
710 final TestActorRef<Shard> shard = actorFactory.createTestActor(
711 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
712 "testBatchedModificationsOnTransactionChain");
714 ShardTestKit.waitUntilLeader(shard);
716 final LocalHistoryIdentifier historyId = nextHistoryId();
717 final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
718 final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
720 final Duration duration = Duration.ofSeconds(5);
722 // Send a BatchedModifications to start a chained write
723 // transaction and ready it.
725 final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
726 final YangInstanceIdentifier path = TestModel.TEST_PATH;
727 shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), testKit.getRef());
728 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
730 // Create a read Tx on the same chain.
732 shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
733 DataStoreVersions.CURRENT_VERSION).toSerializable(), testKit.getRef());
735 final CreateTransactionReply createReply = testKit.expectMsgClass(Duration.ofSeconds(3),
736 CreateTransactionReply.class);
738 getSystem().actorSelection(createReply.getTransactionPath())
739 .tell(new ReadData(path, DataStoreVersions.CURRENT_VERSION), testKit.getRef());
740 final ReadDataReply readReply = testKit.expectMsgClass(Duration.ofSeconds(3), ReadDataReply.class);
741 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
743 // Commit the write transaction.
745 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
746 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
747 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
748 assertTrue("Can commit", canCommitReply.getCanCommit());
750 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
751 testKit.expectMsgClass(duration, CommitTransactionReply.class);
753 // Verify data in the data store.
755 final NormalizedNode actualNode = readStore(shard, path);
756 assertEquals("Stored node", containerNode, actualNode);
760 public void testOnBatchedModificationsWhenNotLeader() {
761 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
762 final ShardTestKit testKit = new ShardTestKit(getSystem());
763 final Creator<Shard> creator = new Creator<>() {
764 private static final long serialVersionUID = 1L;
767 public Shard create() {
768 return new Shard(newShardBuilder()) {
770 protected boolean isLeader() {
771 return overrideLeaderCalls.get() ? false : super.isLeader();
775 public ActorSelection getLeader() {
776 return overrideLeaderCalls.get() ? getSystem().actorSelection(testKit.getRef().path())
783 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props.create(Shard.class,
784 new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
785 "testOnBatchedModificationsWhenNotLeader");
787 ShardTestKit.waitUntilLeader(shard);
789 overrideLeaderCalls.set(true);
791 final BatchedModifications batched = new BatchedModifications(nextTransactionId(),
792 DataStoreVersions.CURRENT_VERSION);
794 shard.tell(batched, ActorRef.noSender());
796 testKit.expectMsgEquals(batched);
800 public void testTransactionMessagesWithNoLeader() {
801 final ShardTestKit testKit = new ShardTestKit(getSystem());
802 dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
803 .shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
804 final TestActorRef<Shard> shard = actorFactory.createTestActor(
805 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
806 "testTransactionMessagesWithNoLeader");
808 testKit.waitUntilNoLeader(shard);
810 final TransactionIdentifier txId = nextTransactionId();
811 shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), testKit.getRef());
812 Failure failure = testKit.expectMsgClass(Failure.class);
813 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
815 shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
816 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
817 failure = testKit.expectMsgClass(Failure.class);
818 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
820 shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true, Optional.empty()),
822 failure = testKit.expectMsgClass(Failure.class);
823 assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
827 public void testReadyWithReadWriteImmediateCommit() {
828 testReadyWithImmediateCommit(true);
832 public void testReadyWithWriteOnlyImmediateCommit() {
833 testReadyWithImmediateCommit(false);
836 private void testReadyWithImmediateCommit(final boolean readWrite) {
837 final ShardTestKit testKit = new ShardTestKit(getSystem());
838 final TestActorRef<Shard> shard = actorFactory.createTestActor(
839 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
840 "testReadyWithImmediateCommit-" + readWrite);
842 ShardTestKit.waitUntilLeader(shard);
844 final TransactionIdentifier transactionID = nextTransactionId();
845 final NormalizedNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
847 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH, containerNode, true),
850 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true),
854 testKit.expectMsgClass(Duration.ofSeconds(5), CommitTransactionReply.class);
856 final NormalizedNode actualNode = readStore(shard, TestModel.TEST_PATH);
857 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
861 public void testReadyLocalTransactionWithImmediateCommit() {
862 final ShardTestKit testKit = new ShardTestKit(getSystem());
863 final TestActorRef<Shard> shard = actorFactory.createTestActor(
864 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
865 "testReadyLocalTransactionWithImmediateCommit");
867 ShardTestKit.waitUntilLeader(shard);
869 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
871 final DataTreeModification modification = dataStore.newModification();
873 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
874 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
875 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
876 .addChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
878 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
880 final TransactionIdentifier txId = nextTransactionId();
881 modification.ready();
882 final ReadyLocalTransaction readyMessage =
883 new ReadyLocalTransaction(txId, modification, true, Optional.empty());
885 shard.tell(readyMessage, testKit.getRef());
887 testKit.expectMsgClass(CommitTransactionReply.class);
889 final NormalizedNode actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
890 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
894 public void testReadyLocalTransactionWithThreePhaseCommit() {
895 final ShardTestKit testKit = new ShardTestKit(getSystem());
896 final TestActorRef<Shard> shard = actorFactory.createTestActor(
897 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
898 "testReadyLocalTransactionWithThreePhaseCommit");
900 ShardTestKit.waitUntilLeader(shard);
902 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
904 final DataTreeModification modification = dataStore.newModification();
906 final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
907 new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
908 final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
909 .addChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
911 new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
913 final TransactionIdentifier txId = nextTransactionId();
914 modification.ready();
915 final ReadyLocalTransaction readyMessage =
916 new ReadyLocalTransaction(txId, modification, false, Optional.empty());
918 shard.tell(readyMessage, testKit.getRef());
920 testKit.expectMsgClass(ReadyTransactionReply.class);
922 // Send the CanCommitTransaction message.
924 shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), testKit.getRef());
925 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
926 .fromSerializable(testKit.expectMsgClass(CanCommitTransactionReply.class));
927 assertTrue("Can commit", canCommitReply.getCanCommit());
929 // Send the CanCommitTransaction message.
931 shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), testKit.getRef());
932 testKit.expectMsgClass(CommitTransactionReply.class);
934 final NormalizedNode actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
935 assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
939 public void testReadWriteCommitWithPersistenceDisabled() {
940 dataStoreContextBuilder.persistent(false);
941 final ShardTestKit testKit = new ShardTestKit(getSystem());
942 final TestActorRef<Shard> shard = actorFactory.createTestActor(
943 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
944 "testCommitWithPersistenceDisabled");
946 ShardTestKit.waitUntilLeader(shard);
948 // Setup a simulated transactions with a mock cohort.
950 final Duration duration = Duration.ofSeconds(5);
952 final TransactionIdentifier transactionID = nextTransactionId();
953 final NormalizedNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
954 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false),
956 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
958 // Send the CanCommitTransaction message.
960 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
961 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
962 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
963 assertTrue("Can commit", canCommitReply.getCanCommit());
965 // Send the CanCommitTransaction message.
967 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
968 testKit.expectMsgClass(duration, CommitTransactionReply.class);
970 final NormalizedNode actualNode = readStore(shard, TestModel.TEST_PATH);
971 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
975 public void testReadWriteCommitWhenTransactionHasModifications() throws Exception {
976 testCommitWhenTransactionHasModifications(true);
980 public void testWriteOnlyCommitWhenTransactionHasModifications() throws Exception {
981 testCommitWhenTransactionHasModifications(false);
984 private void testCommitWhenTransactionHasModifications(final boolean readWrite) throws Exception {
985 final ShardTestKit testKit = new ShardTestKit(getSystem());
986 final DataTree dataTree = createDelegatingMockDataTree();
987 final TestActorRef<Shard> shard = actorFactory.createTestActor(
988 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
989 "testCommitWhenTransactionHasModifications-" + readWrite);
991 ShardTestKit.waitUntilLeader(shard);
993 final Duration duration = Duration.ofSeconds(5);
994 final TransactionIdentifier transactionID = nextTransactionId();
997 shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
998 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1000 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1001 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1004 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1006 // Send the CanCommitTransaction message.
1008 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
1009 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1010 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
1011 assertTrue("Can commit", canCommitReply.getCanCommit());
1013 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
1014 testKit.expectMsgClass(duration, CommitTransactionReply.class);
1016 final InOrder inOrder = inOrder(dataTree);
1017 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1018 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1019 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1021 // Purge request is scheduled as asynchronous, wait for two heartbeats to let it propagate into
1023 Thread.sleep(HEARTBEAT_MILLIS * 2);
1025 shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, testKit.getRef());
1026 final ShardStats shardStats = testKit.expectMsgClass(duration, ShardStats.class);
1028 // Use MBean for verification
1029 // Committed transaction count should increase as usual
1030 assertEquals(1, shardStats.getCommittedTransactionsCount());
1032 // Commit index should advance 1 to account for disabling metadata
1033 assertEquals(1, shardStats.getCommitIndex());
1037 public void testCommitPhaseFailure() throws Exception {
1038 final ShardTestKit testKit = new ShardTestKit(getSystem());
1039 final DataTree dataTree = createDelegatingMockDataTree();
1040 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1041 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1042 "testCommitPhaseFailure");
1044 ShardTestKit.waitUntilLeader(shard);
1046 final Duration duration = Duration.ofSeconds(5);
1047 final Timeout timeout = Timeout.create(duration);
1049 // Setup 2 simulated transactions with mock cohorts. The first
1053 doThrow(new RuntimeException("mock commit failure")).when(dataTree)
1054 .commit(any(DataTreeCandidate.class));
1056 final TransactionIdentifier transactionID1 = nextTransactionId();
1057 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1058 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1059 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1061 final TransactionIdentifier transactionID2 = nextTransactionId();
1062 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1063 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1064 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1066 // Send the CanCommitTransaction message for the first Tx.
1068 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1069 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1070 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
1071 assertTrue("Can commit", canCommitReply.getCanCommit());
1073 // Send the CanCommitTransaction message for the 2nd Tx. This
1074 // should get queued and
1075 // processed after the first Tx completes.
1077 final Future<Object> canCommitFuture = Patterns.ask(shard,
1078 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1080 // Send the CommitTransaction message for the first Tx. This
1081 // should send back an error
1082 // and trigger the 2nd Tx to proceed.
1084 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1085 testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1087 // Wait for the 2nd Tx to complete the canCommit phase.
1089 final CountDownLatch latch = new CountDownLatch(1);
1090 canCommitFuture.onComplete(new OnComplete<>() {
1092 public void onComplete(final Throwable failure, final Object resp) {
1095 }, getSystem().dispatcher());
1097 assertTrue("2nd CanCommit complete", latch.await(5, TimeUnit.SECONDS));
1099 final InOrder inOrder = inOrder(dataTree);
1100 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1101 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1103 // FIXME: this invocation is done on the result of validate(). To test it, we need to make sure mock
1104 // validate performs wrapping and we capture that mock
1105 // inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1107 inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
1111 public void testPreCommitPhaseFailure() throws Exception {
1112 final ShardTestKit testKit = new ShardTestKit(getSystem());
1113 final DataTree dataTree = createDelegatingMockDataTree();
1114 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1115 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1116 "testPreCommitPhaseFailure");
1118 ShardTestKit.waitUntilLeader(shard);
1120 final Duration duration = Duration.ofSeconds(5);
1121 final Timeout timeout = Timeout.create(duration);
1123 doThrow(new RuntimeException("mock preCommit failure")).when(dataTree)
1124 .prepare(any(DataTreeModification.class));
1126 final TransactionIdentifier transactionID1 = nextTransactionId();
1127 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1128 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1129 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1131 final TransactionIdentifier transactionID2 = nextTransactionId();
1132 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1133 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1134 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1136 // Send the CanCommitTransaction message for the first Tx.
1138 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1139 final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1140 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
1141 assertTrue("Can commit", canCommitReply.getCanCommit());
1143 // Send the CanCommitTransaction message for the 2nd Tx. This
1144 // should get queued and
1145 // processed after the first Tx completes.
1147 final Future<Object> canCommitFuture = Patterns.ask(shard,
1148 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1150 // Send the CommitTransaction message for the first Tx. This
1151 // should send back an error
1152 // and trigger the 2nd Tx to proceed.
1154 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1155 testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1157 // Wait for the 2nd Tx to complete the canCommit phase.
1159 final CountDownLatch latch = new CountDownLatch(1);
1160 canCommitFuture.onComplete(new OnComplete<>() {
1162 public void onComplete(final Throwable failure, final Object resp) {
1165 }, getSystem().dispatcher());
1167 assertTrue("2nd CanCommit complete", latch.await(5, TimeUnit.SECONDS));
1169 final InOrder inOrder = inOrder(dataTree);
1170 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1171 inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
1172 inOrder.verify(dataTree).validate(any(DataTreeModification.class));
1176 public void testCanCommitPhaseFailure() throws Exception {
1177 final ShardTestKit testKit = new ShardTestKit(getSystem());
1178 final DataTree dataTree = createDelegatingMockDataTree();
1179 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1180 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1181 "testCanCommitPhaseFailure");
1183 ShardTestKit.waitUntilLeader(shard);
1185 final Duration duration = Duration.ofSeconds(5);
1186 final TransactionIdentifier transactionID1 = nextTransactionId();
1188 doThrow(new DataValidationFailedException(YangInstanceIdentifier.empty(), "mock canCommit failure"))
1189 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1191 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1192 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1193 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1195 // Send the CanCommitTransaction message.
1197 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1198 testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1200 // Send another can commit to ensure the failed one got cleaned
1203 final TransactionIdentifier transactionID2 = nextTransactionId();
1204 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1205 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1206 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1208 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1209 final CanCommitTransactionReply reply = CanCommitTransactionReply
1210 .fromSerializable(testKit.expectMsgClass(CanCommitTransactionReply.class));
1211 assertTrue("getCanCommit", reply.getCanCommit());
1215 public void testImmediateCommitWithCanCommitPhaseFailure() throws Exception {
1216 testImmediateCommitWithCanCommitPhaseFailure(true);
1217 testImmediateCommitWithCanCommitPhaseFailure(false);
1220 private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Exception {
1221 final ShardTestKit testKit = new ShardTestKit(getSystem());
1222 final DataTree dataTree = createDelegatingMockDataTree();
1223 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1224 newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1225 "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
1227 ShardTestKit.waitUntilLeader(shard);
1229 doThrow(new DataValidationFailedException(YangInstanceIdentifier.empty(), "mock canCommit failure"))
1230 .doNothing().when(dataTree).validate(any(DataTreeModification.class));
1232 final Duration duration = Duration.ofSeconds(5);
1234 final TransactionIdentifier transactionID1 = nextTransactionId();
1237 shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
1238 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1240 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1241 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1244 testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1246 // Send another can commit to ensure the failed one got cleaned
1249 final TransactionIdentifier transactionID2 = nextTransactionId();
1251 shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
1252 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1254 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1255 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), testKit.getRef());
1258 testKit.expectMsgClass(duration, CommitTransactionReply.class);
1262 public void testAbortWithCommitPending() {
1263 final ShardTestKit testKit = new ShardTestKit(getSystem());
1264 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
1266 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
1267 // Simulate an AbortTransaction message occurring during
1268 // replication, after
1269 // persisting and before finishing the commit to the
1272 doAbortTransaction(id, null);
1273 super.persistPayload(id, payload, batchHint);
1277 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props.create(Shard.class,
1278 new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
1279 "testAbortWithCommitPending");
1281 ShardTestKit.waitUntilLeader(shard);
1283 final Duration duration = Duration.ofSeconds(5);
1285 final TransactionIdentifier transactionID = nextTransactionId();
1287 shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
1288 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1289 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1291 shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
1292 testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1294 shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), testKit.getRef());
1295 testKit.expectMsgClass(duration, CommitTransactionReply.class);
1297 final NormalizedNode node = readStore(shard, TestModel.TEST_PATH);
1299 // Since we're simulating an abort occurring during replication
1300 // and before finish commit,
1301 // the data should still get written to the in-memory store
1302 // since we've gotten past
1303 // canCommit and preCommit and persisted the data.
1304 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1308 public void testTransactionCommitTimeout() throws Exception {
1309 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1310 final ShardTestKit testKit = new ShardTestKit(getSystem());
1311 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1312 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1313 "testTransactionCommitTimeout");
1315 ShardTestKit.waitUntilLeader(shard);
1317 final Duration duration = Duration.ofSeconds(5);
1319 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1320 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1321 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1323 // Ready 2 Tx's - the first will timeout
1325 final TransactionIdentifier transactionID1 = nextTransactionId();
1327 prepareBatchedModifications(transactionID1,
1328 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1329 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1330 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
1332 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1334 final TransactionIdentifier transactionID2 = nextTransactionId();
1335 final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1336 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1338 prepareBatchedModifications(transactionID2, listNodePath,
1339 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false), testKit.getRef());
1340 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1342 // canCommit 1st Tx. We don't send the commit so it should
1345 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1346 testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1348 // canCommit the 2nd Tx - it should complete after the 1st Tx
1351 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1352 testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1354 // Try to commit the 1st Tx - should fail as it's not the
1357 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1358 testKit.expectMsgClass(duration, akka.actor.Status.Failure.class);
1360 // Commit the 2nd Tx.
1362 shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1363 testKit.expectMsgClass(duration, CommitTransactionReply.class);
1365 final NormalizedNode node = readStore(shard, listNodePath);
1366 assertNotNull(listNodePath + " not found", node);
1371 // public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1372 // dataStoreContextBuilder.shardTransactionCommitQueueCapacity(2);
1374 // new ShardTestKit(getSystem()) {{
1375 // final TestActorRef<Shard> shard = actorFactory.createTestActor(
1376 // newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1377 // "testTransactionCommitQueueCapacityExceeded");
1379 // waitUntilLeader(shard);
1381 // final FiniteDuration duration = duration("5 seconds");
1383 // final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1385 // final TransactionIdentifier transactionID1 = nextTransactionId();
1386 // final MutableCompositeModification modification1 = new MutableCompositeModification();
1387 // final ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
1388 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID1,
1391 // final TransactionIdentifier transactionID2 = nextTransactionId();
1392 // final MutableCompositeModification modification2 = new MutableCompositeModification();
1393 // final ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
1394 // TestModel.OUTER_LIST_PATH,
1395 // ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), transactionID2,
1398 // final TransactionIdentifier transactionID3 = nextTransactionId();
1399 // final MutableCompositeModification modification3 = new MutableCompositeModification();
1400 // final ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
1401 // TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), transactionID3,
1404 // // Ready the Tx's
1406 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1,
1407 // modification1), getRef());
1408 // expectMsgClass(duration, ReadyTransactionReply.class);
1410 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2,
1411 // modification2), getRef());
1412 // expectMsgClass(duration, ReadyTransactionReply.class);
1414 // // The 3rd Tx should exceed queue capacity and fail.
1416 // shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3,
1417 // modification3), getRef());
1418 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1420 // // canCommit 1st Tx.
1422 // shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
1423 // expectMsgClass(duration, CanCommitTransactionReply.class);
1425 // // canCommit the 2nd Tx - it should get queued.
1427 // shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
1429 // // canCommit the 3rd Tx - should exceed queue capacity and fail.
1431 // shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
1432 // expectMsgClass(duration, akka.actor.Status.Failure.class);
1437 public void testTransactionCommitWithPriorExpiredCohortEntries() {
1438 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1439 final ShardTestKit testKit = new ShardTestKit(getSystem());
1440 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1441 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1442 "testTransactionCommitWithPriorExpiredCohortEntries");
1444 ShardTestKit.waitUntilLeader(shard);
1446 final Duration duration = Duration.ofSeconds(5);
1448 final TransactionIdentifier transactionID1 = nextTransactionId();
1449 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1450 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1451 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1453 final TransactionIdentifier transactionID2 = nextTransactionId();
1454 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1455 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1456 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1458 final TransactionIdentifier transactionID3 = nextTransactionId();
1459 shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1460 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1461 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1463 // All Tx's are readied. We'll send canCommit for the last one
1464 // but not the others. The others
1465 // should expire from the queue and the last one should be
1468 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), testKit.getRef());
1469 testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1473 public void testTransactionCommitWithSubsequentExpiredCohortEntry() {
1474 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1475 final ShardTestKit testKit = new ShardTestKit(getSystem());
1476 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1477 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1478 "testTransactionCommitWithSubsequentExpiredCohortEntry");
1480 ShardTestKit.waitUntilLeader(shard);
1482 final Duration duration = Duration.ofSeconds(5);
1484 final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
1486 final TransactionIdentifier transactionID1 = nextTransactionId();
1487 shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
1488 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1489 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1491 // CanCommit the first Tx so it's the current in-progress Tx.
1493 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1494 testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1496 // Ready the second Tx.
1498 final TransactionIdentifier transactionID2 = nextTransactionId();
1499 shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
1500 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), testKit.getRef());
1501 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1503 // Ready the third Tx.
1505 final TransactionIdentifier transactionID3 = nextTransactionId();
1506 final DataTreeModification modification3 = dataStore.newModification();
1507 new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
1508 .apply(modification3);
1509 modification3.ready();
1510 final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3,
1511 true, Optional.empty());
1512 shard.tell(readyMessage, testKit.getRef());
1514 // Commit the first Tx. After completing, the second should
1515 // expire from the queue and the third
1518 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1519 testKit.expectMsgClass(duration, CommitTransactionReply.class);
1521 // Expect commit reply from the third Tx.
1523 testKit.expectMsgClass(duration, CommitTransactionReply.class);
1525 final NormalizedNode node = readStore(shard, TestModel.TEST2_PATH);
1526 assertNotNull(TestModel.TEST2_PATH + " not found", node);
1530 public void testCanCommitBeforeReadyFailure() {
1531 final ShardTestKit testKit = new ShardTestKit(getSystem());
1532 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1533 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1534 "testCanCommitBeforeReadyFailure");
1536 shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), testKit.getRef());
1537 testKit.expectMsgClass(Duration.ofSeconds(5), akka.actor.Status.Failure.class);
1541 public void testAbortAfterCanCommit() throws Exception {
1542 final ShardTestKit testKit = new ShardTestKit(getSystem());
1543 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1544 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterCanCommit");
1546 ShardTestKit.waitUntilLeader(shard);
1548 final Duration duration = Duration.ofSeconds(5);
1549 final Timeout timeout = Timeout.create(duration);
1551 // Ready 2 transactions - the first one will be aborted.
1553 final TransactionIdentifier transactionID1 = nextTransactionId();
1554 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1555 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1556 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1558 final TransactionIdentifier transactionID2 = nextTransactionId();
1559 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1560 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1561 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1563 // Send the CanCommitTransaction message for the first Tx.
1565 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1566 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
1567 .fromSerializable(testKit.expectMsgClass(duration, CanCommitTransactionReply.class));
1568 assertTrue("Can commit", canCommitReply.getCanCommit());
1570 // Send the CanCommitTransaction message for the 2nd Tx. This
1571 // should get queued and
1572 // processed after the first Tx completes.
1574 final Future<Object> canCommitFuture = Patterns.ask(shard,
1575 new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
1577 // Send the AbortTransaction message for the first Tx. This
1578 // should trigger the 2nd
1581 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1582 testKit.expectMsgClass(duration, AbortTransactionReply.class);
1584 // Wait for the 2nd Tx to complete the canCommit phase.
1586 canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture,
1587 FiniteDuration.create(5, TimeUnit.SECONDS));
1588 assertTrue("Can commit", canCommitReply.getCanCommit());
1592 public void testAbortAfterReady() {
1593 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1594 final ShardTestKit testKit = new ShardTestKit(getSystem());
1595 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1596 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1598 ShardTestKit.waitUntilLeader(shard);
1600 final Duration duration = Duration.ofSeconds(5);
1604 final TransactionIdentifier transactionID1 = nextTransactionId();
1605 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1606 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1607 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1609 // Send the AbortTransaction message.
1611 shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1612 testKit.expectMsgClass(duration, AbortTransactionReply.class);
1614 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1616 // Now send CanCommitTransaction - should fail.
1618 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1619 final Throwable failure = testKit.expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
1620 assertTrue("Failure type", failure instanceof IllegalStateException);
1622 // Ready and CanCommit another and verify success.
1624 final TransactionIdentifier transactionID2 = nextTransactionId();
1625 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1626 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1627 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1629 shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1630 testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1634 public void testAbortQueuedTransaction() {
1635 final ShardTestKit testKit = new ShardTestKit(getSystem());
1636 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1637 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
1639 ShardTestKit.waitUntilLeader(shard);
1641 final Duration duration = Duration.ofSeconds(5);
1645 final TransactionIdentifier transactionID1 = nextTransactionId();
1646 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1647 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1648 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1650 final TransactionIdentifier transactionID2 = nextTransactionId();
1651 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1652 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), testKit.getRef());
1653 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1655 final TransactionIdentifier transactionID3 = nextTransactionId();
1656 shard.tell(newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
1657 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1), testKit.getRef());
1658 testKit.expectMsgClass(duration, ReadyTransactionReply.class);
1660 // Abort the second tx while it's queued.
1662 shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), testKit.getRef());
1663 testKit.expectMsgClass(duration, AbortTransactionReply.class);
1665 // Commit the other 2.
1667 shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1668 testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1670 shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), testKit.getRef());
1671 testKit.expectMsgClass(duration, CommitTransactionReply.class);
1673 shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), testKit.getRef());
1674 testKit.expectMsgClass(duration, CanCommitTransactionReply.class);
1676 shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), testKit.getRef());
1677 testKit.expectMsgClass(duration, CommitTransactionReply.class);
1679 assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
1683 public void testCreateSnapshotWithNonPersistentData() throws Exception {
1684 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1688 public void testCreateSnapshot() throws Exception {
1689 testCreateSnapshot(true, "testCreateSnapshot");
1692 private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception {
1693 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1695 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1696 class TestPersistentDataProvider extends DelegatingPersistentDataProvider {
1697 TestPersistentDataProvider(final DataPersistenceProvider delegate) {
1702 public void saveSnapshot(final Object obj) {
1703 savedSnapshot.set(obj);
1704 super.saveSnapshot(obj);
1708 dataStoreContextBuilder.persistent(persistent);
1710 final class TestShard extends Shard {
1712 TestShard(final AbstractBuilder<?, ?> builder) {
1714 setPersistence(new TestPersistentDataProvider(super.persistence()));
1718 public void handleCommand(final Object message) {
1719 super.handleCommand(message);
1721 // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
1722 if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
1723 latch.get().countDown();
1728 public RaftActorContext getRaftActorContext() {
1729 return super.getRaftActorContext();
1733 final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
1735 final TestActorRef<Shard> shard = actorFactory.createTestActor(Props.create(Shard.class,
1736 new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), shardActorName);
1738 ShardTestKit.waitUntilLeader(shard);
1739 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1741 final NormalizedNode expectedRoot = readStore(shard, YangInstanceIdentifier.empty());
1743 // Trigger creation of a snapshot by ensuring
1744 final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
1745 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1746 awaitAndValidateSnapshot(latch, savedSnapshot, expectedRoot);
1748 raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
1749 awaitAndValidateSnapshot(latch, savedSnapshot, expectedRoot);
1752 private static void awaitAndValidateSnapshot(final AtomicReference<CountDownLatch> latch,
1753 final AtomicReference<Object> savedSnapshot, final NormalizedNode expectedRoot)
1754 throws InterruptedException {
1755 assertTrue("Snapshot saved", latch.get().await(5, TimeUnit.SECONDS));
1757 assertTrue("Invalid saved snapshot " + savedSnapshot.get(), savedSnapshot.get() instanceof Snapshot);
1759 verifySnapshot((Snapshot) savedSnapshot.get(), expectedRoot);
1761 latch.set(new CountDownLatch(1));
1762 savedSnapshot.set(null);
1765 private static void verifySnapshot(final Snapshot snapshot, final NormalizedNode expectedRoot) {
1766 final NormalizedNode actual = ((ShardSnapshotState)snapshot.getState()).getSnapshot().getRootNode().get();
1767 assertEquals("Root node", expectedRoot, actual);
1771 * This test simply verifies that the applySnapShot logic will work.
1774 public void testInMemoryDataTreeRestore() throws DataValidationFailedException {
1775 final DataTree store = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL,
1778 final DataTreeModification putTransaction = store.takeSnapshot().newModification();
1779 putTransaction.write(TestModel.TEST_PATH,
1780 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1781 commitTransaction(store, putTransaction);
1784 final NormalizedNode expected = readStore(store, YangInstanceIdentifier.empty());
1786 final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
1788 writeTransaction.delete(YangInstanceIdentifier.empty());
1789 writeTransaction.write(YangInstanceIdentifier.empty(), expected);
1791 commitTransaction(store, writeTransaction);
1793 final NormalizedNode actual = readStore(store, YangInstanceIdentifier.empty());
1795 assertEquals(expected, actual);
1799 public void testRecoveryApplicable() {
1801 final DatastoreContext persistentContext = DatastoreContext.newBuilder()
1802 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
1804 final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext)
1805 .schemaContextProvider(() -> SCHEMA_CONTEXT).props();
1807 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder()
1808 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
1810 final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext)
1811 .schemaContextProvider(() -> SCHEMA_CONTEXT).props();
1813 final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
1815 assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
1817 final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
1819 assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
1823 public void testOnDatastoreContext() {
1824 dataStoreContextBuilder.persistent(true);
1826 final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
1828 assertTrue("isRecoveryApplicable", shard.underlyingActor().persistence().isRecoveryApplicable());
1830 ShardTestKit.waitUntilLeader(shard);
1832 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
1834 assertFalse("isRecoveryApplicable", shard.underlyingActor().persistence().isRecoveryApplicable());
1836 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
1838 assertTrue("isRecoveryApplicable", shard.underlyingActor().persistence().isRecoveryApplicable());
1842 public void testRegisterRoleChangeListener() {
1843 final ShardTestKit testKit = new ShardTestKit(getSystem());
1844 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1845 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1846 "testRegisterRoleChangeListener");
1848 ShardTestKit.waitUntilLeader(shard);
1850 final ActorRef listener = getSystem().actorOf(MessageCollectorActor.props());
1852 shard.tell(new RegisterRoleChangeListener(), listener);
1854 MessageCollectorActor.expectFirstMatching(listener, RegisterRoleChangeListenerReply.class);
1856 ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
1857 ShardLeaderStateChanged.class);
1858 assertTrue("getLocalShardDataTree present", leaderStateChanged.getLocalShardDataTree().isPresent());
1859 assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
1860 leaderStateChanged.getLocalShardDataTree().get());
1862 MessageCollectorActor.clearMessages(listener);
1864 // Force a leader change
1866 shard.tell(new RequestVote(10000, "member2", 50, 50), testKit.getRef());
1868 leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener, ShardLeaderStateChanged.class);
1869 assertFalse("getLocalShardDataTree present", leaderStateChanged.getLocalShardDataTree().isPresent());
1873 public void testFollowerInitialSyncStatus() {
1874 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1875 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1876 "testFollowerInitialSyncStatus");
1878 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false,
1879 "member-1-shard-inventory-operational"));
1881 assertFalse(shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1883 shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true,
1884 "member-1-shard-inventory-operational"));
1886 assertTrue(shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1890 public void testClusteredDataTreeChangeListenerWithDelayedRegistration() throws Exception {
1891 final ShardTestKit testKit = new ShardTestKit(getSystem());
1892 final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistration";
1893 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
1894 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
1896 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
1897 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
1898 TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
1900 setupInMemorySnapshotStore();
1902 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1903 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1904 actorFactory.generateActorId(testName + "-shard"));
1906 testKit.waitUntilNoLeader(shard);
1908 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), testKit.getRef());
1909 final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(Duration.ofSeconds(5),
1910 RegisterDataTreeNotificationListenerReply.class);
1911 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
1913 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
1914 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
1916 listener.waitForChangeEvents();
1920 public void testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed() throws Exception {
1921 final ShardTestKit testKit = new ShardTestKit(getSystem());
1922 final String testName = "testClusteredDataTreeChangeListenerWithDelayedRegistrationClosed";
1923 dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
1924 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
1926 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(0);
1927 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener,
1928 TestModel.TEST_PATH), actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
1930 setupInMemorySnapshotStore();
1932 final TestActorRef<Shard> shard = actorFactory.createTestActor(
1933 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1934 actorFactory.generateActorId(testName + "-shard"));
1936 testKit.waitUntilNoLeader(shard);
1938 shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), testKit.getRef());
1939 final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(Duration.ofSeconds(5),
1940 RegisterDataTreeNotificationListenerReply.class);
1941 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
1943 final ActorSelection regActor = getSystem().actorSelection(reply.getListenerRegistrationPath());
1944 regActor.tell(CloseDataTreeNotificationListenerRegistration.getInstance(), testKit.getRef());
1945 testKit.expectMsgClass(CloseDataTreeNotificationListenerRegistrationReply.class);
1947 shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
1948 .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
1950 listener.expectNoMoreChanges("Received unexpected change after close");
1954 public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
1955 final ShardTestKit testKit = new ShardTestKit(getSystem());
1956 final String testName = "testClusteredDataTreeChangeListenerRegistration";
1957 final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
1958 MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
1960 final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
1961 MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
1963 final TestActorRef<Shard> followerShard = actorFactory
1964 .createTestActor(Shard.builder().id(followerShardID)
1965 .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
1966 .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
1967 "akka://test/user/" + leaderShardID.toString()))
1968 .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
1969 .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
1971 final TestActorRef<Shard> leaderShard = actorFactory
1972 .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
1973 .peerAddresses(Collections.singletonMap(followerShardID.toString(),
1974 "akka://test/user/" + followerShardID.toString()))
1975 .schemaContextProvider(() -> SCHEMA_CONTEXT).props()
1976 .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
1978 leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1979 final String leaderPath = ShardTestKit.waitUntilLeader(followerShard);
1980 assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
1982 final YangInstanceIdentifier path = TestModel.TEST_PATH;
1983 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
1984 final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path),
1985 actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
1987 followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), testKit.getRef());
1988 final RegisterDataTreeNotificationListenerReply reply = testKit.expectMsgClass(Duration.ofSeconds(5),
1989 RegisterDataTreeNotificationListenerReply.class);
1990 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
1992 writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1994 listener.waitForChangeEvents();
1998 public void testServerRemoved() {
1999 final TestActorRef<MessageCollectorActor> parent = actorFactory.createTestActor(MessageCollectorActor.props()
2000 .withDispatcher(Dispatchers.DefaultDispatcherId()));
2002 final ActorRef shard = parent.underlyingActor().context().actorOf(
2003 newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
2004 "testServerRemoved");
2006 shard.tell(new ServerRemoved("test"), ActorRef.noSender());
2008 MessageCollectorActor.expectFirstMatching(parent, ServerRemoved.class);