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.ArgumentMatchers.any;
15 import static org.mockito.ArgumentMatchers.argThat;
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.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.FiniteDuration;
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;
99 private static SchemaContext SCHEMA_CONTEXT;
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;
148 private ClusterWrapper mockClusterWrapper;
150 protected final String memberName = "mock-member";
152 private final int operationTimeoutInSeconds = 2;
153 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
154 .operationTimeoutInSeconds(operationTimeoutInSeconds);
157 public static void setUpClass() {
159 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
160 .put("akka.actor.default-dispatcher.type",
161 "akka.testkit.CallingThreadDispatcherConfigurator").build())
162 .withFallback(ConfigFactory.load());
163 system = ActorSystem.create("test", config);
164 SCHEMA_CONTEXT = TestModel.createTestContext();
168 public static void tearDownClass() {
169 TestKit.shutdownActorSystem(system);
171 SCHEMA_CONTEXT = null;
175 public void setUp() {
176 MockitoAnnotations.initMocks(this);
178 doReturn(getSystem()).when(mockActorContext).getActorSystem();
179 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
180 doReturn(MemberName.forName(memberName)).when(mockActorContext).getCurrentMemberName();
181 doReturn(new ShardStrategyFactory(configuration,
182 LogicalDatastoreType.CONFIGURATION)).when(mockActorContext).getShardStrategyFactory();
183 doReturn(SCHEMA_CONTEXT).when(mockActorContext).getSchemaContext();
184 doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
185 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
186 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
187 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
188 doReturn(new Timeout(5, TimeUnit.SECONDS)).when(mockActorContext).getTransactionCommitOperationTimeout();
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 class CreateTransactionArgumentMatcher implements ArgumentMatcher<CreateTransaction> {
205 public boolean matches(CreateTransaction argument) {
206 return argument.getTransactionId().getHistoryId().getClientId().getFrontendId().getMemberName()
207 .getName().equals(expMemberName) && argument.getTransactionType() == type.ordinal();
211 return argThat(new CreateTransactionArgumentMatcher());
214 protected DataExists eqDataExists() {
215 class DataExistsArgumentMatcher implements ArgumentMatcher<DataExists> {
217 public boolean matches(DataExists argument) {
218 return argument.getPath().equals(TestModel.TEST_PATH);
222 return argThat(new DataExistsArgumentMatcher());
225 protected ReadData eqReadData() {
226 return eqReadData(TestModel.TEST_PATH);
229 protected ReadData eqReadData(final YangInstanceIdentifier path) {
230 class ReadDataArgumentMatcher implements ArgumentMatcher<ReadData> {
232 public boolean matches(ReadData argument) {
233 return argument.getPath().equals(path);
237 return argThat(new ReadDataArgumentMatcher());
240 protected Future<Object> readyTxReply(final String path) {
241 return Futures.successful((Object)new ReadyTransactionReply(path));
245 protected Future<ReadDataReply> readDataReply(final NormalizedNode<?, ?> data) {
246 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
249 protected Future<DataExistsReply> dataExistsReply(final boolean exists) {
250 return Futures.successful(new DataExistsReply(exists, DataStoreVersions.CURRENT_VERSION));
253 protected Future<BatchedModificationsReply> batchedModificationsReply(final int count) {
254 return Futures.successful(new BatchedModificationsReply(count));
257 @SuppressWarnings("unchecked")
258 protected Future<Object> incompleteFuture() {
259 return mock(Future.class);
262 protected ActorSelection actorSelection(final ActorRef actorRef) {
263 return getSystem().actorSelection(actorRef.path());
266 protected void expectBatchedModifications(final ActorRef actorRef, final int count) {
267 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
268 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
271 protected void expectBatchedModifications(final int count) {
272 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
273 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
276 protected void expectBatchedModificationsReady(final ActorRef actorRef) {
277 expectBatchedModificationsReady(actorRef, false);
280 protected void expectBatchedModificationsReady(final ActorRef actorRef, final boolean doCommitOnReady) {
281 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
282 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
283 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
286 protected void expectIncompleteBatchedModifications() {
287 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
288 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
291 protected void expectFailedBatchedModifications(final ActorRef actorRef) {
292 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
293 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
296 protected void expectReadyLocalTransaction(final ActorRef actorRef, final boolean doCommitOnReady) {
297 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
298 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
299 eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
302 protected CreateTransactionReply createTransactionReply(final ActorRef actorRef, final short transactionVersion) {
303 return new CreateTransactionReply(actorRef.path().toString(), nextTransactionId(), transactionVersion);
306 protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem) {
307 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
310 protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
311 final String shardName) {
312 return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
313 DataStoreVersions.CURRENT_VERSION);
316 protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
317 final String shardName, final short transactionVersion) {
318 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
319 log.info("Created mock shard actor {}", actorRef);
321 doReturn(actorSystem.actorSelection(actorRef.path()))
322 .when(mockActorContext).actorSelection(actorRef.path().toString());
324 doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion))
325 .when(mockActorContext).findPrimaryShardAsync(eq(shardName));
330 protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef) {
331 return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
334 protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef,
335 final short transactionVersion) {
336 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
337 transactionVersion));
340 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
341 final TransactionType type, final short transactionVersion, final String shardName) {
342 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
345 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
346 memberName, shardActorRef);
349 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
350 final TransactionType type, final short transactionVersion, final String prefix,
351 final ActorRef shardActorRef) {
354 if (type == TransactionType.WRITE_ONLY
355 && dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
356 txActorRef = shardActorRef;
358 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
359 log.info("Created mock shard Tx actor {}", txActorRef);
361 doReturn(actorSystem.actorSelection(txActorRef.path()))
362 .when(mockActorContext).actorSelection(txActorRef.path().toString());
364 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext)
365 .executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
366 eqCreateTransaction(prefix, type), any(Timeout.class));
372 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
373 final TransactionType type) {
374 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
375 DefaultShardStrategy.DEFAULT_SHARD);
378 protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
379 final TransactionType type,
380 final String shardName) {
381 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
385 @SuppressWarnings({"checkstyle:avoidHidingCauseException", "checkstyle:IllegalThrows"})
386 protected void propagateReadFailedExceptionCause(final FluentFuture<?> future) throws Throwable {
388 future.get(5, TimeUnit.SECONDS);
389 fail("Expected ReadFailedException");
390 } catch (ExecutionException e) {
391 final Throwable cause = e.getCause();
392 assertTrue("Unexpected cause: " + cause.getClass(), cause instanceof ReadFailedException);
393 throw Throwables.getRootCause(cause);
397 protected List<BatchedModifications> captureBatchedModifications(final ActorRef actorRef) {
398 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
399 ArgumentCaptor.forClass(BatchedModifications.class);
400 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
401 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture(), any(Timeout.class));
403 List<BatchedModifications> batchedModifications = filterCaptured(
404 batchedModificationsCaptor, BatchedModifications.class);
405 return batchedModifications;
408 protected <T> List<T> filterCaptured(final ArgumentCaptor<T> captor, final Class<T> type) {
409 List<T> captured = new ArrayList<>();
410 for (T c: captor.getAllValues()) {
411 if (type.isInstance(c)) {
419 protected void verifyOneBatchedModification(final ActorRef actorRef, final Modification expected,
420 final boolean expIsReady) {
421 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
422 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
424 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
427 protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
428 final Modification... expected) {
429 verifyBatchedModifications(message, expIsReady, false, expected);
432 protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
433 final boolean expIsDoCommitOnReady, final Modification... expected) {
434 assertEquals("Message type", BatchedModifications.class, message.getClass());
435 BatchedModifications batchedModifications = (BatchedModifications)message;
436 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
437 assertEquals("isReady", expIsReady, batchedModifications.isReady());
438 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
439 for (int i = 0; i < batchedModifications.getModifications().size(); i++) {
440 Modification actual = batchedModifications.getModifications().get(i);
441 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
442 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
443 ((AbstractModification)actual).getPath());
444 if (actual instanceof WriteModification) {
445 assertEquals("getData", ((WriteModification)expected[i]).getData(),
446 ((WriteModification)actual).getData());
451 @SuppressWarnings("checkstyle:IllegalCatch")
452 protected void verifyCohortFutures(final AbstractThreePhaseCommitCohort<?> proxy,
453 final Object... expReplies) {
454 assertEquals("getReadyOperationFutures size", expReplies.length,
455 proxy.getCohortFutures().size());
457 List<Object> futureResults = new ArrayList<>();
458 for (Future<?> future : proxy.getCohortFutures()) {
459 assertNotNull("Ready operation Future is null", future);
461 futureResults.add(Await.result(future, FiniteDuration.create(5, TimeUnit.SECONDS)));
462 } catch (Exception e) {
463 futureResults.add(e);
467 for (Object expReply : expReplies) {
468 boolean found = false;
469 Iterator<?> iter = futureResults.iterator();
470 while (iter.hasNext()) {
471 Object actual = iter.next();
472 if (CommitTransactionReply.isSerializedType(expReply)
473 && CommitTransactionReply.isSerializedType(actual)) {
475 } else if (expReply instanceof ActorSelection && Objects.equals(expReply, actual)) {
477 } else if (expReply instanceof Class && ((Class<?>) expReply).isInstance(actual)) {
488 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));