1 package org.opendaylight.controller.cluster.datastore;
3 import static org.junit.Assert.assertEquals;
4 import static org.junit.Assert.assertFalse;
5 import static org.junit.Assert.assertNotNull;
6 import static org.junit.Assert.assertNull;
7 import static org.junit.Assert.assertTrue;
8 import static org.mockito.Mockito.doReturn;
9 import static org.mockito.Mockito.inOrder;
10 import static org.mockito.Mockito.mock;
11 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.PoisonPill;
15 import akka.actor.Props;
16 import akka.dispatch.Dispatchers;
17 import akka.dispatch.OnComplete;
18 import akka.japi.Creator;
19 import akka.japi.Procedure;
20 import akka.pattern.Patterns;
21 import akka.persistence.SnapshotSelectionCriteria;
22 import akka.testkit.TestActorRef;
23 import akka.util.Timeout;
24 import com.google.common.base.Function;
25 import com.google.common.base.Optional;
26 import com.google.common.util.concurrent.Futures;
27 import com.google.common.util.concurrent.ListenableFuture;
28 import com.google.common.util.concurrent.MoreExecutors;
29 import com.google.common.util.concurrent.Uninterruptibles;
30 import java.io.IOException;
31 import java.util.Collections;
32 import java.util.HashSet;
33 import java.util.List;
36 import java.util.concurrent.CountDownLatch;
37 import java.util.concurrent.ExecutionException;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.atomic.AtomicBoolean;
40 import java.util.concurrent.atomic.AtomicReference;
41 import org.junit.Test;
42 import org.mockito.InOrder;
43 import org.opendaylight.controller.cluster.DataPersistenceProvider;
44 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
45 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
46 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
47 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
48 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
50 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
51 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
52 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
53 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
54 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
55 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
56 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
57 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
58 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
59 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
60 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
61 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
62 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
63 import org.opendaylight.controller.cluster.datastore.modification.Modification;
64 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
65 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
66 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
67 import org.opendaylight.controller.cluster.datastore.utils.MessageCollectorActor;
68 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
69 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
70 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
71 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
72 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
73 import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry;
74 import org.opendaylight.controller.cluster.raft.Snapshot;
75 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
76 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
77 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
78 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
79 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
80 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
81 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
82 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
83 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
84 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
85 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
86 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
87 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
88 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
89 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
90 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
91 import org.opendaylight.controller.protobuff.messages.cohort3pc.ThreePhaseCommitCohortMessages;
92 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
93 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
94 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
95 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
96 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
97 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
98 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
99 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
100 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
101 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
102 import scala.concurrent.Await;
103 import scala.concurrent.Future;
104 import scala.concurrent.duration.FiniteDuration;
106 public class ShardTest extends AbstractShardTest {
109 public void testRegisterChangeListener() throws Exception {
110 new ShardTestKit(getSystem()) {{
111 TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
112 newShardProps(), "testRegisterChangeListener");
114 waitUntilLeader(shard);
116 shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
118 MockDataChangeListener listener = new MockDataChangeListener(1);
119 ActorRef dclActor = getSystem().actorOf(DataChangeListener.props(listener),
120 "testRegisterChangeListener-DataChangeListener");
122 shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
123 dclActor, AsyncDataBroker.DataChangeScope.BASE), getRef());
125 RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
126 RegisterChangeListenerReply.class);
127 String replyPath = reply.getListenerRegistrationPath().toString();
128 assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
129 "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
131 YangInstanceIdentifier path = TestModel.TEST_PATH;
132 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
134 listener.waitForChangeEvents(path);
136 dclActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
137 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
141 @SuppressWarnings("serial")
143 public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
144 // This test tests the timing window in which a change listener is registered before the
145 // shard becomes the leader. We verify that the listener is registered and notified of the
146 // existing data when the shard becomes the leader.
147 new ShardTestKit(getSystem()) {{
148 // For this test, we want to send the RegisterChangeListener message after the shard
149 // has recovered from persistence and before it becomes the leader. So we subclass
150 // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
151 // we know that the shard has been initialized to a follower and has started the
152 // election process. The following 2 CountDownLatches are used to coordinate the
153 // ElectionTimeout with the sending of the RegisterChangeListener message.
154 final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
155 final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
156 Creator<Shard> creator = new Creator<Shard>() {
157 boolean firstElectionTimeout = true;
160 public Shard create() throws Exception {
161 // Use a non persistent provider because this test actually invokes persist on the journal
162 // this will cause all other messages to not be queued properly after that.
163 // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
164 // it does do a persist)
165 return new Shard(shardID, Collections.<String,String>emptyMap(),
166 dataStoreContextBuilder.persistent(false).build(), SCHEMA_CONTEXT) {
168 public void onReceiveCommand(final Object message) throws Exception {
169 if(message instanceof ElectionTimeout && firstElectionTimeout) {
170 // Got the first ElectionTimeout. We don't forward it to the
171 // base Shard yet until we've sent the RegisterChangeListener
172 // message. So we signal the onFirstElectionTimeout latch to tell
173 // the main thread to send the RegisterChangeListener message and
174 // start a thread to wait on the onChangeListenerRegistered latch,
175 // which the main thread signals after it has sent the message.
176 // After the onChangeListenerRegistered is triggered, we send the
177 // original ElectionTimeout message to proceed with the election.
178 firstElectionTimeout = false;
179 final ActorRef self = getSelf();
183 Uninterruptibles.awaitUninterruptibly(
184 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
185 self.tell(message, self);
189 onFirstElectionTimeout.countDown();
191 super.onReceiveCommand(message);
198 MockDataChangeListener listener = new MockDataChangeListener(1);
199 ActorRef dclActor = getSystem().actorOf(DataChangeListener.props(listener),
200 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
202 TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
203 Props.create(new DelegatingShardCreator(creator)),
204 "testRegisterChangeListenerWhenNotLeaderInitially");
206 // Write initial data into the in-memory store.
207 YangInstanceIdentifier path = TestModel.TEST_PATH;
208 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
210 // Wait until the shard receives the first ElectionTimeout message.
211 assertEquals("Got first ElectionTimeout", true,
212 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
214 // Now send the RegisterChangeListener and wait for the reply.
215 shard.tell(new RegisterChangeListener(path, dclActor,
216 AsyncDataBroker.DataChangeScope.SUBTREE), getRef());
218 RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
219 RegisterChangeListenerReply.class);
220 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
222 // Sanity check - verify the shard is not the leader yet.
223 shard.tell(new FindLeader(), getRef());
224 FindLeaderReply findLeadeReply =
225 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
226 assertNull("Expected the shard not to be the leader", findLeadeReply.getLeaderActor());
228 // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
229 // with the election process.
230 onChangeListenerRegistered.countDown();
232 // Wait for the shard to become the leader and notify our listener with the existing
233 // data in the store.
234 listener.waitForChangeEvents(path);
236 dclActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
237 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
242 public void testCreateTransaction(){
243 new ShardTestKit(getSystem()) {{
244 ActorRef shard = getSystem().actorOf(newShardProps(), "testCreateTransaction");
246 waitUntilLeader(shard);
248 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
250 shard.tell(new CreateTransaction("txn-1",
251 TransactionProxy.TransactionType.READ_ONLY.ordinal() ).toSerializable(), getRef());
253 CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
254 CreateTransactionReply.class);
256 String path = reply.getTransactionActorPath().toString();
257 assertTrue("Unexpected transaction path " + path,
258 path.contains("akka://test/user/testCreateTransaction/shard-txn-1"));
260 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
265 public void testCreateTransactionOnChain(){
266 new ShardTestKit(getSystem()) {{
267 final ActorRef shard = getSystem().actorOf(newShardProps(), "testCreateTransactionOnChain");
269 waitUntilLeader(shard);
271 shard.tell(new CreateTransaction("txn-1",
272 TransactionProxy.TransactionType.READ_ONLY.ordinal() , "foobar").toSerializable(),
275 CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
276 CreateTransactionReply.class);
278 String path = reply.getTransactionActorPath().toString();
279 assertTrue("Unexpected transaction path " + path,
280 path.contains("akka://test/user/testCreateTransactionOnChain/shard-txn-1"));
282 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
286 @SuppressWarnings("serial")
288 public void testPeerAddressResolved() throws Exception {
289 new ShardTestKit(getSystem()) {{
290 final CountDownLatch recoveryComplete = new CountDownLatch(1);
291 class TestShard extends Shard {
293 super(shardID, Collections.<String, String>singletonMap(shardID.toString(), null),
294 newDatastoreContext(), SCHEMA_CONTEXT);
297 Map<String, String> getPeerAddresses() {
298 return getRaftActorContext().getPeerAddresses();
302 protected void onRecoveryComplete() {
304 super.onRecoveryComplete();
306 recoveryComplete.countDown();
311 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
312 Props.create(new DelegatingShardCreator(new Creator<Shard>() {
314 public TestShard create() throws Exception {
315 return new TestShard();
317 })), "testPeerAddressResolved");
319 //waitUntilLeader(shard);
320 assertEquals("Recovery complete", true,
321 Uninterruptibles.awaitUninterruptibly(recoveryComplete, 5, TimeUnit.SECONDS));
323 String address = "akka://foobar";
324 shard.underlyingActor().onReceiveCommand(new PeerAddressResolved(shardID.toString(), address));
326 assertEquals("getPeerAddresses", address,
327 ((TestShard)shard.underlyingActor()).getPeerAddresses().get(shardID.toString()));
329 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
334 public void testApplySnapshot() throws Exception {
335 TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(),
336 "testApplySnapshot");
338 InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
339 store.onGlobalContextUpdated(SCHEMA_CONTEXT);
341 writeToStore(store, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
343 YangInstanceIdentifier root = YangInstanceIdentifier.builder().build();
344 NormalizedNode<?,?> expected = readStore(store, root);
346 ApplySnapshot applySnapshot = new ApplySnapshot(Snapshot.create(
347 SerializationUtils.serializeNormalizedNode(expected),
348 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4));
350 shard.underlyingActor().onReceiveCommand(applySnapshot);
352 NormalizedNode<?,?> actual = readStore(shard, root);
354 assertEquals("Root node", expected, actual);
356 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
360 public void testApplyState() throws Exception {
362 TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(), "testApplyState");
364 NormalizedNode<?, ?> node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
366 ApplyState applyState = new ApplyState(null, "test", new ReplicatedLogImplEntry(1, 2,
367 newModificationPayload(new WriteModification(TestModel.TEST_PATH, node))));
369 shard.underlyingActor().onReceiveCommand(applyState);
371 NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
372 assertEquals("Applied state", node, actual);
374 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
378 public void testRecovery() throws Exception {
380 // Set up the InMemorySnapshotStore.
382 InMemoryDOMDataStore testStore = InMemoryDOMDataStoreFactory.create("Test", null, null);
383 testStore.onGlobalContextUpdated(SCHEMA_CONTEXT);
385 writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
387 NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.builder().build());
389 InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
390 SerializationUtils.serializeNormalizedNode(root),
391 Collections.<ReplicatedLogEntry>emptyList(), 0, 1, -1, -1));
393 // Set up the InMemoryJournal.
395 InMemoryJournal.addEntry(shardID.toString(), 0, new ReplicatedLogImplEntry(0, 1, newModificationPayload(
396 new WriteModification(TestModel.OUTER_LIST_PATH,
397 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build()))));
399 int nListEntries = 16;
400 Set<Integer> listEntryKeys = new HashSet<>();
402 // Add some ModificationPayload entries
403 for(int i = 1; i <= nListEntries; i++) {
404 listEntryKeys.add(Integer.valueOf(i));
405 YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
406 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
407 Modification mod = new MergeModification(path,
408 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
409 InMemoryJournal.addEntry(shardID.toString(), i, new ReplicatedLogImplEntry(i, 1,
410 newModificationPayload(mod)));
413 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 1,
414 new ApplyJournalEntries(nListEntries));
416 testRecovery(listEntryKeys);
419 private ModificationPayload newModificationPayload(final Modification... mods) throws IOException {
420 MutableCompositeModification compMod = new MutableCompositeModification();
421 for(Modification mod: mods) {
422 compMod.addModification(mod);
425 return new ModificationPayload(compMod);
428 @SuppressWarnings({ "unchecked" })
430 public void testConcurrentThreePhaseCommits() throws Throwable {
431 new ShardTestKit(getSystem()) {{
432 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
433 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
434 "testConcurrentThreePhaseCommits");
436 waitUntilLeader(shard);
438 final String transactionID1 = "tx1";
439 final String transactionID2 = "tx2";
440 final String transactionID3 = "tx3";
442 final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort1 = new AtomicReference<>();
443 final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort2 = new AtomicReference<>();
444 final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort3 = new AtomicReference<>();
445 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
447 public DOMStoreThreePhaseCommitCohort decorate(String transactionID, DOMStoreThreePhaseCommitCohort actual) {
448 if(transactionID.equals(transactionID1)) {
449 mockCohort1.set(createDelegatingMockCohort("cohort1", actual));
450 return mockCohort1.get();
451 } else if(transactionID.equals(transactionID2)) {
452 mockCohort2.set(createDelegatingMockCohort("cohort2", actual));
453 return mockCohort2.get();
455 mockCohort3.set(createDelegatingMockCohort("cohort3", actual));
456 return mockCohort3.get();
461 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
464 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
465 final Timeout timeout = new Timeout(duration);
467 // Send a BatchedModifications message for the first transaction.
469 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
470 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
471 BatchedModificationsReply batchedReply = expectMsgClass(duration, BatchedModificationsReply.class);
472 assertEquals("getCohortPath", shard.path().toString(), batchedReply.getCohortPath());
473 assertEquals("getNumBatched", 1, batchedReply.getNumBatched());
475 // Send the CanCommitTransaction message for the first Tx.
477 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
478 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
479 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
480 assertEquals("Can commit", true, canCommitReply.getCanCommit());
482 // Send BatchedModifications for the next 2 Tx's.
484 shard.tell(newBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
485 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true), getRef());
486 expectMsgClass(duration, BatchedModificationsReply.class);
488 shard.tell(newBatchedModifications(transactionID3, YangInstanceIdentifier.builder(
489 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
490 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true), getRef());
491 expectMsgClass(duration, BatchedModificationsReply.class);
493 // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
494 // processed after the first Tx completes.
496 Future<Object> canCommitFuture1 = Patterns.ask(shard,
497 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
499 Future<Object> canCommitFuture2 = Patterns.ask(shard,
500 new CanCommitTransaction(transactionID3).toSerializable(), timeout);
502 // Send the CommitTransaction message for the first Tx. After it completes, it should
503 // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
505 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
506 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
508 // Wait for the next 2 Tx's to complete.
510 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
511 final CountDownLatch commitLatch = new CountDownLatch(2);
513 class OnFutureComplete extends OnComplete<Object> {
514 private final Class<?> expRespType;
516 OnFutureComplete(final Class<?> expRespType) {
517 this.expRespType = expRespType;
521 public void onComplete(final Throwable error, final Object resp) {
523 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
526 assertEquals("Commit response type", expRespType, resp.getClass());
528 } catch (Exception e) {
534 void onSuccess(final Object resp) throws Exception {
538 class OnCommitFutureComplete extends OnFutureComplete {
539 OnCommitFutureComplete() {
540 super(CommitTransactionReply.SERIALIZABLE_CLASS);
544 public void onComplete(final Throwable error, final Object resp) {
545 super.onComplete(error, resp);
546 commitLatch.countDown();
550 class OnCanCommitFutureComplete extends OnFutureComplete {
551 private final String transactionID;
553 OnCanCommitFutureComplete(final String transactionID) {
554 super(CanCommitTransactionReply.SERIALIZABLE_CLASS);
555 this.transactionID = transactionID;
559 void onSuccess(final Object resp) throws Exception {
560 CanCommitTransactionReply canCommitReply =
561 CanCommitTransactionReply.fromSerializable(resp);
562 assertEquals("Can commit", true, canCommitReply.getCanCommit());
564 Future<Object> commitFuture = Patterns.ask(shard,
565 new CommitTransaction(transactionID).toSerializable(), timeout);
566 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
570 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
571 getSystem().dispatcher());
573 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
574 getSystem().dispatcher());
576 boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
578 if(caughtEx.get() != null) {
579 throw caughtEx.get();
582 assertEquals("Commits complete", true, done);
584 InOrder inOrder = inOrder(mockCohort1.get(), mockCohort2.get(), mockCohort3.get());
585 inOrder.verify(mockCohort1.get()).canCommit();
586 inOrder.verify(mockCohort1.get()).preCommit();
587 inOrder.verify(mockCohort1.get()).commit();
588 inOrder.verify(mockCohort2.get()).canCommit();
589 inOrder.verify(mockCohort2.get()).preCommit();
590 inOrder.verify(mockCohort2.get()).commit();
591 inOrder.verify(mockCohort3.get()).canCommit();
592 inOrder.verify(mockCohort3.get()).preCommit();
593 inOrder.verify(mockCohort3.get()).commit();
595 // Verify data in the data store.
597 NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
598 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
599 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
600 outerList.getValue() instanceof Iterable);
601 Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
602 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
603 entry instanceof MapEntryNode);
604 MapEntryNode mapEntry = (MapEntryNode)entry;
605 Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
606 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
607 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
608 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", 1, idLeaf.get().getValue());
610 verifyLastApplied(shard, 2);
612 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
616 private BatchedModifications newBatchedModifications(String transactionID, YangInstanceIdentifier path,
617 NormalizedNode<?, ?> data, boolean ready) {
618 return newBatchedModifications(transactionID, null, path, data, ready);
621 private BatchedModifications newBatchedModifications(String transactionID, String transactionChainID,
622 YangInstanceIdentifier path, NormalizedNode<?, ?> data, boolean ready) {
623 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, transactionChainID);
624 batched.addModification(new WriteModification(path, data));
625 batched.setReady(ready);
629 @SuppressWarnings("unchecked")
631 public void testMultipleBatchedModifications() throws Throwable {
632 new ShardTestKit(getSystem()) {{
633 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
634 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
635 "testMultipleBatchedModifications");
637 waitUntilLeader(shard);
639 final String transactionID = "tx";
640 FiniteDuration duration = duration("5 seconds");
642 final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort = new AtomicReference<>();
643 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
645 public DOMStoreThreePhaseCommitCohort decorate(String txID, DOMStoreThreePhaseCommitCohort actual) {
646 if(mockCohort.get() == null) {
647 mockCohort.set(createDelegatingMockCohort("cohort", actual));
650 return mockCohort.get();
654 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
656 // Send a BatchedModifications to start a transaction.
658 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
659 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
660 expectMsgClass(duration, BatchedModificationsReply.class);
662 // Send a couple more BatchedModifications.
664 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
665 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
666 expectMsgClass(duration, BatchedModificationsReply.class);
668 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
669 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
670 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true), getRef());
671 expectMsgClass(duration, BatchedModificationsReply.class);
673 // Send the CanCommitTransaction message.
675 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
676 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
677 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
678 assertEquals("Can commit", true, canCommitReply.getCanCommit());
680 // Send the CanCommitTransaction message.
682 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
683 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
685 InOrder inOrder = inOrder(mockCohort.get());
686 inOrder.verify(mockCohort.get()).canCommit();
687 inOrder.verify(mockCohort.get()).preCommit();
688 inOrder.verify(mockCohort.get()).commit();
690 // Verify data in the data store.
692 NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
693 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
694 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
695 outerList.getValue() instanceof Iterable);
696 Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
697 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
698 entry instanceof MapEntryNode);
699 MapEntryNode mapEntry = (MapEntryNode)entry;
700 Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
701 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
702 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
703 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", 1, idLeaf.get().getValue());
705 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
710 public void testBatchedModificationsOnTransactionChain() throws Throwable {
711 new ShardTestKit(getSystem()) {{
712 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
713 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
714 "testBatchedModificationsOnTransactionChain");
716 waitUntilLeader(shard);
718 String transactionChainID = "txChain";
719 String transactionID1 = "tx1";
720 String transactionID2 = "tx2";
722 FiniteDuration duration = duration("5 seconds");
724 // Send a BatchedModifications to start a chained write transaction and ready it.
726 ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
727 YangInstanceIdentifier path = TestModel.TEST_PATH;
728 shard.tell(newBatchedModifications(transactionID1, transactionChainID, path,
729 containerNode, true), getRef());
730 expectMsgClass(duration, BatchedModificationsReply.class);
732 // Create a read Tx on the same chain.
734 shard.tell(new CreateTransaction(transactionID2, TransactionProxy.TransactionType.READ_ONLY.ordinal() ,
735 transactionChainID).toSerializable(), getRef());
737 CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
739 getSystem().actorSelection(createReply.getTransactionActorPath()).tell(new ReadData(path), getRef());
740 ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
741 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
743 // Commit the write transaction.
745 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
746 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
747 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
748 assertEquals("Can commit", true, canCommitReply.getCanCommit());
750 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
751 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
753 // Verify data in the data store.
755 NormalizedNode<?, ?> actualNode = readStore(shard, path);
756 assertEquals("Stored node", containerNode, actualNode);
758 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
763 public void testOnBatchedModificationsWhenNotLeader() {
764 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
765 new ShardTestKit(getSystem()) {{
766 Creator<Shard> creator = new Creator<Shard>() {
768 public Shard create() throws Exception {
769 return new Shard(shardID, Collections.<String,String>emptyMap(),
770 newDatastoreContext(), SCHEMA_CONTEXT) {
772 protected boolean isLeader() {
773 return overrideLeaderCalls.get() ? false : super.isLeader();
777 protected ActorSelection getLeader() {
778 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
785 TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
786 Props.create(new DelegatingShardCreator(creator)), "testOnBatchedModificationsWhenNotLeader");
788 waitUntilLeader(shard);
790 overrideLeaderCalls.set(true);
792 BatchedModifications batched = new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, "");
794 shard.tell(batched, ActorRef.noSender());
796 expectMsgEquals(batched);
798 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
803 public void testCommitWithPersistenceDisabled() throws Throwable {
804 dataStoreContextBuilder.persistent(false);
805 new ShardTestKit(getSystem()) {{
806 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
807 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
808 "testCommitWithPersistenceDisabled");
810 waitUntilLeader(shard);
812 String transactionID = "tx";
813 FiniteDuration duration = duration("5 seconds");
815 // Send a BatchedModifications to start a transaction.
817 NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
818 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true), getRef());
819 expectMsgClass(duration, BatchedModificationsReply.class);
821 // Send the CanCommitTransaction message.
823 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
824 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
825 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
826 assertEquals("Can commit", true, canCommitReply.getCanCommit());
828 // Send the CanCommitTransaction message.
830 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
831 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
833 NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
834 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
836 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
841 public void testCommitWhenTransactionHasNoModifications(){
842 // Note that persistence is enabled which would normally result in the entry getting written to the journal
843 // but here that need not happen
844 new ShardTestKit(getSystem()) {
846 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
847 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
848 "testCommitWhenTransactionHasNoModifications");
850 waitUntilLeader(shard);
852 String transactionID = "tx1";
853 MutableCompositeModification modification = new MutableCompositeModification();
854 DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
855 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
856 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
857 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
859 FiniteDuration duration = duration("5 seconds");
861 // Simulate the ForwardedReadyTransaction messages that would be sent
862 // by the ShardTransaction.
864 shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION,
865 cohort, modification, true), getRef());
866 expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
868 // Send the CanCommitTransaction message.
870 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
871 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
872 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
873 assertEquals("Can commit", true, canCommitReply.getCanCommit());
875 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
876 expectMsgClass(duration, ThreePhaseCommitCohortMessages.CommitTransactionReply.class);
878 InOrder inOrder = inOrder(cohort);
879 inOrder.verify(cohort).canCommit();
880 inOrder.verify(cohort).preCommit();
881 inOrder.verify(cohort).commit();
883 // Use MBean for verification
884 // Committed transaction count should increase as usual
885 assertEquals(1,shard.underlyingActor().getShardMBean().getCommittedTransactionsCount());
887 // Commit index should not advance because this does not go into the journal
888 assertEquals(-1, shard.underlyingActor().getShardMBean().getCommitIndex());
890 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
897 public void testCommitWhenTransactionHasModifications(){
898 new ShardTestKit(getSystem()) {
900 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
901 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
902 "testCommitWhenTransactionHasModifications");
904 waitUntilLeader(shard);
906 String transactionID = "tx1";
907 MutableCompositeModification modification = new MutableCompositeModification();
908 modification.addModification(new DeleteModification(YangInstanceIdentifier.builder().build()));
909 DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
910 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
911 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
912 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
914 FiniteDuration duration = duration("5 seconds");
916 // Simulate the ForwardedReadyTransaction messages that would be sent
917 // by the ShardTransaction.
919 shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION,
920 cohort, modification, true), getRef());
921 expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
923 // Send the CanCommitTransaction message.
925 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
926 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
927 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
928 assertEquals("Can commit", true, canCommitReply.getCanCommit());
930 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
931 expectMsgClass(duration, ThreePhaseCommitCohortMessages.CommitTransactionReply.class);
933 InOrder inOrder = inOrder(cohort);
934 inOrder.verify(cohort).canCommit();
935 inOrder.verify(cohort).preCommit();
936 inOrder.verify(cohort).commit();
938 // Use MBean for verification
939 // Committed transaction count should increase as usual
940 assertEquals(1, shard.underlyingActor().getShardMBean().getCommittedTransactionsCount());
942 // Commit index should advance as we do not have an empty modification
943 assertEquals(0, shard.underlyingActor().getShardMBean().getCommitIndex());
945 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
952 public void testCommitPhaseFailure() throws Throwable {
953 new ShardTestKit(getSystem()) {{
954 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
955 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
956 "testCommitPhaseFailure");
958 waitUntilLeader(shard);
960 // Setup 2 mock cohorts. The first one fails in the commit phase.
962 final String transactionID1 = "tx1";
963 final DOMStoreThreePhaseCommitCohort cohort1 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
964 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
965 doReturn(Futures.immediateFuture(null)).when(cohort1).preCommit();
966 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).commit();
968 final String transactionID2 = "tx2";
969 final DOMStoreThreePhaseCommitCohort cohort2 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort2");
970 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
972 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
974 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
975 DOMStoreThreePhaseCommitCohort actual) {
976 return transactionID1.equals(transactionID) ? cohort1 : cohort2;
980 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
982 FiniteDuration duration = duration("5 seconds");
983 final Timeout timeout = new Timeout(duration);
985 // Send BatchedModifications to start and ready each transaction.
987 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
988 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
989 expectMsgClass(duration, BatchedModificationsReply.class);
991 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
992 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
993 expectMsgClass(duration, BatchedModificationsReply.class);
995 // Send the CanCommitTransaction message for the first Tx.
997 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
998 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
999 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1000 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1002 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1003 // processed after the first Tx completes.
1005 Future<Object> canCommitFuture = Patterns.ask(shard,
1006 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
1008 // Send the CommitTransaction message for the first Tx. This should send back an error
1009 // and trigger the 2nd Tx to proceed.
1011 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
1012 expectMsgClass(duration, akka.actor.Status.Failure.class);
1014 // Wait for the 2nd Tx to complete the canCommit phase.
1016 final CountDownLatch latch = new CountDownLatch(1);
1017 canCommitFuture.onComplete(new OnComplete<Object>() {
1019 public void onComplete(final Throwable t, final Object resp) {
1022 }, getSystem().dispatcher());
1024 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1026 InOrder inOrder = inOrder(cohort1, cohort2);
1027 inOrder.verify(cohort1).canCommit();
1028 inOrder.verify(cohort1).preCommit();
1029 inOrder.verify(cohort1).commit();
1030 inOrder.verify(cohort2).canCommit();
1032 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1037 public void testPreCommitPhaseFailure() throws Throwable {
1038 new ShardTestKit(getSystem()) {{
1039 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1040 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1041 "testPreCommitPhaseFailure");
1043 waitUntilLeader(shard);
1045 String transactionID = "tx1";
1046 final DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
1047 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1048 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).preCommit();
1050 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
1052 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
1053 DOMStoreThreePhaseCommitCohort actual) {
1058 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
1060 FiniteDuration duration = duration("5 seconds");
1062 // Send BatchedModifications to start and ready a transaction.
1064 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
1065 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1066 expectMsgClass(duration, BatchedModificationsReply.class);
1068 // Send the CanCommitTransaction message.
1070 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1071 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1072 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1073 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1075 // Send the CommitTransaction message. This should send back an error
1076 // for preCommit failure.
1078 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
1079 expectMsgClass(duration, akka.actor.Status.Failure.class);
1081 InOrder inOrder = inOrder(cohort);
1082 inOrder.verify(cohort).canCommit();
1083 inOrder.verify(cohort).preCommit();
1085 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1090 public void testCanCommitPhaseFailure() throws Throwable {
1091 new ShardTestKit(getSystem()) {{
1092 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1093 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1094 "testCanCommitPhaseFailure");
1096 waitUntilLeader(shard);
1098 final FiniteDuration duration = duration("5 seconds");
1100 String transactionID = "tx1";
1101 final DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
1102 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1104 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
1106 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
1107 DOMStoreThreePhaseCommitCohort actual) {
1112 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
1114 // Send BatchedModifications to start and ready a transaction.
1116 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
1117 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1118 expectMsgClass(duration, BatchedModificationsReply.class);
1120 // Send the CanCommitTransaction message.
1122 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1123 expectMsgClass(duration, akka.actor.Status.Failure.class);
1125 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1130 public void testAbortBeforeFinishCommit() throws Throwable {
1131 new ShardTestKit(getSystem()) {{
1132 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1133 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1134 "testAbortBeforeFinishCommit");
1136 waitUntilLeader(shard);
1138 final FiniteDuration duration = duration("5 seconds");
1139 InMemoryDOMDataStore dataStore = shard.underlyingActor().getDataStore();
1141 final String transactionID = "tx1";
1142 Function<DOMStoreThreePhaseCommitCohort,ListenableFuture<Void>> preCommit =
1143 new Function<DOMStoreThreePhaseCommitCohort,ListenableFuture<Void>>() {
1145 public ListenableFuture<Void> apply(final DOMStoreThreePhaseCommitCohort cohort) {
1146 ListenableFuture<Void> preCommitFuture = cohort.preCommit();
1148 // Simulate an AbortTransaction message occurring during replication, after
1149 // persisting and before finishing the commit to the in-memory store.
1150 // We have no followers so due to optimizations in the RaftActor, it does not
1151 // attempt replication and thus we can't send an AbortTransaction message b/c
1152 // it would be processed too late after CommitTransaction completes. So we'll
1153 // simulate an AbortTransaction message occurring during replication by calling
1154 // the shard directly.
1156 shard.underlyingActor().doAbortTransaction(transactionID, null);
1158 return preCommitFuture;
1162 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
1163 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1164 expectMsgClass(duration, BatchedModificationsReply.class);
1166 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1167 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1168 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1169 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1171 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
1172 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1174 NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1176 // Since we're simulating an abort occurring during replication and before finish commit,
1177 // the data should still get written to the in-memory store since we've gotten past
1178 // canCommit and preCommit and persisted the data.
1179 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1181 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1186 public void testTransactionCommitTimeout() throws Throwable {
1187 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1189 new ShardTestKit(getSystem()) {{
1190 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1191 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1192 "testTransactionCommitTimeout");
1194 waitUntilLeader(shard);
1196 final FiniteDuration duration = duration("5 seconds");
1198 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1199 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1200 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1202 // Create and ready the 1st Tx - will timeout
1204 String transactionID1 = "tx1";
1205 shard.tell(newBatchedModifications(transactionID1, YangInstanceIdentifier.builder(
1206 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1207 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true), getRef());
1208 expectMsgClass(duration, BatchedModificationsReply.class);
1210 // Create and ready the 2nd Tx
1212 String transactionID2 = "tx2";
1213 YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1214 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1215 shard.tell(newBatchedModifications(transactionID2, listNodePath,
1216 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), true), getRef());
1217 expectMsgClass(duration, BatchedModificationsReply.class);
1219 // canCommit 1st Tx. We don't send the commit so it should timeout.
1221 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1222 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1224 // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1226 shard.tell(new CanCommitTransaction(transactionID2).toSerializable(), getRef());
1227 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1229 // Commit the 2nd Tx.
1231 shard.tell(new CommitTransaction(transactionID2).toSerializable(), getRef());
1232 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1234 NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1235 assertNotNull(listNodePath + " not found", node);
1237 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1242 public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1243 dataStoreContextBuilder.shardTransactionCommitQueueCapacity(1);
1245 new ShardTestKit(getSystem()) {{
1246 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1247 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1248 "testTransactionCommitQueueCapacityExceeded");
1250 waitUntilLeader(shard);
1252 final FiniteDuration duration = duration("5 seconds");
1254 String transactionID1 = "tx1";
1255 String transactionID2 = "tx2";
1256 String transactionID3 = "tx3";
1258 // Send a BatchedModifications to start transactions and ready them.
1260 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1261 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1262 expectMsgClass(duration, BatchedModificationsReply.class);
1264 shard.tell(newBatchedModifications(transactionID2,TestModel.OUTER_LIST_PATH,
1265 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true), getRef());
1266 expectMsgClass(duration, BatchedModificationsReply.class);
1268 shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1269 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1270 expectMsgClass(duration, BatchedModificationsReply.class);
1272 // canCommit 1st Tx.
1274 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1275 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1277 // canCommit the 2nd Tx - it should get queued.
1279 shard.tell(new CanCommitTransaction(transactionID2).toSerializable(), getRef());
1281 // canCommit the 3rd Tx - should exceed queue capacity and fail.
1283 shard.tell(new CanCommitTransaction(transactionID3).toSerializable(), getRef());
1284 expectMsgClass(duration, akka.actor.Status.Failure.class);
1286 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1291 public void testCanCommitBeforeReadyFailure() throws Throwable {
1292 new ShardTestKit(getSystem()) {{
1293 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1294 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1295 "testCanCommitBeforeReadyFailure");
1297 shard.tell(new CanCommitTransaction("tx").toSerializable(), getRef());
1298 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1300 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1305 public void testAbortTransaction() throws Throwable {
1306 new ShardTestKit(getSystem()) {{
1307 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1308 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1309 "testAbortTransaction");
1311 waitUntilLeader(shard);
1313 // Setup 2 simulated transactions with mock cohorts. The first one will be aborted.
1315 final String transactionID1 = "tx1";
1316 final DOMStoreThreePhaseCommitCohort cohort1 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
1317 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1318 doReturn(Futures.immediateFuture(null)).when(cohort1).abort();
1320 final String transactionID2 = "tx2";
1321 final DOMStoreThreePhaseCommitCohort cohort2 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort2");
1322 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1324 FiniteDuration duration = duration("5 seconds");
1325 final Timeout timeout = new Timeout(duration);
1327 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
1329 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
1330 DOMStoreThreePhaseCommitCohort actual) {
1331 return transactionID1.equals(transactionID) ? cohort1 : cohort2;
1335 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
1337 // Send BatchedModifications to start and ready each transaction.
1339 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1340 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1341 expectMsgClass(duration, BatchedModificationsReply.class);
1343 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1344 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1345 expectMsgClass(duration, BatchedModificationsReply.class);
1347 // Send the CanCommitTransaction message for the first Tx.
1349 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1350 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1351 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1352 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1354 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1355 // processed after the first Tx completes.
1357 Future<Object> canCommitFuture = Patterns.ask(shard,
1358 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
1360 // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1363 shard.tell(new AbortTransaction(transactionID1).toSerializable(), getRef());
1364 expectMsgClass(duration, AbortTransactionReply.SERIALIZABLE_CLASS);
1366 // Wait for the 2nd Tx to complete the canCommit phase.
1368 Await.ready(canCommitFuture, duration);
1370 InOrder inOrder = inOrder(cohort1, cohort2);
1371 inOrder.verify(cohort1).canCommit();
1372 inOrder.verify(cohort2).canCommit();
1374 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1379 public void testCreateSnapshot() throws Exception {
1380 testCreateSnapshot(true, "testCreateSnapshot");
1384 public void testCreateSnapshotWithNonPersistentData() throws Exception {
1385 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1388 @SuppressWarnings("serial")
1389 public void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
1391 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1392 class DelegatingPersistentDataProvider implements DataPersistenceProvider {
1393 DataPersistenceProvider delegate;
1395 DelegatingPersistentDataProvider(DataPersistenceProvider delegate) {
1396 this.delegate = delegate;
1400 public boolean isRecoveryApplicable() {
1401 return delegate.isRecoveryApplicable();
1405 public <T> void persist(T o, Procedure<T> procedure) {
1406 delegate.persist(o, procedure);
1410 public void saveSnapshot(Object o) {
1411 savedSnapshot.set(o);
1412 delegate.saveSnapshot(o);
1416 public void deleteSnapshots(SnapshotSelectionCriteria criteria) {
1417 delegate.deleteSnapshots(criteria);
1421 public void deleteMessages(long sequenceNumber) {
1422 delegate.deleteMessages(sequenceNumber);
1426 dataStoreContextBuilder.persistent(persistent);
1428 new ShardTestKit(getSystem()) {{
1429 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1430 Creator<Shard> creator = new Creator<Shard>() {
1432 public Shard create() throws Exception {
1433 return new Shard(shardID, Collections.<String,String>emptyMap(),
1434 newDatastoreContext(), SCHEMA_CONTEXT) {
1436 DelegatingPersistentDataProvider delegating;
1439 protected DataPersistenceProvider persistence() {
1440 if(delegating == null) {
1441 delegating = new DelegatingPersistentDataProvider(super.persistence());
1448 protected void commitSnapshot(final long sequenceNumber) {
1449 super.commitSnapshot(sequenceNumber);
1450 latch.get().countDown();
1456 TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1457 Props.create(new DelegatingShardCreator(creator)), shardActorName);
1459 waitUntilLeader(shard);
1461 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1463 NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.builder().build());
1465 CaptureSnapshot capture = new CaptureSnapshot(-1, -1, -1, -1, -1, -1);
1466 shard.tell(capture, getRef());
1468 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1470 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
1471 savedSnapshot.get() instanceof Snapshot);
1473 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
1475 latch.set(new CountDownLatch(1));
1476 savedSnapshot.set(null);
1478 shard.tell(capture, getRef());
1480 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1482 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
1483 savedSnapshot.get() instanceof Snapshot);
1485 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
1487 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1490 private void verifySnapshot(Snapshot snapshot, NormalizedNode<?,?> expectedRoot) {
1492 NormalizedNode<?, ?> actual = SerializationUtils.deserializeNormalizedNode(snapshot.getState());
1493 assertEquals("Root node", expectedRoot, actual);
1499 * This test simply verifies that the applySnapShot logic will work
1500 * @throws ReadFailedException
1503 public void testInMemoryDataStoreRestore() throws ReadFailedException {
1504 InMemoryDOMDataStore store = new InMemoryDOMDataStore("test", MoreExecutors.sameThreadExecutor());
1506 store.onGlobalContextUpdated(SCHEMA_CONTEXT);
1508 DOMStoreWriteTransaction putTransaction = store.newWriteOnlyTransaction();
1509 putTransaction.write(TestModel.TEST_PATH,
1510 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1511 commitTransaction(putTransaction);
1514 NormalizedNode<?, ?> expected = readStore(store);
1516 DOMStoreWriteTransaction writeTransaction = store.newWriteOnlyTransaction();
1518 writeTransaction.delete(YangInstanceIdentifier.builder().build());
1519 writeTransaction.write(YangInstanceIdentifier.builder().build(), expected);
1521 commitTransaction(writeTransaction);
1523 NormalizedNode<?, ?> actual = readStore(store);
1525 assertEquals(expected, actual);
1529 public void testRecoveryApplicable(){
1531 final DatastoreContext persistentContext = DatastoreContext.newBuilder().
1532 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
1534 final Props persistentProps = Shard.props(shardID, Collections.<String, String>emptyMap(),
1535 persistentContext, SCHEMA_CONTEXT);
1537 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
1538 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
1540 final Props nonPersistentProps = Shard.props(shardID, Collections.<String, String>emptyMap(),
1541 nonPersistentContext, SCHEMA_CONTEXT);
1543 new ShardTestKit(getSystem()) {{
1544 TestActorRef<Shard> shard1 = TestActorRef.create(getSystem(),
1545 persistentProps, "testPersistence1");
1547 assertTrue("Recovery Applicable", shard1.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1549 shard1.tell(PoisonPill.getInstance(), ActorRef.noSender());
1551 TestActorRef<Shard> shard2 = TestActorRef.create(getSystem(),
1552 nonPersistentProps, "testPersistence2");
1554 assertFalse("Recovery Not Applicable", shard2.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1556 shard2.tell(PoisonPill.getInstance(), ActorRef.noSender());
1563 public void testOnDatastoreContext() {
1564 new ShardTestKit(getSystem()) {{
1565 dataStoreContextBuilder.persistent(true);
1567 TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(), "testOnDatastoreContext");
1569 assertEquals("isRecoveryApplicable", true,
1570 shard.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1572 waitUntilLeader(shard);
1574 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
1576 assertEquals("isRecoveryApplicable", false,
1577 shard.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1579 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
1581 assertEquals("isRecoveryApplicable", true,
1582 shard.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1584 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1589 public void testRegisterRoleChangeListener() throws Exception {
1590 new ShardTestKit(getSystem()) {
1592 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1593 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1594 "testRegisterRoleChangeListener");
1596 waitUntilLeader(shard);
1598 TestActorRef<MessageCollectorActor> listener =
1599 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
1601 shard.tell(new RegisterRoleChangeListener(), listener);
1603 // TODO: MessageCollectorActor exists as a test util in both the akka-raft and distributed-datastore
1604 // projects. Need to move it to commons as a regular utility and then we can get rid of this arbitrary
1606 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1608 List<Object> allMatching = MessageCollectorActor.getAllMatching(listener, RegisterRoleChangeListenerReply.class);
1610 assertEquals(1, allMatching.size());
1616 public void testFollowerInitialSyncStatus() throws Exception {
1617 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1618 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1619 "testFollowerInitialSyncStatus");
1621 shard.underlyingActor().onReceiveCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
1623 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1625 shard.underlyingActor().onReceiveCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
1627 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1629 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1632 private void commitTransaction(final DOMStoreWriteTransaction transaction) {
1633 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
1634 ListenableFuture<Void> future =
1635 commitCohort.preCommit();
1638 future = commitCohort.commit();
1640 } catch (InterruptedException | ExecutionException e) {