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.io.IOException;
37 import java.util.ArrayList;
38 import java.util.Iterator;
39 import java.util.List;
41 import java.util.Objects;
42 import java.util.concurrent.ExecutionException;
43 import java.util.concurrent.TimeUnit;
44 import org.junit.AfterClass;
45 import org.junit.Before;
46 import org.junit.BeforeClass;
47 import org.mockito.ArgumentCaptor;
48 import org.mockito.ArgumentMatcher;
49 import org.mockito.Mock;
50 import org.mockito.Mockito;
51 import org.mockito.MockitoAnnotations;
52 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
53 import org.opendaylight.controller.cluster.access.concepts.MemberName;
54 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
55 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
56 import org.opendaylight.controller.cluster.datastore.config.Configuration;
57 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
58 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
59 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
60 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
61 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
62 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
63 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
64 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
65 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
66 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
67 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
68 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
69 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
70 import org.opendaylight.controller.cluster.datastore.modification.Modification;
71 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
72 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
73 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
74 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
75 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
76 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
77 import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
78 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
79 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
80 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
81 import org.opendaylight.mdsal.common.api.ReadFailedException;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
84 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87 import scala.concurrent.Await;
88 import scala.concurrent.Future;
89 import scala.concurrent.duration.Duration;
92 * Abstract base class for TransactionProxy unit tests.
94 * @author Thomas Pantelis
96 public abstract class AbstractTransactionProxyTest extends AbstractTest {
97 protected final Logger log = LoggerFactory.getLogger(getClass());
99 private static ActorSystem system;
101 private final Configuration configuration = new MockConfiguration() {
102 Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
103 TestModel.JUNK_QNAME.getLocalName(), new ShardStrategy() {
105 public String findShard(final YangInstanceIdentifier path) {
106 return TestModel.JUNK_QNAME.getLocalName();
110 public YangInstanceIdentifier getPrefixForPath(final YangInstanceIdentifier path) {
111 return YangInstanceIdentifier.EMPTY;
114 CarsModel.BASE_QNAME.getLocalName(), new ShardStrategy() {
116 public String findShard(final YangInstanceIdentifier path) {
117 return CarsModel.BASE_QNAME.getLocalName();
121 public YangInstanceIdentifier getPrefixForPath(final YangInstanceIdentifier path) {
122 return YangInstanceIdentifier.EMPTY;
127 public ShardStrategy getStrategyForModule(final String moduleName) {
128 return strategyMap.get(moduleName);
132 public String getModuleNameFromNameSpace(final String nameSpace) {
133 if (TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
134 return TestModel.JUNK_QNAME.getLocalName();
135 } else if (CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
136 return CarsModel.BASE_QNAME.getLocalName();
143 protected ActorContext mockActorContext;
145 protected TransactionContextFactory mockComponentFactory;
147 private SchemaContext schemaContext;
150 private ClusterWrapper mockClusterWrapper;
152 protected final String memberName = "mock-member";
154 private final int operationTimeoutInSeconds = 2;
155 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
156 .operationTimeoutInSeconds(operationTimeoutInSeconds);
159 public static void setUpClass() throws IOException {
161 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
162 .put("akka.actor.default-dispatcher.type",
163 "akka.testkit.CallingThreadDispatcherConfigurator").build())
164 .withFallback(ConfigFactory.load());
165 system = ActorSystem.create("test", config);
169 public static void tearDownClass() throws IOException {
170 TestKit.shutdownActorSystem(system);
175 public void setUp() {
176 MockitoAnnotations.initMocks(this);
178 schemaContext = TestModel.createTestContext();
180 doReturn(getSystem()).when(mockActorContext).getActorSystem();
181 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
182 doReturn(MemberName.forName(memberName)).when(mockActorContext).getCurrentMemberName();
183 doReturn(new ShardStrategyFactory(configuration,
184 LogicalDatastoreType.CONFIGURATION)).when(mockActorContext).getShardStrategyFactory();
185 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
186 doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
187 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
188 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
189 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
191 final ClientIdentifier mockClientId = MockIdentifiers.clientIdentifier(getClass(), memberName);
192 mockComponentFactory = new TransactionContextFactory(mockActorContext, mockClientId);
194 Timer timer = new MetricRegistry().timer("test");
195 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
198 protected ActorSystem getSystem() {
202 protected CreateTransaction eqCreateTransaction(final String expMemberName,
203 final TransactionType type) {
204 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
206 public boolean matches(final Object argument) {
207 if (CreateTransaction.class.equals(argument.getClass())) {
208 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
209 return obj.getTransactionId().getHistoryId().getClientId().getFrontendId().getMemberName()
210 .getName().equals(expMemberName) && obj.getTransactionType() == type.ordinal();
217 return argThat(matcher);
220 protected DataExists eqDataExists() {
221 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
223 public boolean matches(final Object argument) {
224 return argument instanceof DataExists && ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
228 return argThat(matcher);
231 protected ReadData eqReadData() {
232 return eqReadData(TestModel.TEST_PATH);
235 protected ReadData eqReadData(final YangInstanceIdentifier path) {
236 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
238 public boolean matches(final Object argument) {
239 return argument instanceof ReadData && ((ReadData)argument).getPath().equals(path);
243 return argThat(matcher);
246 protected Future<Object> readyTxReply(final String path) {
247 return Futures.successful((Object)new ReadyTransactionReply(path));
251 protected Future<ReadDataReply> readDataReply(final NormalizedNode<?, ?> data) {
252 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
255 protected Future<DataExistsReply> dataExistsReply(final boolean exists) {
256 return Futures.successful(new DataExistsReply(exists, DataStoreVersions.CURRENT_VERSION));
259 protected Future<BatchedModificationsReply> batchedModificationsReply(final int count) {
260 return Futures.successful(new BatchedModificationsReply(count));
263 @SuppressWarnings("unchecked")
264 protected Future<Object> incompleteFuture() {
265 return mock(Future.class);
268 protected ActorSelection actorSelection(final ActorRef actorRef) {
269 return getSystem().actorSelection(actorRef.path());
272 protected void expectBatchedModifications(final ActorRef actorRef, final int count) {
273 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
274 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
277 protected void expectBatchedModifications(final int count) {
278 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
279 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
282 protected void expectBatchedModificationsReady(final ActorRef actorRef) {
283 expectBatchedModificationsReady(actorRef, false);
286 protected void expectBatchedModificationsReady(final ActorRef actorRef, final boolean doCommitOnReady) {
287 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
288 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
289 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
292 protected void expectIncompleteBatchedModifications() {
293 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
294 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
297 protected void expectFailedBatchedModifications(final ActorRef actorRef) {
298 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
299 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
302 protected void expectReadyLocalTransaction(final ActorRef actorRef, final boolean doCommitOnReady) {
303 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
304 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
305 eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
308 protected CreateTransactionReply createTransactionReply(final ActorRef actorRef, final short transactionVersion) {
309 return new CreateTransactionReply(actorRef.path().toString(), nextTransactionId(), transactionVersion);
312 protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem) {
313 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
316 protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
317 final String shardName) {
318 return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
319 DataStoreVersions.CURRENT_VERSION);
322 protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
323 final String shardName, final short transactionVersion) {
324 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
325 log.info("Created mock shard actor {}", actorRef);
327 doReturn(actorSystem.actorSelection(actorRef.path()))
328 .when(mockActorContext).actorSelection(actorRef.path().toString());
330 doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion))
331 .when(mockActorContext).findPrimaryShardAsync(eq(shardName));
336 protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef) {
337 return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
340 protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef,
341 final short transactionVersion) {
342 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
343 transactionVersion));
346 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
347 final TransactionType type, final short transactionVersion, final String shardName) {
348 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
351 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
352 memberName, shardActorRef);
355 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
356 final TransactionType type, final short transactionVersion, final String prefix,
357 final ActorRef shardActorRef) {
360 if (type == TransactionType.WRITE_ONLY
361 && dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
362 txActorRef = shardActorRef;
364 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
365 log.info("Created mock shard Tx actor {}", txActorRef);
367 doReturn(actorSystem.actorSelection(txActorRef.path()))
368 .when(mockActorContext).actorSelection(txActorRef.path().toString());
370 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext)
371 .executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
372 eqCreateTransaction(prefix, type), any(Timeout.class));
378 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
379 final TransactionType type) {
380 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
381 DefaultShardStrategy.DEFAULT_SHARD);
384 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
385 final TransactionType type,
386 final String shardName) {
387 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
391 @SuppressWarnings({"checkstyle:avoidHidingCauseException", "checkstyle:IllegalThrows"})
392 protected void propagateReadFailedExceptionCause(final FluentFuture<?> future) throws Throwable {
394 future.get(5, TimeUnit.SECONDS);
395 fail("Expected ReadFailedException");
396 } catch (ExecutionException e) {
397 final Throwable cause = e.getCause();
398 assertTrue("Unexpected cause: " + cause.getClass(), cause instanceof ReadFailedException);
399 throw Throwables.getRootCause(cause);
403 protected List<BatchedModifications> captureBatchedModifications(final ActorRef actorRef) {
404 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
405 ArgumentCaptor.forClass(BatchedModifications.class);
406 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
407 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture(), any(Timeout.class));
409 List<BatchedModifications> batchedModifications = filterCaptured(
410 batchedModificationsCaptor, BatchedModifications.class);
411 return batchedModifications;
414 protected <T> List<T> filterCaptured(final ArgumentCaptor<T> captor, final Class<T> type) {
415 List<T> captured = new ArrayList<>();
416 for (T c: captor.getAllValues()) {
417 if (type.isInstance(c)) {
425 protected void verifyOneBatchedModification(final ActorRef actorRef, final Modification expected,
426 final boolean expIsReady) {
427 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
428 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
430 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
433 protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
434 final Modification... expected) {
435 verifyBatchedModifications(message, expIsReady, false, expected);
438 protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
439 final boolean expIsDoCommitOnReady, final Modification... expected) {
440 assertEquals("Message type", BatchedModifications.class, message.getClass());
441 BatchedModifications batchedModifications = (BatchedModifications)message;
442 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
443 assertEquals("isReady", expIsReady, batchedModifications.isReady());
444 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
445 for (int i = 0; i < batchedModifications.getModifications().size(); i++) {
446 Modification actual = batchedModifications.getModifications().get(i);
447 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
448 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
449 ((AbstractModification)actual).getPath());
450 if (actual instanceof WriteModification) {
451 assertEquals("getData", ((WriteModification)expected[i]).getData(),
452 ((WriteModification)actual).getData());
457 @SuppressWarnings("checkstyle:IllegalCatch")
458 protected void verifyCohortFutures(final AbstractThreePhaseCommitCohort<?> proxy,
459 final Object... expReplies) {
460 assertEquals("getReadyOperationFutures size", expReplies.length,
461 proxy.getCohortFutures().size());
463 List<Object> futureResults = new ArrayList<>();
464 for (Future<?> future : proxy.getCohortFutures()) {
465 assertNotNull("Ready operation Future is null", future);
467 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
468 } catch (Exception e) {
469 futureResults.add(e);
473 for (Object expReply : expReplies) {
474 boolean found = false;
475 Iterator<?> iter = futureResults.iterator();
476 while (iter.hasNext()) {
477 Object actual = iter.next();
478 if (CommitTransactionReply.isSerializedType(expReply)
479 && CommitTransactionReply.isSerializedType(actual)) {
481 } else if (expReply instanceof ActorSelection && Objects.equals(expReply, actual)) {
483 } else if (expReply instanceof Class && ((Class<?>) expReply).isInstance(actual)) {
494 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));