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 return new Shard(shardID, Collections.<String,String>emptyMap(),
162 newDatastoreContext(), SCHEMA_CONTEXT) {
164 public void onReceiveCommand(final Object message) throws Exception {
165 if(message instanceof ElectionTimeout && firstElectionTimeout) {
166 // Got the first ElectionTimeout. We don't forward it to the
167 // base Shard yet until we've sent the RegisterChangeListener
168 // message. So we signal the onFirstElectionTimeout latch to tell
169 // the main thread to send the RegisterChangeListener message and
170 // start a thread to wait on the onChangeListenerRegistered latch,
171 // which the main thread signals after it has sent the message.
172 // After the onChangeListenerRegistered is triggered, we send the
173 // original ElectionTimeout message to proceed with the election.
174 firstElectionTimeout = false;
175 final ActorRef self = getSelf();
179 Uninterruptibles.awaitUninterruptibly(
180 onChangeListenerRegistered, 5, TimeUnit.SECONDS);
181 self.tell(message, self);
185 onFirstElectionTimeout.countDown();
187 super.onReceiveCommand(message);
194 MockDataChangeListener listener = new MockDataChangeListener(1);
195 ActorRef dclActor = getSystem().actorOf(DataChangeListener.props(listener),
196 "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
198 TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
199 Props.create(new DelegatingShardCreator(creator)),
200 "testRegisterChangeListenerWhenNotLeaderInitially");
202 // Write initial data into the in-memory store.
203 YangInstanceIdentifier path = TestModel.TEST_PATH;
204 writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
206 // Wait until the shard receives the first ElectionTimeout message.
207 assertEquals("Got first ElectionTimeout", true,
208 onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
210 // Now send the RegisterChangeListener and wait for the reply.
211 shard.tell(new RegisterChangeListener(path, dclActor,
212 AsyncDataBroker.DataChangeScope.SUBTREE), getRef());
214 RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
215 RegisterChangeListenerReply.class);
216 assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
218 // Sanity check - verify the shard is not the leader yet.
219 shard.tell(new FindLeader(), getRef());
220 FindLeaderReply findLeadeReply =
221 expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
222 assertNull("Expected the shard not to be the leader", findLeadeReply.getLeaderActor());
224 // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
225 // with the election process.
226 onChangeListenerRegistered.countDown();
228 // Wait for the shard to become the leader and notify our listener with the existing
229 // data in the store.
230 listener.waitForChangeEvents(path);
232 dclActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
233 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
238 public void testCreateTransaction(){
239 new ShardTestKit(getSystem()) {{
240 ActorRef shard = getSystem().actorOf(newShardProps(), "testCreateTransaction");
242 waitUntilLeader(shard);
244 shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
246 shard.tell(new CreateTransaction("txn-1",
247 TransactionProxy.TransactionType.READ_ONLY.ordinal() ).toSerializable(), getRef());
249 CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
250 CreateTransactionReply.class);
252 String path = reply.getTransactionActorPath().toString();
253 assertTrue("Unexpected transaction path " + path,
254 path.contains("akka://test/user/testCreateTransaction/shard-txn-1"));
256 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
261 public void testCreateTransactionOnChain(){
262 new ShardTestKit(getSystem()) {{
263 final ActorRef shard = getSystem().actorOf(newShardProps(), "testCreateTransactionOnChain");
265 waitUntilLeader(shard);
267 shard.tell(new CreateTransaction("txn-1",
268 TransactionProxy.TransactionType.READ_ONLY.ordinal() , "foobar").toSerializable(),
271 CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
272 CreateTransactionReply.class);
274 String path = reply.getTransactionActorPath().toString();
275 assertTrue("Unexpected transaction path " + path,
276 path.contains("akka://test/user/testCreateTransactionOnChain/shard-txn-1"));
278 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
282 @SuppressWarnings("serial")
284 public void testPeerAddressResolved() throws Exception {
285 new ShardTestKit(getSystem()) {{
286 final CountDownLatch recoveryComplete = new CountDownLatch(1);
287 class TestShard extends Shard {
289 super(shardID, Collections.<String, String>singletonMap(shardID.toString(), null),
290 newDatastoreContext(), SCHEMA_CONTEXT);
293 Map<String, String> getPeerAddresses() {
294 return getRaftActorContext().getPeerAddresses();
298 protected void onRecoveryComplete() {
300 super.onRecoveryComplete();
302 recoveryComplete.countDown();
307 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
308 Props.create(new DelegatingShardCreator(new Creator<Shard>() {
310 public TestShard create() throws Exception {
311 return new TestShard();
313 })), "testPeerAddressResolved");
315 //waitUntilLeader(shard);
316 assertEquals("Recovery complete", true,
317 Uninterruptibles.awaitUninterruptibly(recoveryComplete, 5, TimeUnit.SECONDS));
319 String address = "akka://foobar";
320 shard.underlyingActor().onReceiveCommand(new PeerAddressResolved(shardID.toString(), address));
322 assertEquals("getPeerAddresses", address,
323 ((TestShard)shard.underlyingActor()).getPeerAddresses().get(shardID.toString()));
325 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
330 public void testApplySnapshot() throws Exception {
331 TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(),
332 "testApplySnapshot");
334 InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
335 store.onGlobalContextUpdated(SCHEMA_CONTEXT);
337 writeToStore(store, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
339 YangInstanceIdentifier root = YangInstanceIdentifier.builder().build();
340 NormalizedNode<?,?> expected = readStore(store, root);
342 ApplySnapshot applySnapshot = new ApplySnapshot(Snapshot.create(
343 SerializationUtils.serializeNormalizedNode(expected),
344 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4));
346 shard.underlyingActor().onReceiveCommand(applySnapshot);
348 NormalizedNode<?,?> actual = readStore(shard, root);
350 assertEquals("Root node", expected, actual);
352 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
356 public void testApplyState() throws Exception {
358 TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(), "testApplyState");
360 NormalizedNode<?, ?> node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
362 ApplyState applyState = new ApplyState(null, "test", new ReplicatedLogImplEntry(1, 2,
363 newModificationPayload(new WriteModification(TestModel.TEST_PATH, node))));
365 shard.underlyingActor().onReceiveCommand(applyState);
367 NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
368 assertEquals("Applied state", node, actual);
370 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
374 public void testRecovery() throws Exception {
376 // Set up the InMemorySnapshotStore.
378 InMemoryDOMDataStore testStore = InMemoryDOMDataStoreFactory.create("Test", null, null);
379 testStore.onGlobalContextUpdated(SCHEMA_CONTEXT);
381 writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
383 NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.builder().build());
385 InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
386 SerializationUtils.serializeNormalizedNode(root),
387 Collections.<ReplicatedLogEntry>emptyList(), 0, 1, -1, -1));
389 // Set up the InMemoryJournal.
391 InMemoryJournal.addEntry(shardID.toString(), 0, new ReplicatedLogImplEntry(0, 1, newModificationPayload(
392 new WriteModification(TestModel.OUTER_LIST_PATH,
393 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build()))));
395 int nListEntries = 16;
396 Set<Integer> listEntryKeys = new HashSet<>();
398 // Add some ModificationPayload entries
399 for(int i = 1; i <= nListEntries; i++) {
400 listEntryKeys.add(Integer.valueOf(i));
401 YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
402 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
403 Modification mod = new MergeModification(path,
404 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
405 InMemoryJournal.addEntry(shardID.toString(), i, new ReplicatedLogImplEntry(i, 1,
406 newModificationPayload(mod)));
409 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 1,
410 new ApplyJournalEntries(nListEntries));
412 testRecovery(listEntryKeys);
415 private ModificationPayload newModificationPayload(final Modification... mods) throws IOException {
416 MutableCompositeModification compMod = new MutableCompositeModification();
417 for(Modification mod: mods) {
418 compMod.addModification(mod);
421 return new ModificationPayload(compMod);
424 @SuppressWarnings({ "unchecked" })
426 public void testConcurrentThreePhaseCommits() throws Throwable {
427 new ShardTestKit(getSystem()) {{
428 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
429 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
430 "testConcurrentThreePhaseCommits");
432 waitUntilLeader(shard);
434 final String transactionID1 = "tx1";
435 final String transactionID2 = "tx2";
436 final String transactionID3 = "tx3";
438 final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort1 = new AtomicReference<>();
439 final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort2 = new AtomicReference<>();
440 final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort3 = new AtomicReference<>();
441 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
443 public DOMStoreThreePhaseCommitCohort decorate(String transactionID, DOMStoreThreePhaseCommitCohort actual) {
444 if(transactionID.equals(transactionID1)) {
445 mockCohort1.set(createDelegatingMockCohort("cohort1", actual));
446 return mockCohort1.get();
447 } else if(transactionID.equals(transactionID2)) {
448 mockCohort2.set(createDelegatingMockCohort("cohort2", actual));
449 return mockCohort2.get();
451 mockCohort3.set(createDelegatingMockCohort("cohort3", actual));
452 return mockCohort3.get();
457 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
460 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
461 final Timeout timeout = new Timeout(duration);
463 // Send a BatchedModifications message for the first transaction.
465 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
466 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
467 BatchedModificationsReply batchedReply = expectMsgClass(duration, BatchedModificationsReply.class);
468 assertEquals("getCohortPath", shard.path().toString(), batchedReply.getCohortPath());
469 assertEquals("getNumBatched", 1, batchedReply.getNumBatched());
471 // Send the CanCommitTransaction message for the first Tx.
473 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
474 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
475 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
476 assertEquals("Can commit", true, canCommitReply.getCanCommit());
478 // Send BatchedModifications for the next 2 Tx's.
480 shard.tell(newBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
481 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true), getRef());
482 expectMsgClass(duration, BatchedModificationsReply.class);
484 shard.tell(newBatchedModifications(transactionID3, YangInstanceIdentifier.builder(
485 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
486 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true), getRef());
487 expectMsgClass(duration, BatchedModificationsReply.class);
489 // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
490 // processed after the first Tx completes.
492 Future<Object> canCommitFuture1 = Patterns.ask(shard,
493 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
495 Future<Object> canCommitFuture2 = Patterns.ask(shard,
496 new CanCommitTransaction(transactionID3).toSerializable(), timeout);
498 // Send the CommitTransaction message for the first Tx. After it completes, it should
499 // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
501 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
502 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
504 // Wait for the next 2 Tx's to complete.
506 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
507 final CountDownLatch commitLatch = new CountDownLatch(2);
509 class OnFutureComplete extends OnComplete<Object> {
510 private final Class<?> expRespType;
512 OnFutureComplete(final Class<?> expRespType) {
513 this.expRespType = expRespType;
517 public void onComplete(final Throwable error, final Object resp) {
519 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
522 assertEquals("Commit response type", expRespType, resp.getClass());
524 } catch (Exception e) {
530 void onSuccess(final Object resp) throws Exception {
534 class OnCommitFutureComplete extends OnFutureComplete {
535 OnCommitFutureComplete() {
536 super(CommitTransactionReply.SERIALIZABLE_CLASS);
540 public void onComplete(final Throwable error, final Object resp) {
541 super.onComplete(error, resp);
542 commitLatch.countDown();
546 class OnCanCommitFutureComplete extends OnFutureComplete {
547 private final String transactionID;
549 OnCanCommitFutureComplete(final String transactionID) {
550 super(CanCommitTransactionReply.SERIALIZABLE_CLASS);
551 this.transactionID = transactionID;
555 void onSuccess(final Object resp) throws Exception {
556 CanCommitTransactionReply canCommitReply =
557 CanCommitTransactionReply.fromSerializable(resp);
558 assertEquals("Can commit", true, canCommitReply.getCanCommit());
560 Future<Object> commitFuture = Patterns.ask(shard,
561 new CommitTransaction(transactionID).toSerializable(), timeout);
562 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
566 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
567 getSystem().dispatcher());
569 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
570 getSystem().dispatcher());
572 boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
574 if(caughtEx.get() != null) {
575 throw caughtEx.get();
578 assertEquals("Commits complete", true, done);
580 InOrder inOrder = inOrder(mockCohort1.get(), mockCohort2.get(), mockCohort3.get());
581 inOrder.verify(mockCohort1.get()).canCommit();
582 inOrder.verify(mockCohort1.get()).preCommit();
583 inOrder.verify(mockCohort1.get()).commit();
584 inOrder.verify(mockCohort2.get()).canCommit();
585 inOrder.verify(mockCohort2.get()).preCommit();
586 inOrder.verify(mockCohort2.get()).commit();
587 inOrder.verify(mockCohort3.get()).canCommit();
588 inOrder.verify(mockCohort3.get()).preCommit();
589 inOrder.verify(mockCohort3.get()).commit();
591 // Verify data in the data store.
593 NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
594 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
595 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
596 outerList.getValue() instanceof Iterable);
597 Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
598 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
599 entry instanceof MapEntryNode);
600 MapEntryNode mapEntry = (MapEntryNode)entry;
601 Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
602 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
603 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
604 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", 1, idLeaf.get().getValue());
606 verifyLastApplied(shard, 2);
608 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
612 private BatchedModifications newBatchedModifications(String transactionID, YangInstanceIdentifier path,
613 NormalizedNode<?, ?> data, boolean ready) {
614 return newBatchedModifications(transactionID, null, path, data, ready);
617 private BatchedModifications newBatchedModifications(String transactionID, String transactionChainID,
618 YangInstanceIdentifier path, NormalizedNode<?, ?> data, boolean ready) {
619 BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, transactionChainID);
620 batched.addModification(new WriteModification(path, data));
621 batched.setReady(ready);
625 @SuppressWarnings("unchecked")
627 public void testMultipleBatchedModifications() throws Throwable {
628 new ShardTestKit(getSystem()) {{
629 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
630 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
631 "testMultipleBatchedModifications");
633 waitUntilLeader(shard);
635 final String transactionID = "tx";
636 FiniteDuration duration = duration("5 seconds");
638 final AtomicReference<DOMStoreThreePhaseCommitCohort> mockCohort = new AtomicReference<>();
639 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
641 public DOMStoreThreePhaseCommitCohort decorate(String txID, DOMStoreThreePhaseCommitCohort actual) {
642 if(mockCohort.get() == null) {
643 mockCohort.set(createDelegatingMockCohort("cohort", actual));
646 return mockCohort.get();
650 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
652 // Send a BatchedModifications to start a transaction.
654 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
655 ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
656 expectMsgClass(duration, BatchedModificationsReply.class);
658 // Send a couple more BatchedModifications.
660 shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
661 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
662 expectMsgClass(duration, BatchedModificationsReply.class);
664 shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
665 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
666 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true), getRef());
667 expectMsgClass(duration, BatchedModificationsReply.class);
669 // Send the CanCommitTransaction message.
671 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
672 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
673 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
674 assertEquals("Can commit", true, canCommitReply.getCanCommit());
676 // Send the CanCommitTransaction message.
678 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
679 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
681 InOrder inOrder = inOrder(mockCohort.get());
682 inOrder.verify(mockCohort.get()).canCommit();
683 inOrder.verify(mockCohort.get()).preCommit();
684 inOrder.verify(mockCohort.get()).commit();
686 // Verify data in the data store.
688 NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
689 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
690 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
691 outerList.getValue() instanceof Iterable);
692 Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
693 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
694 entry instanceof MapEntryNode);
695 MapEntryNode mapEntry = (MapEntryNode)entry;
696 Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
697 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
698 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
699 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", 1, idLeaf.get().getValue());
701 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
706 public void testBatchedModificationsOnTransactionChain() throws Throwable {
707 new ShardTestKit(getSystem()) {{
708 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
709 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
710 "testBatchedModificationsOnTransactionChain");
712 waitUntilLeader(shard);
714 String transactionChainID = "txChain";
715 String transactionID1 = "tx1";
716 String transactionID2 = "tx2";
718 FiniteDuration duration = duration("5 seconds");
720 // Send a BatchedModifications to start a chained write transaction and ready it.
722 ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
723 YangInstanceIdentifier path = TestModel.TEST_PATH;
724 shard.tell(newBatchedModifications(transactionID1, transactionChainID, path,
725 containerNode, true), getRef());
726 expectMsgClass(duration, BatchedModificationsReply.class);
728 // Create a read Tx on the same chain.
730 shard.tell(new CreateTransaction(transactionID2, TransactionProxy.TransactionType.READ_ONLY.ordinal() ,
731 transactionChainID).toSerializable(), getRef());
733 CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
735 getSystem().actorSelection(createReply.getTransactionActorPath()).tell(new ReadData(path), getRef());
736 ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
737 assertEquals("Read node", containerNode, readReply.getNormalizedNode());
739 // Commit the write transaction.
741 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
742 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
743 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
744 assertEquals("Can commit", true, canCommitReply.getCanCommit());
746 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
747 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
749 // Verify data in the data store.
751 NormalizedNode<?, ?> actualNode = readStore(shard, path);
752 assertEquals("Stored node", containerNode, actualNode);
754 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
759 public void testOnBatchedModificationsWhenNotLeader() {
760 final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
761 new ShardTestKit(getSystem()) {{
762 Creator<Shard> creator = new Creator<Shard>() {
764 public Shard create() throws Exception {
765 return new Shard(shardID, Collections.<String,String>emptyMap(),
766 newDatastoreContext(), SCHEMA_CONTEXT) {
768 protected boolean isLeader() {
769 return overrideLeaderCalls.get() ? false : super.isLeader();
773 protected ActorSelection getLeader() {
774 return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
781 TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
782 Props.create(new DelegatingShardCreator(creator)), "testOnBatchedModificationsWhenNotLeader");
784 waitUntilLeader(shard);
786 overrideLeaderCalls.set(true);
788 BatchedModifications batched = new BatchedModifications("tx", DataStoreVersions.CURRENT_VERSION, "");
790 shard.tell(batched, ActorRef.noSender());
792 expectMsgEquals(batched);
794 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
799 public void testCommitWithPersistenceDisabled() throws Throwable {
800 dataStoreContextBuilder.persistent(false);
801 new ShardTestKit(getSystem()) {{
802 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
803 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
804 "testCommitWithPersistenceDisabled");
806 waitUntilLeader(shard);
808 String transactionID = "tx";
809 FiniteDuration duration = duration("5 seconds");
811 // Send a BatchedModifications to start a transaction.
813 NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
814 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true), getRef());
815 expectMsgClass(duration, BatchedModificationsReply.class);
817 // Send the CanCommitTransaction message.
819 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
820 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
821 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
822 assertEquals("Can commit", true, canCommitReply.getCanCommit());
824 // Send the CanCommitTransaction message.
826 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
827 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
829 NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
830 assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
832 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
837 public void testCommitWhenTransactionHasNoModifications(){
838 // Note that persistence is enabled which would normally result in the entry getting written to the journal
839 // but here that need not happen
840 new ShardTestKit(getSystem()) {
842 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
843 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
844 "testCommitWhenTransactionHasNoModifications");
846 waitUntilLeader(shard);
848 String transactionID = "tx1";
849 MutableCompositeModification modification = new MutableCompositeModification();
850 DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
851 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
852 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
853 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
855 FiniteDuration duration = duration("5 seconds");
857 // Simulate the ForwardedReadyTransaction messages that would be sent
858 // by the ShardTransaction.
860 shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION,
861 cohort, modification, true), getRef());
862 expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
864 // Send the CanCommitTransaction message.
866 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
867 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
868 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
869 assertEquals("Can commit", true, canCommitReply.getCanCommit());
871 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
872 expectMsgClass(duration, ThreePhaseCommitCohortMessages.CommitTransactionReply.class);
874 InOrder inOrder = inOrder(cohort);
875 inOrder.verify(cohort).canCommit();
876 inOrder.verify(cohort).preCommit();
877 inOrder.verify(cohort).commit();
879 // Use MBean for verification
880 // Committed transaction count should increase as usual
881 assertEquals(1,shard.underlyingActor().getShardMBean().getCommittedTransactionsCount());
883 // Commit index should not advance because this does not go into the journal
884 assertEquals(-1, shard.underlyingActor().getShardMBean().getCommitIndex());
886 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
893 public void testCommitWhenTransactionHasModifications(){
894 new ShardTestKit(getSystem()) {
896 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
897 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
898 "testCommitWhenTransactionHasModifications");
900 waitUntilLeader(shard);
902 String transactionID = "tx1";
903 MutableCompositeModification modification = new MutableCompositeModification();
904 modification.addModification(new DeleteModification(YangInstanceIdentifier.builder().build()));
905 DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
906 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
907 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).preCommit();
908 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).commit();
910 FiniteDuration duration = duration("5 seconds");
912 // Simulate the ForwardedReadyTransaction messages that would be sent
913 // by the ShardTransaction.
915 shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION,
916 cohort, modification, true), getRef());
917 expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
919 // Send the CanCommitTransaction message.
921 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
922 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
923 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
924 assertEquals("Can commit", true, canCommitReply.getCanCommit());
926 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
927 expectMsgClass(duration, ThreePhaseCommitCohortMessages.CommitTransactionReply.class);
929 InOrder inOrder = inOrder(cohort);
930 inOrder.verify(cohort).canCommit();
931 inOrder.verify(cohort).preCommit();
932 inOrder.verify(cohort).commit();
934 // Use MBean for verification
935 // Committed transaction count should increase as usual
936 assertEquals(1,shard.underlyingActor().getShardMBean().getCommittedTransactionsCount());
938 // Commit index should advance as we do not have an empty modification
939 assertEquals(0, shard.underlyingActor().getShardMBean().getCommitIndex());
941 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
948 public void testCommitPhaseFailure() throws Throwable {
949 new ShardTestKit(getSystem()) {{
950 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
951 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
952 "testCommitPhaseFailure");
954 waitUntilLeader(shard);
956 // Setup 2 mock cohorts. The first one fails in the commit phase.
958 final String transactionID1 = "tx1";
959 final DOMStoreThreePhaseCommitCohort cohort1 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
960 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
961 doReturn(Futures.immediateFuture(null)).when(cohort1).preCommit();
962 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort1).commit();
964 final String transactionID2 = "tx2";
965 final DOMStoreThreePhaseCommitCohort cohort2 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort2");
966 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
968 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
970 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
971 DOMStoreThreePhaseCommitCohort actual) {
972 return transactionID1.equals(transactionID) ? cohort1 : cohort2;
976 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
978 FiniteDuration duration = duration("5 seconds");
979 final Timeout timeout = new Timeout(duration);
981 // Send BatchedModifications to start and ready each transaction.
983 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
984 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
985 expectMsgClass(duration, BatchedModificationsReply.class);
987 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
988 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
989 expectMsgClass(duration, BatchedModificationsReply.class);
991 // Send the CanCommitTransaction message for the first Tx.
993 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
994 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
995 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
996 assertEquals("Can commit", true, canCommitReply.getCanCommit());
998 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
999 // processed after the first Tx completes.
1001 Future<Object> canCommitFuture = Patterns.ask(shard,
1002 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
1004 // Send the CommitTransaction message for the first Tx. This should send back an error
1005 // and trigger the 2nd Tx to proceed.
1007 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
1008 expectMsgClass(duration, akka.actor.Status.Failure.class);
1010 // Wait for the 2nd Tx to complete the canCommit phase.
1012 final CountDownLatch latch = new CountDownLatch(1);
1013 canCommitFuture.onComplete(new OnComplete<Object>() {
1015 public void onComplete(final Throwable t, final Object resp) {
1018 }, getSystem().dispatcher());
1020 assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
1022 InOrder inOrder = inOrder(cohort1, cohort2);
1023 inOrder.verify(cohort1).canCommit();
1024 inOrder.verify(cohort1).preCommit();
1025 inOrder.verify(cohort1).commit();
1026 inOrder.verify(cohort2).canCommit();
1028 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1033 public void testPreCommitPhaseFailure() throws Throwable {
1034 new ShardTestKit(getSystem()) {{
1035 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1036 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1037 "testPreCommitPhaseFailure");
1039 waitUntilLeader(shard);
1041 String transactionID = "tx1";
1042 final DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
1043 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
1044 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).preCommit();
1046 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
1048 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
1049 DOMStoreThreePhaseCommitCohort actual) {
1054 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
1056 FiniteDuration duration = duration("5 seconds");
1058 // Send BatchedModifications to start and ready a transaction.
1060 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
1061 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1062 expectMsgClass(duration, BatchedModificationsReply.class);
1064 // Send the CanCommitTransaction message.
1066 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1067 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1068 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1069 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1071 // Send the CommitTransaction message. This should send back an error
1072 // for preCommit failure.
1074 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
1075 expectMsgClass(duration, akka.actor.Status.Failure.class);
1077 InOrder inOrder = inOrder(cohort);
1078 inOrder.verify(cohort).canCommit();
1079 inOrder.verify(cohort).preCommit();
1081 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1086 public void testCanCommitPhaseFailure() throws Throwable {
1087 new ShardTestKit(getSystem()) {{
1088 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1089 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1090 "testCanCommitPhaseFailure");
1092 waitUntilLeader(shard);
1094 final FiniteDuration duration = duration("5 seconds");
1096 String transactionID = "tx1";
1097 final DOMStoreThreePhaseCommitCohort cohort = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
1098 doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock"))).when(cohort).canCommit();
1100 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
1102 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
1103 DOMStoreThreePhaseCommitCohort actual) {
1108 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
1110 // Send BatchedModifications to start and ready a transaction.
1112 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
1113 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1114 expectMsgClass(duration, BatchedModificationsReply.class);
1116 // Send the CanCommitTransaction message.
1118 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1119 expectMsgClass(duration, akka.actor.Status.Failure.class);
1121 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1126 public void testAbortBeforeFinishCommit() throws Throwable {
1127 new ShardTestKit(getSystem()) {{
1128 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1129 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1130 "testAbortBeforeFinishCommit");
1132 waitUntilLeader(shard);
1134 final FiniteDuration duration = duration("5 seconds");
1135 InMemoryDOMDataStore dataStore = shard.underlyingActor().getDataStore();
1137 final String transactionID = "tx1";
1138 Function<DOMStoreThreePhaseCommitCohort,ListenableFuture<Void>> preCommit =
1139 new Function<DOMStoreThreePhaseCommitCohort,ListenableFuture<Void>>() {
1141 public ListenableFuture<Void> apply(final DOMStoreThreePhaseCommitCohort cohort) {
1142 ListenableFuture<Void> preCommitFuture = cohort.preCommit();
1144 // Simulate an AbortTransaction message occurring during replication, after
1145 // persisting and before finishing the commit to the in-memory store.
1146 // We have no followers so due to optimizations in the RaftActor, it does not
1147 // attempt replication and thus we can't send an AbortTransaction message b/c
1148 // it would be processed too late after CommitTransaction completes. So we'll
1149 // simulate an AbortTransaction message occurring during replication by calling
1150 // the shard directly.
1152 shard.underlyingActor().doAbortTransaction(transactionID, null);
1154 return preCommitFuture;
1158 shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
1159 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1160 expectMsgClass(duration, BatchedModificationsReply.class);
1162 shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef());
1163 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1164 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1165 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1167 shard.tell(new CommitTransaction(transactionID).toSerializable(), getRef());
1168 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1170 NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
1172 // Since we're simulating an abort occurring during replication and before finish commit,
1173 // the data should still get written to the in-memory store since we've gotten past
1174 // canCommit and preCommit and persisted the data.
1175 assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
1177 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1182 public void testTransactionCommitTimeout() throws Throwable {
1183 dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
1185 new ShardTestKit(getSystem()) {{
1186 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1187 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1188 "testTransactionCommitTimeout");
1190 waitUntilLeader(shard);
1192 final FiniteDuration duration = duration("5 seconds");
1194 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1195 writeToStore(shard, TestModel.OUTER_LIST_PATH,
1196 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1198 // Create and ready the 1st Tx - will timeout
1200 String transactionID1 = "tx1";
1201 shard.tell(newBatchedModifications(transactionID1, YangInstanceIdentifier.builder(
1202 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
1203 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true), getRef());
1204 expectMsgClass(duration, BatchedModificationsReply.class);
1206 // Create and ready the 2nd Tx
1208 String transactionID2 = "tx2";
1209 YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1210 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
1211 shard.tell(newBatchedModifications(transactionID2, listNodePath,
1212 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), true), getRef());
1213 expectMsgClass(duration, BatchedModificationsReply.class);
1215 // canCommit 1st Tx. We don't send the commit so it should timeout.
1217 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1218 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1220 // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
1222 shard.tell(new CanCommitTransaction(transactionID2).toSerializable(), getRef());
1223 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1225 // Commit the 2nd Tx.
1227 shard.tell(new CommitTransaction(transactionID2).toSerializable(), getRef());
1228 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
1230 NormalizedNode<?, ?> node = readStore(shard, listNodePath);
1231 assertNotNull(listNodePath + " not found", node);
1233 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1238 public void testTransactionCommitQueueCapacityExceeded() throws Throwable {
1239 dataStoreContextBuilder.shardTransactionCommitQueueCapacity(1);
1241 new ShardTestKit(getSystem()) {{
1242 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1243 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1244 "testTransactionCommitQueueCapacityExceeded");
1246 waitUntilLeader(shard);
1248 final FiniteDuration duration = duration("5 seconds");
1250 String transactionID1 = "tx1";
1251 String transactionID2 = "tx2";
1252 String transactionID3 = "tx3";
1254 // Send a BatchedModifications to start transactions and ready them.
1256 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1257 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1258 expectMsgClass(duration, BatchedModificationsReply.class);
1260 shard.tell(newBatchedModifications(transactionID2,TestModel.OUTER_LIST_PATH,
1261 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true), getRef());
1262 expectMsgClass(duration, BatchedModificationsReply.class);
1264 shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
1265 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1266 expectMsgClass(duration, BatchedModificationsReply.class);
1268 // canCommit 1st Tx.
1270 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1271 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS);
1273 // canCommit the 2nd Tx - it should get queued.
1275 shard.tell(new CanCommitTransaction(transactionID2).toSerializable(), getRef());
1277 // canCommit the 3rd Tx - should exceed queue capacity and fail.
1279 shard.tell(new CanCommitTransaction(transactionID3).toSerializable(), getRef());
1280 expectMsgClass(duration, akka.actor.Status.Failure.class);
1282 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1287 public void testCanCommitBeforeReadyFailure() throws Throwable {
1288 new ShardTestKit(getSystem()) {{
1289 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1290 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1291 "testCanCommitBeforeReadyFailure");
1293 shard.tell(new CanCommitTransaction("tx").toSerializable(), getRef());
1294 expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
1296 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1301 public void testAbortTransaction() throws Throwable {
1302 new ShardTestKit(getSystem()) {{
1303 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1304 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1305 "testAbortTransaction");
1307 waitUntilLeader(shard);
1309 // Setup 2 simulated transactions with mock cohorts. The first one will be aborted.
1311 final String transactionID1 = "tx1";
1312 final DOMStoreThreePhaseCommitCohort cohort1 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort1");
1313 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort1).canCommit();
1314 doReturn(Futures.immediateFuture(null)).when(cohort1).abort();
1316 final String transactionID2 = "tx2";
1317 final DOMStoreThreePhaseCommitCohort cohort2 = mock(DOMStoreThreePhaseCommitCohort.class, "cohort2");
1318 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort2).canCommit();
1320 FiniteDuration duration = duration("5 seconds");
1321 final Timeout timeout = new Timeout(duration);
1323 ShardCommitCoordinator.CohortDecorator cohortDecorator = new ShardCommitCoordinator.CohortDecorator() {
1325 public DOMStoreThreePhaseCommitCohort decorate(String transactionID,
1326 DOMStoreThreePhaseCommitCohort actual) {
1327 return transactionID1.equals(transactionID) ? cohort1 : cohort2;
1331 shard.underlyingActor().getCommitCoordinator().setCohortDecorator(cohortDecorator);
1333 // Send BatchedModifications to start and ready each transaction.
1335 shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
1336 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1337 expectMsgClass(duration, BatchedModificationsReply.class);
1339 shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
1340 ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
1341 expectMsgClass(duration, BatchedModificationsReply.class);
1343 // Send the CanCommitTransaction message for the first Tx.
1345 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
1346 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
1347 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
1348 assertEquals("Can commit", true, canCommitReply.getCanCommit());
1350 // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
1351 // processed after the first Tx completes.
1353 Future<Object> canCommitFuture = Patterns.ask(shard,
1354 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
1356 // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
1359 shard.tell(new AbortTransaction(transactionID1).toSerializable(), getRef());
1360 expectMsgClass(duration, AbortTransactionReply.SERIALIZABLE_CLASS);
1362 // Wait for the 2nd Tx to complete the canCommit phase.
1364 Await.ready(canCommitFuture, duration);
1366 InOrder inOrder = inOrder(cohort1, cohort2);
1367 inOrder.verify(cohort1).canCommit();
1368 inOrder.verify(cohort2).canCommit();
1370 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1375 public void testCreateSnapshot() throws Exception {
1376 testCreateSnapshot(true, "testCreateSnapshot");
1380 public void testCreateSnapshotWithNonPersistentData() throws Exception {
1381 testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
1384 @SuppressWarnings("serial")
1385 public void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
1387 final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
1388 class DelegatingPersistentDataProvider implements DataPersistenceProvider {
1389 DataPersistenceProvider delegate;
1391 DelegatingPersistentDataProvider(DataPersistenceProvider delegate) {
1392 this.delegate = delegate;
1396 public boolean isRecoveryApplicable() {
1397 return delegate.isRecoveryApplicable();
1401 public <T> void persist(T o, Procedure<T> procedure) {
1402 delegate.persist(o, procedure);
1406 public void saveSnapshot(Object o) {
1407 savedSnapshot.set(o);
1408 delegate.saveSnapshot(o);
1412 public void deleteSnapshots(SnapshotSelectionCriteria criteria) {
1413 delegate.deleteSnapshots(criteria);
1417 public void deleteMessages(long sequenceNumber) {
1418 delegate.deleteMessages(sequenceNumber);
1422 dataStoreContextBuilder.persistent(persistent);
1424 new ShardTestKit(getSystem()) {{
1425 final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
1426 Creator<Shard> creator = new Creator<Shard>() {
1428 public Shard create() throws Exception {
1429 return new Shard(shardID, Collections.<String,String>emptyMap(),
1430 newDatastoreContext(), SCHEMA_CONTEXT) {
1432 DelegatingPersistentDataProvider delegating;
1435 protected DataPersistenceProvider persistence() {
1436 if(delegating == null) {
1437 delegating = new DelegatingPersistentDataProvider(super.persistence());
1444 protected void commitSnapshot(final long sequenceNumber) {
1445 super.commitSnapshot(sequenceNumber);
1446 latch.get().countDown();
1452 TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1453 Props.create(new DelegatingShardCreator(creator)), shardActorName);
1455 waitUntilLeader(shard);
1457 writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1459 NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.builder().build());
1461 CaptureSnapshot capture = new CaptureSnapshot(-1, -1, -1, -1, -1, -1);
1462 shard.tell(capture, getRef());
1464 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1466 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
1467 savedSnapshot.get() instanceof Snapshot);
1469 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
1471 latch.set(new CountDownLatch(1));
1472 savedSnapshot.set(null);
1474 shard.tell(capture, getRef());
1476 assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
1478 assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
1479 savedSnapshot.get() instanceof Snapshot);
1481 verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
1483 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1486 private void verifySnapshot(Snapshot snapshot, NormalizedNode<?,?> expectedRoot) {
1488 NormalizedNode<?, ?> actual = SerializationUtils.deserializeNormalizedNode(snapshot.getState());
1489 assertEquals("Root node", expectedRoot, actual);
1495 * This test simply verifies that the applySnapShot logic will work
1496 * @throws ReadFailedException
1499 public void testInMemoryDataStoreRestore() throws ReadFailedException {
1500 InMemoryDOMDataStore store = new InMemoryDOMDataStore("test", MoreExecutors.sameThreadExecutor());
1502 store.onGlobalContextUpdated(SCHEMA_CONTEXT);
1504 DOMStoreWriteTransaction putTransaction = store.newWriteOnlyTransaction();
1505 putTransaction.write(TestModel.TEST_PATH,
1506 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1507 commitTransaction(putTransaction);
1510 NormalizedNode<?, ?> expected = readStore(store);
1512 DOMStoreWriteTransaction writeTransaction = store.newWriteOnlyTransaction();
1514 writeTransaction.delete(YangInstanceIdentifier.builder().build());
1515 writeTransaction.write(YangInstanceIdentifier.builder().build(), expected);
1517 commitTransaction(writeTransaction);
1519 NormalizedNode<?, ?> actual = readStore(store);
1521 assertEquals(expected, actual);
1525 public void testRecoveryApplicable(){
1527 final DatastoreContext persistentContext = DatastoreContext.newBuilder().
1528 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
1530 final Props persistentProps = Shard.props(shardID, Collections.<String, String>emptyMap(),
1531 persistentContext, SCHEMA_CONTEXT);
1533 final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
1534 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
1536 final Props nonPersistentProps = Shard.props(shardID, Collections.<String, String>emptyMap(),
1537 nonPersistentContext, SCHEMA_CONTEXT);
1539 new ShardTestKit(getSystem()) {{
1540 TestActorRef<Shard> shard1 = TestActorRef.create(getSystem(),
1541 persistentProps, "testPersistence1");
1543 assertTrue("Recovery Applicable", shard1.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1545 shard1.tell(PoisonPill.getInstance(), ActorRef.noSender());
1547 TestActorRef<Shard> shard2 = TestActorRef.create(getSystem(),
1548 nonPersistentProps, "testPersistence2");
1550 assertFalse("Recovery Not Applicable", shard2.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1552 shard2.tell(PoisonPill.getInstance(), ActorRef.noSender());
1559 public void testOnDatastoreContext() {
1560 new ShardTestKit(getSystem()) {{
1561 dataStoreContextBuilder.persistent(true);
1563 TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(), "testOnDatastoreContext");
1565 assertEquals("isRecoveryApplicable", true,
1566 shard.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1568 waitUntilLeader(shard);
1570 shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
1572 assertEquals("isRecoveryApplicable", false,
1573 shard.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1575 shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
1577 assertEquals("isRecoveryApplicable", true,
1578 shard.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable());
1580 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1585 public void testRegisterRoleChangeListener() throws Exception {
1586 new ShardTestKit(getSystem()) {
1588 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1589 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1590 "testRegisterRoleChangeListener");
1592 waitUntilLeader(shard);
1594 TestActorRef<MessageCollectorActor> listener =
1595 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
1597 shard.tell(new RegisterRoleChangeListener(), listener);
1599 // TODO: MessageCollectorActor exists as a test util in both the akka-raft and distributed-datastore
1600 // projects. Need to move it to commons as a regular utility and then we can get rid of this arbitrary
1602 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1604 List<Object> allMatching = MessageCollectorActor.getAllMatching(listener, RegisterRoleChangeListenerReply.class);
1606 assertEquals(1, allMatching.size());
1612 public void testFollowerInitialSyncStatus() throws Exception {
1613 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
1614 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
1615 "testFollowerInitialSyncStatus");
1617 shard.underlyingActor().onReceiveCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
1619 assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1621 shard.underlyingActor().onReceiveCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
1623 assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
1625 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
1628 private void commitTransaction(final DOMStoreWriteTransaction transaction) {
1629 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
1630 ListenableFuture<Void> future =
1631 commitCohort.preCommit();
1634 future = commitCohort.commit();
1636 } catch (InterruptedException | ExecutionException e) {