2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore;
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.mockito.ArgumentMatchers.any;
15 import static org.mockito.ArgumentMatchers.anyString;
16 import static org.mockito.ArgumentMatchers.eq;
17 import static org.mockito.ArgumentMatchers.isA;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.doThrow;
20 import static org.mockito.Mockito.mock;
21 import static org.mockito.Mockito.verify;
22 import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_ONLY;
23 import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_WRITE;
24 import static org.opendaylight.controller.cluster.datastore.TransactionType.WRITE_ONLY;
26 import akka.actor.ActorRef;
27 import akka.actor.ActorSelection;
28 import akka.actor.ActorSystem;
29 import akka.actor.Props;
30 import akka.dispatch.Futures;
31 import akka.util.Timeout;
32 import com.google.common.base.Throwables;
33 import com.google.common.collect.ImmutableSortedSet;
34 import com.google.common.collect.Sets;
35 import com.google.common.util.concurrent.FluentFuture;
36 import com.google.common.util.concurrent.FutureCallback;
37 import com.google.common.util.concurrent.MoreExecutors;
38 import com.google.common.util.concurrent.Uninterruptibles;
39 import java.util.Collection;
40 import java.util.List;
41 import java.util.Optional;
42 import java.util.SortedSet;
43 import java.util.concurrent.CountDownLatch;
44 import java.util.concurrent.ExecutionException;
45 import java.util.concurrent.TimeUnit;
46 import java.util.concurrent.atomic.AtomicReference;
47 import org.junit.Assert;
48 import org.junit.Test;
49 import org.mockito.ArgumentCaptor;
50 import org.mockito.InOrder;
51 import org.mockito.Mockito;
52 import org.opendaylight.controller.cluster.access.concepts.MemberName;
53 import org.opendaylight.controller.cluster.datastore.config.Configuration;
54 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
55 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
56 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
57 import org.opendaylight.controller.cluster.datastore.exceptions.TimeoutException;
58 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
59 import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
61 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
62 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
63 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
64 import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
65 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
66 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
67 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
68 import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregatorTest;
69 import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
70 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
71 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
72 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
73 import org.opendaylight.mdsal.common.api.ReadFailedException;
74 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
75 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
76 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
81 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
82 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
83 import scala.concurrent.Promise;
85 @SuppressWarnings({"resource", "checkstyle:IllegalThrows", "checkstyle:AvoidHidingCauseException"})
86 public class TransactionProxyTest extends AbstractTransactionProxyTest {
88 @SuppressWarnings("serial")
89 static class TestException extends RuntimeException {
93 FluentFuture<?> invoke(TransactionProxy proxy);
97 public void testRead() throws Exception {
98 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
100 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
102 doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
103 eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
105 Optional<NormalizedNode> readOptional = transactionProxy.read(
106 TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
108 assertFalse("NormalizedNode isPresent", readOptional.isPresent());
110 NormalizedNode expectedNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
112 doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync(
113 eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
115 readOptional = transactionProxy.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
117 assertTrue("NormalizedNode isPresent", readOptional.isPresent());
119 assertEquals("Response NormalizedNode", expectedNode, readOptional.get());
122 @Test(expected = ReadFailedException.class)
123 public void testReadWithInvalidReplyMessageType() throws Throwable {
124 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
126 doReturn(Futures.successful(new Object())).when(mockActorContext)
127 .executeOperationAsync(eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
129 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
132 transactionProxy.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
133 } catch (ExecutionException e) {
138 @Test(expected = TestException.class)
139 public void testReadWithAsyncRemoteOperatonFailure() throws Throwable {
140 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
142 doReturn(Futures.failed(new TestException())).when(mockActorContext)
143 .executeOperationAsync(eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
145 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
147 propagateReadFailedExceptionCause(transactionProxy.read(TestModel.TEST_PATH));
150 private void testExceptionOnInitialCreateTransaction(final Exception exToThrow, final Invoker invoker)
152 ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
154 if (exToThrow instanceof PrimaryNotFoundException) {
155 doReturn(Futures.failed(exToThrow)).when(mockActorContext).findPrimaryShardAsync(anyString());
157 doReturn(primaryShardInfoReply(getSystem(), actorRef)).when(mockActorContext)
158 .findPrimaryShardAsync(anyString());
161 doReturn(Futures.failed(exToThrow)).when(mockActorContext).executeOperationAsync(
162 any(ActorSelection.class), any(), any(Timeout.class));
164 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
166 propagateReadFailedExceptionCause(invoker.invoke(transactionProxy));
169 private void testReadWithExceptionOnInitialCreateTransaction(final Exception exToThrow) throws Throwable {
170 testExceptionOnInitialCreateTransaction(exToThrow, proxy -> proxy.read(TestModel.TEST_PATH));
173 @Test(expected = PrimaryNotFoundException.class)
174 public void testReadWhenAPrimaryNotFoundExceptionIsThrown() throws Throwable {
175 testReadWithExceptionOnInitialCreateTransaction(new PrimaryNotFoundException("test"));
178 @Test(expected = TestException.class)
179 public void testReadWhenATimeoutExceptionIsThrown() throws Throwable {
180 testReadWithExceptionOnInitialCreateTransaction(new TimeoutException("test",
181 new TestException()));
184 @Test(expected = TestException.class)
185 public void testReadWhenAnyOtherExceptionIsThrown() throws Throwable {
186 testReadWithExceptionOnInitialCreateTransaction(new TestException());
190 public void testReadWithPriorRecordingOperationSuccessful() throws Exception {
191 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
193 NormalizedNode expectedNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
195 expectBatchedModifications(actorRef, 1);
197 doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync(
198 eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
200 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
202 transactionProxy.write(TestModel.TEST_PATH, expectedNode);
204 Optional<NormalizedNode> readOptional = transactionProxy.read(
205 TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
207 assertTrue("NormalizedNode isPresent", readOptional.isPresent());
208 assertEquals("Response NormalizedNode", expectedNode, readOptional.get());
210 InOrder inOrder = Mockito.inOrder(mockActorContext);
211 inOrder.verify(mockActorContext).executeOperationAsync(
212 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
214 inOrder.verify(mockActorContext).executeOperationAsync(
215 eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
218 @Test(expected = IllegalStateException.class)
219 public void testReadPreConditionCheck() {
220 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
221 transactionProxy.read(TestModel.TEST_PATH);
224 @Test(expected = IllegalArgumentException.class)
225 public void testInvalidCreateTransactionReply() throws Throwable {
226 ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
228 doReturn(getSystem().actorSelection(actorRef.path())).when(mockActorContext)
229 .actorSelection(actorRef.path().toString());
231 doReturn(primaryShardInfoReply(getSystem(), actorRef)).when(mockActorContext)
232 .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
234 doReturn(Futures.successful(new Object())).when(mockActorContext).executeOperationAsync(
235 eq(getSystem().actorSelection(actorRef.path())), eqCreateTransaction(memberName, READ_ONLY),
238 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
240 propagateReadFailedExceptionCause(transactionProxy.read(TestModel.TEST_PATH));
244 public void testExists() throws Exception {
245 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
247 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
249 doReturn(dataExistsReply(false)).when(mockActorContext).executeOperationAsync(
250 eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
252 Boolean exists = transactionProxy.exists(TestModel.TEST_PATH).get();
254 assertEquals("Exists response", Boolean.FALSE, exists);
256 doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync(
257 eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
259 exists = transactionProxy.exists(TestModel.TEST_PATH).get();
261 assertEquals("Exists response", Boolean.TRUE, exists);
264 @Test(expected = PrimaryNotFoundException.class)
265 public void testExistsWhenAPrimaryNotFoundExceptionIsThrown() throws Throwable {
266 testExceptionOnInitialCreateTransaction(new PrimaryNotFoundException("test"),
267 proxy -> proxy.exists(TestModel.TEST_PATH));
270 @Test(expected = ReadFailedException.class)
271 public void testExistsWithInvalidReplyMessageType() throws Throwable {
272 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
274 doReturn(Futures.successful(new Object())).when(mockActorContext)
275 .executeOperationAsync(eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
277 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
280 transactionProxy.exists(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
281 } catch (ExecutionException e) {
286 @Test(expected = TestException.class)
287 public void testExistsWithAsyncRemoteOperatonFailure() throws Throwable {
288 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
290 doReturn(Futures.failed(new TestException())).when(mockActorContext)
291 .executeOperationAsync(eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
293 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
295 propagateReadFailedExceptionCause(transactionProxy.exists(TestModel.TEST_PATH));
299 public void testExistsWithPriorRecordingOperationSuccessful() throws Exception {
300 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
302 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
304 expectBatchedModifications(actorRef, 1);
306 doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync(
307 eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
309 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
311 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
313 Boolean exists = transactionProxy.exists(TestModel.TEST_PATH).get();
315 assertEquals("Exists response", Boolean.TRUE, exists);
317 InOrder inOrder = Mockito.inOrder(mockActorContext);
318 inOrder.verify(mockActorContext).executeOperationAsync(
319 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
321 inOrder.verify(mockActorContext).executeOperationAsync(
322 eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
325 @Test(expected = IllegalStateException.class)
326 public void testExistsPreConditionCheck() {
327 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
328 transactionProxy.exists(TestModel.TEST_PATH);
332 public void testWrite() {
333 dataStoreContextBuilder.shardBatchedModificationCount(1);
334 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
336 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
338 expectBatchedModifications(actorRef, 1);
340 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
342 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
344 verifyOneBatchedModification(actorRef, new WriteModification(TestModel.TEST_PATH, nodeToWrite), false);
348 @SuppressWarnings("checkstyle:IllegalCatch")
349 public void testWriteAfterAsyncRead() throws Exception {
350 ActorRef actorRef = setupActorContextWithoutInitialCreateTransaction(getSystem(),
351 DefaultShardStrategy.DEFAULT_SHARD);
353 Promise<Object> createTxPromise = akka.dispatch.Futures.promise();
354 doReturn(createTxPromise).when(mockActorContext).executeOperationAsync(
355 eq(getSystem().actorSelection(actorRef.path())),
356 eqCreateTransaction(memberName, READ_WRITE), any(Timeout.class));
358 doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
359 eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
361 expectBatchedModificationsReady(actorRef);
363 final NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
365 final TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
367 final CountDownLatch readComplete = new CountDownLatch(1);
368 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
369 com.google.common.util.concurrent.Futures.addCallback(transactionProxy.read(TestModel.TEST_PATH),
370 new FutureCallback<Optional<NormalizedNode>>() {
372 public void onSuccess(final Optional<NormalizedNode> result) {
374 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
375 } catch (Exception e) {
378 readComplete.countDown();
383 public void onFailure(final Throwable failure) {
384 caughtEx.set(failure);
385 readComplete.countDown();
387 }, MoreExecutors.directExecutor());
389 createTxPromise.success(createTransactionReply(actorRef, DataStoreVersions.CURRENT_VERSION));
391 Uninterruptibles.awaitUninterruptibly(readComplete, 5, TimeUnit.SECONDS);
393 final Throwable t = caughtEx.get();
395 Throwables.propagateIfPossible(t, Exception.class);
396 throw new RuntimeException(t);
399 // This sends the batched modification.
400 transactionProxy.ready();
402 verifyOneBatchedModification(actorRef, new WriteModification(TestModel.TEST_PATH, nodeToWrite), true);
405 @Test(expected = IllegalStateException.class)
406 public void testWritePreConditionCheck() {
407 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
408 transactionProxy.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
411 @Test(expected = IllegalStateException.class)
412 public void testWriteAfterReadyPreConditionCheck() {
413 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
415 transactionProxy.ready();
417 transactionProxy.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
421 public void testMerge() {
422 dataStoreContextBuilder.shardBatchedModificationCount(1);
423 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
425 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
427 expectBatchedModifications(actorRef, 1);
429 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
431 transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
433 verifyOneBatchedModification(actorRef, new MergeModification(TestModel.TEST_PATH, nodeToWrite), false);
437 public void testDelete() {
438 dataStoreContextBuilder.shardBatchedModificationCount(1);
439 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
441 expectBatchedModifications(actorRef, 1);
443 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
445 transactionProxy.delete(TestModel.TEST_PATH);
447 verifyOneBatchedModification(actorRef, new DeleteModification(TestModel.TEST_PATH), false);
451 public void testReadWrite() {
452 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
454 final NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
456 doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
457 eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
459 expectBatchedModifications(actorRef, 1);
461 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
463 transactionProxy.read(TestModel.TEST_PATH);
465 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
467 transactionProxy.read(TestModel.TEST_PATH);
469 transactionProxy.read(TestModel.TEST_PATH);
471 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
472 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
474 verifyBatchedModifications(batchedModifications.get(0), false,
475 new WriteModification(TestModel.TEST_PATH, nodeToWrite));
479 public void testReadyWithReadWrite() {
480 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
482 final NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
484 doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
485 eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
487 expectBatchedModificationsReady(actorRef, true);
489 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
491 transactionProxy.read(TestModel.TEST_PATH);
493 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
495 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
497 assertTrue(ready instanceof SingleCommitCohortProxy);
499 verifyCohortFutures((SingleCommitCohortProxy)ready, new CommitTransactionReply().toSerializable());
501 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
502 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
504 verifyBatchedModifications(batchedModifications.get(0), true, true,
505 new WriteModification(TestModel.TEST_PATH, nodeToWrite));
507 assertEquals("getTotalMessageCount", 1, batchedModifications.get(0).getTotalMessagesSent());
511 public void testReadyWithNoModifications() {
512 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
514 doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
515 eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
517 expectBatchedModificationsReady(actorRef, true);
519 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
521 transactionProxy.read(TestModel.TEST_PATH);
523 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
525 assertTrue(ready instanceof SingleCommitCohortProxy);
527 verifyCohortFutures((SingleCommitCohortProxy)ready, new CommitTransactionReply().toSerializable());
529 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
530 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
532 verifyBatchedModifications(batchedModifications.get(0), true, true);
536 public void testReadyWithMultipleShardWrites() {
537 ActorRef actorRef1 = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
539 ActorRef actorRef2 = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY,
540 TestModel.JUNK_QNAME.getLocalName());
542 expectBatchedModificationsReady(actorRef1);
543 expectBatchedModificationsReady(actorRef2);
545 ActorRef actorRef3 = getSystem().actorOf(Props.create(DoNothingActor.class));
547 doReturn(getSystem().actorSelection(actorRef3.path())).when(mockActorContext)
548 .actorSelection(actorRef3.path().toString());
550 doReturn(Futures.successful(newPrimaryShardInfo(actorRef3, createDataTree()))).when(mockActorContext)
551 .findPrimaryShardAsync(eq(CarsModel.BASE_QNAME.getLocalName()));
553 expectReadyLocalTransaction(actorRef3, false);
555 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
557 transactionProxy.write(TestModel.JUNK_PATH, ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
558 transactionProxy.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
559 transactionProxy.write(CarsModel.BASE_PATH, ImmutableNodes.containerNode(CarsModel.BASE_QNAME));
561 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
563 assertTrue(ready instanceof ThreePhaseCommitCohortProxy);
565 verifyCohortFutures((ThreePhaseCommitCohortProxy)ready, actorSelection(actorRef1),
566 actorSelection(actorRef2), actorSelection(actorRef3));
568 SortedSet<String> expShardNames =
569 ImmutableSortedSet.of(DefaultShardStrategy.DEFAULT_SHARD,
570 TestModel.JUNK_QNAME.getLocalName(), CarsModel.BASE_QNAME.getLocalName());
572 ArgumentCaptor<BatchedModifications> batchedMods = ArgumentCaptor.forClass(BatchedModifications.class);
573 verify(mockActorContext).executeOperationAsync(
574 eq(actorSelection(actorRef1)), batchedMods.capture(), any(Timeout.class));
575 assertTrue("Participating shards present", batchedMods.getValue().getParticipatingShardNames().isPresent());
576 assertEquals("Participating shards", expShardNames, batchedMods.getValue().getParticipatingShardNames().get());
578 batchedMods = ArgumentCaptor.forClass(BatchedModifications.class);
579 verify(mockActorContext).executeOperationAsync(
580 eq(actorSelection(actorRef2)), batchedMods.capture(), any(Timeout.class));
581 assertTrue("Participating shards present", batchedMods.getValue().getParticipatingShardNames().isPresent());
582 assertEquals("Participating shards", expShardNames, batchedMods.getValue().getParticipatingShardNames().get());
584 ArgumentCaptor<ReadyLocalTransaction> readyLocalTx = ArgumentCaptor.forClass(ReadyLocalTransaction.class);
585 verify(mockActorContext).executeOperationAsync(
586 eq(actorSelection(actorRef3)), readyLocalTx.capture(), any(Timeout.class));
587 assertTrue("Participating shards present", readyLocalTx.getValue().getParticipatingShardNames().isPresent());
588 assertEquals("Participating shards", expShardNames, readyLocalTx.getValue().getParticipatingShardNames().get());
592 public void testReadyWithWriteOnlyAndLastBatchPending() {
593 dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
595 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
597 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
599 expectBatchedModificationsReady(actorRef, true);
601 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
603 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
605 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
607 assertTrue(ready instanceof SingleCommitCohortProxy);
609 verifyCohortFutures((SingleCommitCohortProxy)ready, new CommitTransactionReply().toSerializable());
611 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
612 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
614 verifyBatchedModifications(batchedModifications.get(0), true, true,
615 new WriteModification(TestModel.TEST_PATH, nodeToWrite));
619 public void testReadyWithWriteOnlyAndLastBatchEmpty() {
620 dataStoreContextBuilder.shardBatchedModificationCount(1).writeOnlyTransactionOptimizationsEnabled(true);
621 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
623 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
625 expectBatchedModificationsReady(actorRef, true);
627 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
629 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
631 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
633 assertTrue(ready instanceof SingleCommitCohortProxy);
635 verifyCohortFutures((SingleCommitCohortProxy)ready, new CommitTransactionReply().toSerializable());
637 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
638 assertEquals("Captured BatchedModifications count", 2, batchedModifications.size());
640 verifyBatchedModifications(batchedModifications.get(0), false,
641 new WriteModification(TestModel.TEST_PATH, nodeToWrite));
643 verifyBatchedModifications(batchedModifications.get(1), true, true);
647 public void testReadyWithReplyFailure() {
648 dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
650 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
652 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
654 expectFailedBatchedModifications(actorRef);
656 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
658 transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
660 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
662 assertTrue(ready instanceof SingleCommitCohortProxy);
664 verifyCohortFutures((SingleCommitCohortProxy)ready, TestException.class);
668 public void testReadyWithDebugContextEnabled() {
669 dataStoreContextBuilder.transactionDebugContextEnabled(true);
671 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
673 expectBatchedModificationsReady(actorRef, true);
675 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
677 transactionProxy.merge(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
679 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
681 assertTrue(ready instanceof DebugThreePhaseCommitCohort);
683 verifyCohortFutures((DebugThreePhaseCommitCohort)ready, new CommitTransactionReply().toSerializable());
687 public void testReadyWithLocalTransaction() {
688 ActorRef shardActorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
690 doReturn(getSystem().actorSelection(shardActorRef.path())).when(mockActorContext)
691 .actorSelection(shardActorRef.path().toString());
693 doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, createDataTree()))).when(mockActorContext)
694 .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
696 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
698 expectReadyLocalTransaction(shardActorRef, true);
700 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
701 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
703 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
704 assertTrue(ready instanceof SingleCommitCohortProxy);
705 verifyCohortFutures((SingleCommitCohortProxy)ready, new CommitTransactionReply().toSerializable());
707 ArgumentCaptor<ReadyLocalTransaction> readyLocalTx = ArgumentCaptor.forClass(ReadyLocalTransaction.class);
708 verify(mockActorContext).executeOperationAsync(
709 eq(actorSelection(shardActorRef)), readyLocalTx.capture(), any(Timeout.class));
710 assertFalse("Participating shards present", readyLocalTx.getValue().getParticipatingShardNames().isPresent());
714 public void testReadyWithLocalTransactionWithFailure() {
715 ActorRef shardActorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
717 doReturn(getSystem().actorSelection(shardActorRef.path())).when(mockActorContext)
718 .actorSelection(shardActorRef.path().toString());
720 DataTree mockDataTree = createDataTree();
721 DataTreeModification mockModification = mockDataTree.takeSnapshot().newModification();
722 doThrow(new RuntimeException("mock")).when(mockModification).ready();
724 doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, mockDataTree))).when(mockActorContext)
725 .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
727 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
729 expectReadyLocalTransaction(shardActorRef, true);
731 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
732 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
734 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
735 assertTrue(ready instanceof SingleCommitCohortProxy);
736 verifyCohortFutures((SingleCommitCohortProxy)ready, RuntimeException.class);
739 private void testWriteOnlyTxWithFindPrimaryShardFailure(final Exception toThrow) {
740 doReturn(Futures.failed(toThrow)).when(mockActorContext).findPrimaryShardAsync(anyString());
742 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
744 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
746 transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
748 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
750 transactionProxy.delete(TestModel.TEST_PATH);
752 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
754 assertTrue(ready instanceof SingleCommitCohortProxy);
756 verifyCohortFutures((SingleCommitCohortProxy)ready, toThrow.getClass());
760 public void testWriteOnlyTxWithPrimaryNotFoundException() {
761 testWriteOnlyTxWithFindPrimaryShardFailure(new PrimaryNotFoundException("mock"));
765 public void testWriteOnlyTxWithNotInitializedException() {
766 testWriteOnlyTxWithFindPrimaryShardFailure(new NotInitializedException("mock"));
770 public void testWriteOnlyTxWithNoShardLeaderException() {
771 testWriteOnlyTxWithFindPrimaryShardFailure(new NoShardLeaderException("mock"));
775 public void testReadyWithInvalidReplyMessageType() {
776 dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
777 ActorRef actorRef1 = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
779 ActorRef actorRef2 = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY,
780 TestModel.JUNK_QNAME.getLocalName());
782 doReturn(Futures.successful(new Object())).when(mockActorContext).executeOperationAsync(
783 eq(actorSelection(actorRef1)), isA(BatchedModifications.class), any(Timeout.class));
785 expectBatchedModificationsReady(actorRef2);
787 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
789 transactionProxy.write(TestModel.JUNK_PATH, ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
790 transactionProxy.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
792 DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
794 assertTrue(ready instanceof ThreePhaseCommitCohortProxy);
796 verifyCohortFutures((ThreePhaseCommitCohortProxy)ready, actorSelection(actorRef2),
797 IllegalArgumentException.class);
801 public void testGetIdentifier() {
802 setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
803 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
805 Object id = transactionProxy.getIdentifier();
806 assertNotNull("getIdentifier returned null", id);
807 assertTrue("Invalid identifier: " + id, id.toString().contains(memberName));
811 public void testClose() {
812 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
814 doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
815 eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
817 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
819 transactionProxy.read(TestModel.TEST_PATH);
821 transactionProxy.close();
823 verify(mockActorContext).sendOperationAsync(
824 eq(actorSelection(actorRef)), isA(CloseTransaction.class));
827 private interface TransactionProxyOperation {
828 void run(TransactionProxy transactionProxy);
831 private PrimaryShardInfo newPrimaryShardInfo(final ActorRef actorRef) {
832 return new PrimaryShardInfo(getSystem().actorSelection(actorRef.path()), DataStoreVersions.CURRENT_VERSION);
835 private PrimaryShardInfo newPrimaryShardInfo(final ActorRef actorRef, final DataTree dataTree) {
836 return new PrimaryShardInfo(getSystem().actorSelection(actorRef.path()), DataStoreVersions.CURRENT_VERSION,
840 private void throttleOperation(final TransactionProxyOperation operation) {
841 throttleOperation(operation, 1, true);
844 private void throttleOperation(final TransactionProxyOperation operation, final int outstandingOpsLimit,
845 final boolean shardFound) {
846 throttleOperation(operation, outstandingOpsLimit, shardFound, TimeUnit.MILLISECONDS.toNanos(
847 mockActorContext.getDatastoreContext().getOperationTimeoutInMillis()));
850 private void throttleOperation(final TransactionProxyOperation operation, final int outstandingOpsLimit,
851 final boolean shardFound, final long expectedCompletionTime) {
852 ActorSystem actorSystem = getSystem();
853 ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
855 // Note that we setting batchedModificationCount to one less than what we need because in TransactionProxy
856 // we now allow one extra permit to be allowed for ready
857 doReturn(dataStoreContextBuilder.operationTimeoutInSeconds(2)
858 .shardBatchedModificationCount(outstandingOpsLimit - 1).build()).when(mockActorContext)
859 .getDatastoreContext();
861 doReturn(actorSystem.actorSelection(shardActorRef.path())).when(mockActorContext)
862 .actorSelection(shardActorRef.path().toString());
865 doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).when(mockActorContext)
866 .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
867 doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).when(mockActorContext)
868 .findPrimaryShardAsync(eq("cars"));
871 doReturn(Futures.failed(new Exception("not found")))
872 .when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
875 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
876 eq(actorSystem.actorSelection(shardActorRef.path())), eqCreateTransaction(memberName, READ_WRITE),
879 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
881 long start = System.nanoTime();
883 operation.run(transactionProxy);
885 long end = System.nanoTime();
887 Assert.assertTrue(String.format("Expected elapsed time: %s. Actual: %s",
888 expectedCompletionTime, end - start),
889 end - start > expectedCompletionTime && end - start < expectedCompletionTime * 2);
893 private void completeOperation(final TransactionProxyOperation operation) {
894 completeOperation(operation, true);
897 private void completeOperation(final TransactionProxyOperation operation, final boolean shardFound) {
898 ActorSystem actorSystem = getSystem();
899 ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
901 doReturn(actorSystem.actorSelection(shardActorRef.path())).when(mockActorContext)
902 .actorSelection(shardActorRef.path().toString());
905 doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).when(mockActorContext)
906 .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
908 doReturn(Futures.failed(new PrimaryNotFoundException("test"))).when(mockActorContext)
909 .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
912 ActorRef txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
913 String actorPath = txActorRef.path().toString();
914 CreateTransactionReply createTransactionReply = new CreateTransactionReply(actorPath, nextTransactionId(),
915 DataStoreVersions.CURRENT_VERSION);
917 doReturn(actorSystem.actorSelection(actorPath)).when(mockActorContext).actorSelection(actorPath);
919 doReturn(Futures.successful(createTransactionReply)).when(mockActorContext).executeOperationAsync(
920 eq(actorSystem.actorSelection(shardActorRef.path())), eqCreateTransaction(memberName, READ_WRITE),
923 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
925 long start = System.nanoTime();
927 operation.run(transactionProxy);
929 long end = System.nanoTime();
931 long expected = TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext()
932 .getOperationTimeoutInMillis());
933 Assert.assertTrue(String.format("Expected elapsed time: %s. Actual: %s",
934 expected, end - start), end - start <= expected);
937 private void completeOperationLocal(final TransactionProxyOperation operation, final DataTree dataTree) {
938 ActorSystem actorSystem = getSystem();
939 ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
941 doReturn(actorSystem.actorSelection(shardActorRef.path())).when(mockActorContext)
942 .actorSelection(shardActorRef.path().toString());
944 doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, dataTree))).when(mockActorContext)
945 .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
947 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
949 long start = System.nanoTime();
951 operation.run(transactionProxy);
953 long end = System.nanoTime();
955 long expected = TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext()
956 .getOperationTimeoutInMillis());
957 Assert.assertTrue(String.format("Expected elapsed time: %s. Actual: %s", expected, end - start),
958 end - start <= expected);
961 private static DataTree createDataTree() {
962 DataTree dataTree = mock(DataTree.class);
963 DataTreeSnapshot dataTreeSnapshot = mock(DataTreeSnapshot.class);
964 DataTreeModification dataTreeModification = mock(DataTreeModification.class);
966 doReturn(dataTreeSnapshot).when(dataTree).takeSnapshot();
967 doReturn(dataTreeModification).when(dataTreeSnapshot).newModification();
972 private static DataTree createDataTree(final NormalizedNode readResponse) {
973 DataTree dataTree = mock(DataTree.class);
974 DataTreeSnapshot dataTreeSnapshot = mock(DataTreeSnapshot.class);
975 DataTreeModification dataTreeModification = mock(DataTreeModification.class);
977 doReturn(dataTreeSnapshot).when(dataTree).takeSnapshot();
978 doReturn(dataTreeModification).when(dataTreeSnapshot).newModification();
979 doReturn(Optional.of(readResponse)).when(dataTreeModification).readNode(any(YangInstanceIdentifier.class));
986 public void testWriteCompletionForLocalShard() {
987 completeOperationLocal(transactionProxy -> {
988 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
990 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
992 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
994 }, createDataTree());
998 public void testWriteThrottlingWhenShardFound() {
999 throttleOperation(transactionProxy -> {
1000 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1002 expectIncompleteBatchedModifications();
1004 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
1006 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
1011 public void testWriteThrottlingWhenShardNotFound() {
1012 // Confirm that there is no throttling when the Shard is not found
1013 completeOperation(transactionProxy -> {
1014 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1016 expectBatchedModifications(2);
1018 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
1020 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
1027 public void testWriteCompletion() {
1028 completeOperation(transactionProxy -> {
1029 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1031 expectBatchedModifications(2);
1033 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
1035 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
1040 public void testMergeThrottlingWhenShardFound() {
1041 throttleOperation(transactionProxy -> {
1042 NormalizedNode nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1044 expectIncompleteBatchedModifications();
1046 transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
1048 transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
1053 public void testMergeThrottlingWhenShardNotFound() {
1054 completeOperation(transactionProxy -> {
1055 NormalizedNode nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1057 expectBatchedModifications(2);
1059 transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
1061 transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
1066 public void testMergeCompletion() {
1067 completeOperation(transactionProxy -> {
1068 NormalizedNode nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1070 expectBatchedModifications(2);
1072 transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
1074 transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
1080 public void testMergeCompletionForLocalShard() {
1081 completeOperationLocal(transactionProxy -> {
1082 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1084 transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
1086 transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
1088 }, createDataTree());
1093 public void testDeleteThrottlingWhenShardFound() {
1095 throttleOperation(transactionProxy -> {
1096 expectIncompleteBatchedModifications();
1098 transactionProxy.delete(TestModel.TEST_PATH);
1100 transactionProxy.delete(TestModel.TEST_PATH);
1106 public void testDeleteThrottlingWhenShardNotFound() {
1108 completeOperation(transactionProxy -> {
1109 expectBatchedModifications(2);
1111 transactionProxy.delete(TestModel.TEST_PATH);
1113 transactionProxy.delete(TestModel.TEST_PATH);
1118 public void testDeleteCompletionForLocalShard() {
1119 completeOperationLocal(transactionProxy -> {
1121 transactionProxy.delete(TestModel.TEST_PATH);
1123 transactionProxy.delete(TestModel.TEST_PATH);
1124 }, createDataTree());
1129 public void testDeleteCompletion() {
1130 completeOperation(transactionProxy -> {
1131 expectBatchedModifications(2);
1133 transactionProxy.delete(TestModel.TEST_PATH);
1135 transactionProxy.delete(TestModel.TEST_PATH);
1141 public void testReadThrottlingWhenShardFound() {
1143 throttleOperation(transactionProxy -> {
1144 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
1145 any(ActorSelection.class), eqReadData());
1147 transactionProxy.read(TestModel.TEST_PATH);
1149 transactionProxy.read(TestModel.TEST_PATH);
1154 public void testReadThrottlingWhenShardNotFound() {
1156 completeOperation(transactionProxy -> {
1157 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
1158 any(ActorSelection.class), eqReadData());
1160 transactionProxy.read(TestModel.TEST_PATH);
1162 transactionProxy.read(TestModel.TEST_PATH);
1168 public void testReadCompletion() {
1169 completeOperation(transactionProxy -> {
1170 NormalizedNode nodeToRead = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1172 doReturn(readDataReply(nodeToRead)).when(mockActorContext).executeOperationAsync(
1173 any(ActorSelection.class), eqReadData(), any(Timeout.class));
1175 transactionProxy.read(TestModel.TEST_PATH);
1177 transactionProxy.read(TestModel.TEST_PATH);
1183 public void testReadCompletionForLocalShard() {
1184 final NormalizedNode nodeToRead = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1185 completeOperationLocal(transactionProxy -> {
1186 transactionProxy.read(TestModel.TEST_PATH);
1188 transactionProxy.read(TestModel.TEST_PATH);
1189 }, createDataTree(nodeToRead));
1194 public void testReadCompletionForLocalShardWhenExceptionOccurs() {
1195 completeOperationLocal(transactionProxy -> {
1196 transactionProxy.read(TestModel.TEST_PATH);
1198 transactionProxy.read(TestModel.TEST_PATH);
1199 }, createDataTree());
1204 public void testExistsThrottlingWhenShardFound() {
1206 throttleOperation(transactionProxy -> {
1207 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
1208 any(ActorSelection.class), eqDataExists());
1210 transactionProxy.exists(TestModel.TEST_PATH);
1212 transactionProxy.exists(TestModel.TEST_PATH);
1217 public void testExistsThrottlingWhenShardNotFound() {
1219 completeOperation(transactionProxy -> {
1220 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
1221 any(ActorSelection.class), eqDataExists());
1223 transactionProxy.exists(TestModel.TEST_PATH);
1225 transactionProxy.exists(TestModel.TEST_PATH);
1231 public void testExistsCompletion() {
1232 completeOperation(transactionProxy -> {
1233 doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync(
1234 any(ActorSelection.class), eqDataExists(), any(Timeout.class));
1236 transactionProxy.exists(TestModel.TEST_PATH);
1238 transactionProxy.exists(TestModel.TEST_PATH);
1244 public void testExistsCompletionForLocalShard() {
1245 final NormalizedNode nodeToRead = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1246 completeOperationLocal(transactionProxy -> {
1247 transactionProxy.exists(TestModel.TEST_PATH);
1249 transactionProxy.exists(TestModel.TEST_PATH);
1250 }, createDataTree(nodeToRead));
1255 public void testExistsCompletionForLocalShardWhenExceptionOccurs() {
1256 completeOperationLocal(transactionProxy -> {
1257 transactionProxy.exists(TestModel.TEST_PATH);
1259 transactionProxy.exists(TestModel.TEST_PATH);
1260 }, createDataTree());
1265 public void testReadyThrottling() {
1267 throttleOperation(transactionProxy -> {
1268 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1270 expectBatchedModifications(1);
1272 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
1274 transactionProxy.ready();
1279 public void testReadyThrottlingWithTwoTransactionContexts() {
1280 throttleOperation(transactionProxy -> {
1281 NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1282 NormalizedNode carsNode = ImmutableNodes.containerNode(CarsModel.BASE_QNAME);
1284 expectBatchedModifications(2);
1286 transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
1288 // Trying to write to Cars will cause another transaction context to get created
1289 transactionProxy.write(CarsModel.BASE_PATH, carsNode);
1291 // Now ready should block for both transaction contexts
1292 transactionProxy.ready();
1293 }, 1, true, TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext()
1294 .getOperationTimeoutInMillis()) * 2);
1297 private void testModificationOperationBatching(final TransactionType type) {
1298 int shardBatchedModificationCount = 3;
1299 dataStoreContextBuilder.shardBatchedModificationCount(shardBatchedModificationCount);
1301 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), type);
1303 expectBatchedModifications(actorRef, shardBatchedModificationCount);
1305 YangInstanceIdentifier writePath1 = TestModel.TEST_PATH;
1306 NormalizedNode writeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1308 YangInstanceIdentifier writePath2 = TestModel.OUTER_LIST_PATH;
1309 NormalizedNode writeNode2 = ImmutableNodes.containerNode(TestModel.OUTER_LIST_QNAME);
1311 YangInstanceIdentifier writePath3 = TestModel.INNER_LIST_PATH;
1312 NormalizedNode writeNode3 = ImmutableNodes.containerNode(TestModel.INNER_LIST_QNAME);
1314 YangInstanceIdentifier mergePath1 = TestModel.TEST_PATH;
1315 NormalizedNode mergeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1317 YangInstanceIdentifier mergePath2 = TestModel.OUTER_LIST_PATH;
1318 NormalizedNode mergeNode2 = ImmutableNodes.containerNode(TestModel.OUTER_LIST_QNAME);
1320 YangInstanceIdentifier mergePath3 = TestModel.INNER_LIST_PATH;
1321 NormalizedNode mergeNode3 = ImmutableNodes.containerNode(TestModel.INNER_LIST_QNAME);
1323 YangInstanceIdentifier deletePath1 = TestModel.TEST_PATH;
1324 YangInstanceIdentifier deletePath2 = TestModel.OUTER_LIST_PATH;
1326 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, type);
1328 transactionProxy.write(writePath1, writeNode1);
1329 transactionProxy.write(writePath2, writeNode2);
1330 transactionProxy.delete(deletePath1);
1331 transactionProxy.merge(mergePath1, mergeNode1);
1332 transactionProxy.merge(mergePath2, mergeNode2);
1333 transactionProxy.write(writePath3, writeNode3);
1334 transactionProxy.merge(mergePath3, mergeNode3);
1335 transactionProxy.delete(deletePath2);
1337 // This sends the last batch.
1338 transactionProxy.ready();
1340 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
1341 assertEquals("Captured BatchedModifications count", 3, batchedModifications.size());
1343 verifyBatchedModifications(batchedModifications.get(0), false, new WriteModification(writePath1, writeNode1),
1344 new WriteModification(writePath2, writeNode2), new DeleteModification(deletePath1));
1346 verifyBatchedModifications(batchedModifications.get(1), false, new MergeModification(mergePath1, mergeNode1),
1347 new MergeModification(mergePath2, mergeNode2), new WriteModification(writePath3, writeNode3));
1349 verifyBatchedModifications(batchedModifications.get(2), true, true,
1350 new MergeModification(mergePath3, mergeNode3), new DeleteModification(deletePath2));
1352 assertEquals("getTotalMessageCount", 3, batchedModifications.get(2).getTotalMessagesSent());
1356 public void testReadWriteModificationOperationBatching() {
1357 testModificationOperationBatching(READ_WRITE);
1361 public void testWriteOnlyModificationOperationBatching() {
1362 testModificationOperationBatching(WRITE_ONLY);
1366 public void testOptimizedWriteOnlyModificationOperationBatching() {
1367 dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
1368 testModificationOperationBatching(WRITE_ONLY);
1372 public void testModificationOperationBatchingWithInterleavedReads() throws Exception {
1374 int shardBatchedModificationCount = 10;
1375 dataStoreContextBuilder.shardBatchedModificationCount(shardBatchedModificationCount);
1377 ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
1379 expectBatchedModifications(actorRef, shardBatchedModificationCount);
1381 final YangInstanceIdentifier writePath1 = TestModel.TEST_PATH;
1382 final NormalizedNode writeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1384 YangInstanceIdentifier writePath2 = TestModel.OUTER_LIST_PATH;
1385 NormalizedNode writeNode2 = ImmutableNodes.containerNode(TestModel.OUTER_LIST_QNAME);
1387 final YangInstanceIdentifier mergePath1 = TestModel.TEST_PATH;
1388 final NormalizedNode mergeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1390 YangInstanceIdentifier mergePath2 = TestModel.INNER_LIST_PATH;
1391 NormalizedNode mergeNode2 = ImmutableNodes.containerNode(TestModel.INNER_LIST_QNAME);
1393 final YangInstanceIdentifier deletePath = TestModel.OUTER_LIST_PATH;
1395 doReturn(readDataReply(writeNode2)).when(mockActorContext).executeOperationAsync(
1396 eq(actorSelection(actorRef)), eqReadData(writePath2), any(Timeout.class));
1398 doReturn(readDataReply(mergeNode2)).when(mockActorContext).executeOperationAsync(
1399 eq(actorSelection(actorRef)), eqReadData(mergePath2), any(Timeout.class));
1401 doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync(
1402 eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
1404 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
1406 transactionProxy.write(writePath1, writeNode1);
1407 transactionProxy.write(writePath2, writeNode2);
1409 Optional<NormalizedNode> readOptional = transactionProxy.read(writePath2).get(5, TimeUnit.SECONDS);
1411 assertTrue("NormalizedNode isPresent", readOptional.isPresent());
1412 assertEquals("Response NormalizedNode", writeNode2, readOptional.get());
1414 transactionProxy.merge(mergePath1, mergeNode1);
1415 transactionProxy.merge(mergePath2, mergeNode2);
1417 readOptional = transactionProxy.read(mergePath2).get(5, TimeUnit.SECONDS);
1419 transactionProxy.delete(deletePath);
1421 Boolean exists = transactionProxy.exists(TestModel.TEST_PATH).get();
1422 assertEquals("Exists response", Boolean.TRUE, exists);
1424 assertTrue("NormalizedNode isPresent", readOptional.isPresent());
1425 assertEquals("Response NormalizedNode", mergeNode2, readOptional.get());
1427 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
1428 assertEquals("Captured BatchedModifications count", 3, batchedModifications.size());
1430 verifyBatchedModifications(batchedModifications.get(0), false, new WriteModification(writePath1, writeNode1),
1431 new WriteModification(writePath2, writeNode2));
1433 verifyBatchedModifications(batchedModifications.get(1), false, new MergeModification(mergePath1, mergeNode1),
1434 new MergeModification(mergePath2, mergeNode2));
1436 verifyBatchedModifications(batchedModifications.get(2), false, new DeleteModification(deletePath));
1438 InOrder inOrder = Mockito.inOrder(mockActorContext);
1439 inOrder.verify(mockActorContext).executeOperationAsync(
1440 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
1442 inOrder.verify(mockActorContext).executeOperationAsync(
1443 eq(actorSelection(actorRef)), eqReadData(writePath2), any(Timeout.class));
1445 inOrder.verify(mockActorContext).executeOperationAsync(
1446 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
1448 inOrder.verify(mockActorContext).executeOperationAsync(
1449 eq(actorSelection(actorRef)), eqReadData(mergePath2), any(Timeout.class));
1451 inOrder.verify(mockActorContext).executeOperationAsync(
1452 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
1454 inOrder.verify(mockActorContext).executeOperationAsync(
1455 eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
1459 public void testReadRoot() throws InterruptedException, ExecutionException, java.util.concurrent.TimeoutException {
1460 EffectiveModelContext schemaContext = SchemaContextHelper.full();
1461 Configuration configuration = mock(Configuration.class);
1462 doReturn(configuration).when(mockActorContext).getConfiguration();
1463 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
1464 doReturn(Sets.newHashSet("test", "cars")).when(configuration).getAllShardNames();
1466 NormalizedNode expectedNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
1467 NormalizedNode expectedNode2 = ImmutableNodes.containerNode(CarsModel.CARS_QNAME);
1469 setUpReadData("test", NormalizedNodeAggregatorTest.getRootNode(expectedNode1, schemaContext));
1470 setUpReadData("cars", NormalizedNodeAggregatorTest.getRootNode(expectedNode2, schemaContext));
1472 doReturn(MemberName.forName(memberName)).when(mockActorContext).getCurrentMemberName();
1474 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
1476 TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
1478 Optional<NormalizedNode> readOptional = transactionProxy.read(
1479 YangInstanceIdentifier.empty()).get(5, TimeUnit.SECONDS);
1481 assertTrue("NormalizedNode isPresent", readOptional.isPresent());
1483 NormalizedNode normalizedNode = readOptional.get();
1485 assertTrue("Expect value to be a Collection", normalizedNode.body() instanceof Collection);
1487 @SuppressWarnings("unchecked")
1488 Collection<NormalizedNode> collection = (Collection<NormalizedNode>) normalizedNode.body();
1490 for (NormalizedNode node : collection) {
1491 assertTrue("Expected " + node + " to be a ContainerNode", node instanceof ContainerNode);
1494 assertTrue("Child with QName = " + TestModel.TEST_QNAME + " not found",
1495 NormalizedNodeAggregatorTest.findChildWithQName(collection, TestModel.TEST_QNAME) != null);
1497 assertEquals(expectedNode1, NormalizedNodeAggregatorTest.findChildWithQName(collection, TestModel.TEST_QNAME));
1499 assertTrue("Child with QName = " + CarsModel.BASE_QNAME + " not found",
1500 NormalizedNodeAggregatorTest.findChildWithQName(collection, CarsModel.BASE_QNAME) != null);
1502 assertEquals(expectedNode2, NormalizedNodeAggregatorTest.findChildWithQName(collection, CarsModel.BASE_QNAME));
1506 private void setUpReadData(final String shardName, final NormalizedNode expectedNode) {
1507 ActorSystem actorSystem = getSystem();
1508 ActorRef shardActorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
1510 doReturn(getSystem().actorSelection(shardActorRef.path())).when(mockActorContext)
1511 .actorSelection(shardActorRef.path().toString());
1513 doReturn(primaryShardInfoReply(getSystem(), shardActorRef)).when(mockActorContext)
1514 .findPrimaryShardAsync(eq(shardName));
1516 ActorRef txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
1518 doReturn(actorSystem.actorSelection(txActorRef.path())).when(mockActorContext)
1519 .actorSelection(txActorRef.path().toString());
1521 doReturn(Futures.successful(createTransactionReply(txActorRef, DataStoreVersions.CURRENT_VERSION)))
1522 .when(mockActorContext).executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
1523 eqCreateTransaction(memberName, TransactionType.READ_ONLY), any(Timeout.class));
1525 doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync(
1526 eq(actorSelection(txActorRef)), eqReadData(YangInstanceIdentifier.empty()), any(Timeout.class));