2 * Copyright (c) 2015 Brocade Communications 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.assertNotNull;
12 import static org.junit.Assert.assertTrue;
13 import static org.junit.Assert.fail;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.argThat;
16 import static org.mockito.Matchers.eq;
17 import static org.mockito.Matchers.isA;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.verify;
22 import akka.actor.ActorRef;
23 import akka.actor.ActorSelection;
24 import akka.actor.ActorSystem;
25 import akka.actor.Props;
26 import akka.dispatch.Futures;
27 import akka.testkit.javadsl.TestKit;
28 import akka.util.Timeout;
29 import com.codahale.metrics.MetricRegistry;
30 import com.codahale.metrics.Timer;
31 import com.google.common.base.Throwables;
32 import com.google.common.collect.ImmutableMap;
33 import com.google.common.util.concurrent.FluentFuture;
34 import com.typesafe.config.Config;
35 import com.typesafe.config.ConfigFactory;
36 import java.util.ArrayList;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.Objects;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.TimeUnit;
43 import org.junit.AfterClass;
44 import org.junit.Before;
45 import org.junit.BeforeClass;
46 import org.mockito.ArgumentCaptor;
47 import org.mockito.ArgumentMatcher;
48 import org.mockito.Mock;
49 import org.mockito.Mockito;
50 import org.mockito.MockitoAnnotations;
51 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
52 import org.opendaylight.controller.cluster.access.concepts.MemberName;
53 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
54 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
55 import org.opendaylight.controller.cluster.datastore.config.Configuration;
56 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
57 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
58 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
59 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
61 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
62 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
63 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
64 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
65 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
66 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
68 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
69 import org.opendaylight.controller.cluster.datastore.modification.Modification;
70 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
71 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
72 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
73 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
74 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
75 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
76 import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
77 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
78 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
79 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
80 import org.opendaylight.mdsal.common.api.ReadFailedException;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
83 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
86 import scala.concurrent.Await;
87 import scala.concurrent.Future;
88 import scala.concurrent.duration.Duration;
91 * Abstract base class for TransactionProxy unit tests.
93 * @author Thomas Pantelis
95 public abstract class AbstractTransactionProxyTest extends AbstractTest {
96 protected final Logger log = LoggerFactory.getLogger(getClass());
98 private static ActorSystem system;
100 private final Configuration configuration = new MockConfiguration() {
101 Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
102 TestModel.JUNK_QNAME.getLocalName(), new ShardStrategy() {
104 public String findShard(final YangInstanceIdentifier path) {
105 return TestModel.JUNK_QNAME.getLocalName();
109 public YangInstanceIdentifier getPrefixForPath(final YangInstanceIdentifier path) {
110 return YangInstanceIdentifier.EMPTY;
113 CarsModel.BASE_QNAME.getLocalName(), new ShardStrategy() {
115 public String findShard(final YangInstanceIdentifier path) {
116 return CarsModel.BASE_QNAME.getLocalName();
120 public YangInstanceIdentifier getPrefixForPath(final YangInstanceIdentifier path) {
121 return YangInstanceIdentifier.EMPTY;
126 public ShardStrategy getStrategyForModule(final String moduleName) {
127 return strategyMap.get(moduleName);
131 public String getModuleNameFromNameSpace(final String nameSpace) {
132 if (TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
133 return TestModel.JUNK_QNAME.getLocalName();
134 } else if (CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
135 return CarsModel.BASE_QNAME.getLocalName();
142 protected ActorContext mockActorContext;
144 protected TransactionContextFactory mockComponentFactory;
146 private SchemaContext schemaContext;
149 private ClusterWrapper mockClusterWrapper;
151 protected final String memberName = "mock-member";
153 private final int operationTimeoutInSeconds = 2;
154 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
155 .operationTimeoutInSeconds(operationTimeoutInSeconds);
158 public static void setUpClass() {
160 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
161 .put("akka.actor.default-dispatcher.type",
162 "akka.testkit.CallingThreadDispatcherConfigurator").build())
163 .withFallback(ConfigFactory.load());
164 system = ActorSystem.create("test", config);
168 public static void tearDownClass() {
169 TestKit.shutdownActorSystem(system);
174 public void setUp() {
175 MockitoAnnotations.initMocks(this);
177 schemaContext = TestModel.createTestContext();
179 doReturn(getSystem()).when(mockActorContext).getActorSystem();
180 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
181 doReturn(MemberName.forName(memberName)).when(mockActorContext).getCurrentMemberName();
182 doReturn(new ShardStrategyFactory(configuration,
183 LogicalDatastoreType.CONFIGURATION)).when(mockActorContext).getShardStrategyFactory();
184 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
185 doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
186 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
187 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
188 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
190 final ClientIdentifier mockClientId = MockIdentifiers.clientIdentifier(getClass(), memberName);
191 mockComponentFactory = new TransactionContextFactory(mockActorContext, mockClientId);
193 Timer timer = new MetricRegistry().timer("test");
194 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
197 protected ActorSystem getSystem() {
201 protected CreateTransaction eqCreateTransaction(final String expMemberName,
202 final TransactionType type) {
203 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
205 public boolean matches(final Object argument) {
206 if (CreateTransaction.class.equals(argument.getClass())) {
207 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
208 return obj.getTransactionId().getHistoryId().getClientId().getFrontendId().getMemberName()
209 .getName().equals(expMemberName) && obj.getTransactionType() == type.ordinal();
216 return argThat(matcher);
219 protected DataExists eqDataExists() {
220 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
222 public boolean matches(final Object argument) {
223 return argument instanceof DataExists && ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
227 return argThat(matcher);
230 protected ReadData eqReadData() {
231 return eqReadData(TestModel.TEST_PATH);
234 protected ReadData eqReadData(final YangInstanceIdentifier path) {
235 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
237 public boolean matches(final Object argument) {
238 return argument instanceof ReadData && ((ReadData)argument).getPath().equals(path);
242 return argThat(matcher);
245 protected Future<Object> readyTxReply(final String path) {
246 return Futures.successful((Object)new ReadyTransactionReply(path));
250 protected Future<ReadDataReply> readDataReply(final NormalizedNode<?, ?> data) {
251 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
254 protected Future<DataExistsReply> dataExistsReply(final boolean exists) {
255 return Futures.successful(new DataExistsReply(exists, DataStoreVersions.CURRENT_VERSION));
258 protected Future<BatchedModificationsReply> batchedModificationsReply(final int count) {
259 return Futures.successful(new BatchedModificationsReply(count));
262 @SuppressWarnings("unchecked")
263 protected Future<Object> incompleteFuture() {
264 return mock(Future.class);
267 protected ActorSelection actorSelection(final ActorRef actorRef) {
268 return getSystem().actorSelection(actorRef.path());
271 protected void expectBatchedModifications(final ActorRef actorRef, final int count) {
272 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
273 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
276 protected void expectBatchedModifications(final int count) {
277 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
278 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
281 protected void expectBatchedModificationsReady(final ActorRef actorRef) {
282 expectBatchedModificationsReady(actorRef, false);
285 protected void expectBatchedModificationsReady(final ActorRef actorRef, final boolean doCommitOnReady) {
286 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
287 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
288 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
291 protected void expectIncompleteBatchedModifications() {
292 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
293 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
296 protected void expectFailedBatchedModifications(final ActorRef actorRef) {
297 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
298 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
301 protected void expectReadyLocalTransaction(final ActorRef actorRef, final boolean doCommitOnReady) {
302 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
303 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
304 eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
307 protected CreateTransactionReply createTransactionReply(final ActorRef actorRef, final short transactionVersion) {
308 return new CreateTransactionReply(actorRef.path().toString(), nextTransactionId(), transactionVersion);
311 protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem) {
312 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
315 protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
316 final String shardName) {
317 return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
318 DataStoreVersions.CURRENT_VERSION);
321 protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
322 final String shardName, final short transactionVersion) {
323 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
324 log.info("Created mock shard actor {}", actorRef);
326 doReturn(actorSystem.actorSelection(actorRef.path()))
327 .when(mockActorContext).actorSelection(actorRef.path().toString());
329 doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion))
330 .when(mockActorContext).findPrimaryShardAsync(eq(shardName));
335 protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef) {
336 return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
339 protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef,
340 final short transactionVersion) {
341 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
342 transactionVersion));
345 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
346 final TransactionType type, final short transactionVersion, final String shardName) {
347 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
350 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
351 memberName, shardActorRef);
354 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
355 final TransactionType type, final short transactionVersion, final String prefix,
356 final ActorRef shardActorRef) {
359 if (type == TransactionType.WRITE_ONLY
360 && dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
361 txActorRef = shardActorRef;
363 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
364 log.info("Created mock shard Tx actor {}", txActorRef);
366 doReturn(actorSystem.actorSelection(txActorRef.path()))
367 .when(mockActorContext).actorSelection(txActorRef.path().toString());
369 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext)
370 .executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
371 eqCreateTransaction(prefix, type), any(Timeout.class));
377 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
378 final TransactionType type) {
379 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
380 DefaultShardStrategy.DEFAULT_SHARD);
383 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
384 final TransactionType type,
385 final String shardName) {
386 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
390 @SuppressWarnings({"checkstyle:avoidHidingCauseException", "checkstyle:IllegalThrows"})
391 protected void propagateReadFailedExceptionCause(final FluentFuture<?> future) throws Throwable {
393 future.get(5, TimeUnit.SECONDS);
394 fail("Expected ReadFailedException");
395 } catch (ExecutionException e) {
396 final Throwable cause = e.getCause();
397 assertTrue("Unexpected cause: " + cause.getClass(), cause instanceof ReadFailedException);
398 throw Throwables.getRootCause(cause);
402 protected List<BatchedModifications> captureBatchedModifications(final ActorRef actorRef) {
403 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
404 ArgumentCaptor.forClass(BatchedModifications.class);
405 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
406 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture(), any(Timeout.class));
408 List<BatchedModifications> batchedModifications = filterCaptured(
409 batchedModificationsCaptor, BatchedModifications.class);
410 return batchedModifications;
413 protected <T> List<T> filterCaptured(final ArgumentCaptor<T> captor, final Class<T> type) {
414 List<T> captured = new ArrayList<>();
415 for (T c: captor.getAllValues()) {
416 if (type.isInstance(c)) {
424 protected void verifyOneBatchedModification(final ActorRef actorRef, final Modification expected,
425 final boolean expIsReady) {
426 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
427 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
429 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
432 protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
433 final Modification... expected) {
434 verifyBatchedModifications(message, expIsReady, false, expected);
437 protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
438 final boolean expIsDoCommitOnReady, final Modification... expected) {
439 assertEquals("Message type", BatchedModifications.class, message.getClass());
440 BatchedModifications batchedModifications = (BatchedModifications)message;
441 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
442 assertEquals("isReady", expIsReady, batchedModifications.isReady());
443 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
444 for (int i = 0; i < batchedModifications.getModifications().size(); i++) {
445 Modification actual = batchedModifications.getModifications().get(i);
446 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
447 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
448 ((AbstractModification)actual).getPath());
449 if (actual instanceof WriteModification) {
450 assertEquals("getData", ((WriteModification)expected[i]).getData(),
451 ((WriteModification)actual).getData());
456 @SuppressWarnings("checkstyle:IllegalCatch")
457 protected void verifyCohortFutures(final AbstractThreePhaseCommitCohort<?> proxy,
458 final Object... expReplies) {
459 assertEquals("getReadyOperationFutures size", expReplies.length,
460 proxy.getCohortFutures().size());
462 List<Object> futureResults = new ArrayList<>();
463 for (Future<?> future : proxy.getCohortFutures()) {
464 assertNotNull("Ready operation Future is null", future);
466 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
467 } catch (Exception e) {
468 futureResults.add(e);
472 for (Object expReply : expReplies) {
473 boolean found = false;
474 Iterator<?> iter = futureResults.iterator();
475 while (iter.hasNext()) {
476 Object actual = iter.next();
477 if (CommitTransactionReply.isSerializedType(expReply)
478 && CommitTransactionReply.isSerializedType(actual)) {
480 } else if (expReply instanceof ActorSelection && Objects.equals(expReply, actual)) {
482 } else if (expReply instanceof Class && ((Class<?>) expReply).isInstance(actual)) {
493 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));