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.fail;
13 import static org.mockito.Matchers.any;
14 import static org.mockito.Matchers.argThat;
15 import static org.mockito.Matchers.eq;
16 import static org.mockito.Matchers.isA;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.verify;
21 import akka.actor.ActorRef;
22 import akka.actor.ActorSelection;
23 import akka.actor.ActorSystem;
24 import akka.actor.Props;
25 import akka.dispatch.Futures;
26 import akka.testkit.JavaTestKit;
27 import akka.util.Timeout;
28 import com.codahale.metrics.MetricRegistry;
29 import com.codahale.metrics.Timer;
30 import com.google.common.base.Throwables;
31 import com.google.common.collect.ImmutableMap;
32 import com.google.common.util.concurrent.CheckedFuture;
33 import com.typesafe.config.Config;
34 import com.typesafe.config.ConfigFactory;
35 import java.io.IOException;
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.TimeUnit;
42 import org.junit.AfterClass;
43 import org.junit.Before;
44 import org.junit.BeforeClass;
45 import org.mockito.ArgumentCaptor;
46 import org.mockito.ArgumentMatcher;
47 import org.mockito.Mock;
48 import org.mockito.Mockito;
49 import org.mockito.MockitoAnnotations;
50 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
51 import org.opendaylight.controller.cluster.access.concepts.MemberName;
52 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
53 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
54 import org.opendaylight.controller.cluster.datastore.config.Configuration;
55 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
56 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
57 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
58 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
59 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
60 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
61 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
62 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
63 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
64 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
65 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
67 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
68 import org.opendaylight.controller.cluster.datastore.modification.Modification;
69 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
70 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
71 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
72 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
73 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
74 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
75 import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
76 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
77 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
78 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
80 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
81 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import scala.concurrent.Await;
85 import scala.concurrent.Future;
86 import scala.concurrent.duration.Duration;
89 * Abstract base class for TransactionProxy unit tests.
91 * @author Thomas Pantelis
93 public abstract class AbstractTransactionProxyTest extends AbstractTest {
94 protected final Logger log = LoggerFactory.getLogger(getClass());
96 private static ActorSystem system;
98 private final Configuration configuration = new MockConfiguration() {
99 Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
100 "junk", path -> "junk").put(
101 "cars", path -> "cars").build();
104 public ShardStrategy getStrategyForModule(String moduleName) {
105 return strategyMap.get(moduleName);
109 public String getModuleNameFromNameSpace(String nameSpace) {
110 if (TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
112 } else if (CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
120 protected ActorContext mockActorContext;
122 protected TransactionContextFactory mockComponentFactory;
124 private SchemaContext schemaContext;
127 private ClusterWrapper mockClusterWrapper;
129 protected final String memberName = "mock-member";
131 private final int operationTimeoutInSeconds = 2;
132 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
133 .operationTimeoutInSeconds(operationTimeoutInSeconds);
136 public static void setUpClass() throws IOException {
138 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
139 .put("akka.actor.default-dispatcher.type",
140 "akka.testkit.CallingThreadDispatcherConfigurator").build())
141 .withFallback(ConfigFactory.load());
142 system = ActorSystem.create("test", config);
146 public static void tearDownClass() throws IOException {
147 JavaTestKit.shutdownActorSystem(system);
152 public void setUp() {
153 MockitoAnnotations.initMocks(this);
155 schemaContext = TestModel.createTestContext();
157 doReturn(getSystem()).when(mockActorContext).getActorSystem();
158 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
159 doReturn(MemberName.forName(memberName)).when(mockActorContext).getCurrentMemberName();
160 doReturn(new ShardStrategyFactory(configuration)).when(mockActorContext).getShardStrategyFactory();
161 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
162 doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
163 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
164 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
165 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
167 final ClientIdentifier mockClientId = MockIdentifiers.clientIdentifier(getClass(), memberName);
168 mockComponentFactory = new TransactionContextFactory(mockActorContext, mockClientId);
170 Timer timer = new MetricRegistry().timer("test");
171 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
174 protected ActorSystem getSystem() {
178 protected CreateTransaction eqCreateTransaction(final String expMemberName,
179 final TransactionType type) {
180 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
182 public boolean matches(Object argument) {
183 if (CreateTransaction.class.equals(argument.getClass())) {
184 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
185 return obj.getTransactionId().getHistoryId().getClientId().getFrontendId().getMemberName()
186 .getName().equals(expMemberName) && obj.getTransactionType() == type.ordinal();
193 return argThat(matcher);
196 protected DataExists eqDataExists() {
197 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
199 public boolean matches(Object argument) {
200 return argument instanceof DataExists && ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
204 return argThat(matcher);
207 protected ReadData eqReadData() {
208 return eqReadData(TestModel.TEST_PATH);
211 protected ReadData eqReadData(final YangInstanceIdentifier path) {
212 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
214 public boolean matches(Object argument) {
215 return argument instanceof ReadData && ((ReadData)argument).getPath().equals(path);
219 return argThat(matcher);
222 protected Future<Object> readyTxReply(String path) {
223 return Futures.successful((Object)new ReadyTransactionReply(path));
227 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
228 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
231 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
232 return Futures.successful(new DataExistsReply(exists, DataStoreVersions.CURRENT_VERSION));
235 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
236 return Futures.successful(new BatchedModificationsReply(count));
239 @SuppressWarnings("unchecked")
240 protected Future<Object> incompleteFuture() {
241 return mock(Future.class);
244 protected ActorSelection actorSelection(ActorRef actorRef) {
245 return getSystem().actorSelection(actorRef.path());
248 protected void expectBatchedModifications(ActorRef actorRef, int count) {
249 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
250 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
253 protected void expectBatchedModifications(int count) {
254 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
255 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
258 protected void expectBatchedModificationsReady(ActorRef actorRef) {
259 expectBatchedModificationsReady(actorRef, false);
262 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
263 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
264 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
265 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
268 protected void expectIncompleteBatchedModifications() {
269 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
270 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
273 protected void expectFailedBatchedModifications(ActorRef actorRef) {
274 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
275 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
278 protected void expectReadyLocalTransaction(ActorRef actorRef, boolean doCommitOnReady) {
279 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
280 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
281 eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
284 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, short transactionVersion) {
285 return new CreateTransactionReply(actorRef.path().toString(), nextTransactionId(), transactionVersion);
288 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
289 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
292 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
293 return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
294 DataStoreVersions.CURRENT_VERSION);
297 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName,
298 short transactionVersion) {
299 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
300 log.info("Created mock shard actor {}", actorRef);
302 doReturn(actorSystem.actorSelection(actorRef.path()))
303 .when(mockActorContext).actorSelection(actorRef.path().toString());
305 doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion))
306 .when(mockActorContext).findPrimaryShardAsync(eq(shardName));
311 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
312 return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
315 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef,
316 short transactionVersion) {
317 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
318 transactionVersion));
321 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
322 TransactionType type, short transactionVersion, String shardName) {
323 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
326 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
327 memberName, shardActorRef);
330 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
331 TransactionType type, short transactionVersion, String prefix, ActorRef shardActorRef) {
334 if (type == TransactionType.WRITE_ONLY
335 && dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
336 txActorRef = shardActorRef;
338 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
339 log.info("Created mock shard Tx actor {}", txActorRef);
341 doReturn(actorSystem.actorSelection(txActorRef.path()))
342 .when(mockActorContext).actorSelection(txActorRef.path().toString());
344 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext)
345 .executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
346 eqCreateTransaction(prefix, type), any(Timeout.class));
352 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
353 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
354 DefaultShardStrategy.DEFAULT_SHARD);
357 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
359 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
363 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future) throws Exception {
365 future.checkedGet(5, TimeUnit.SECONDS);
366 fail("Expected ReadFailedException");
367 } catch (ReadFailedException e) {
368 assertNotNull("Expected a cause", e.getCause());
370 if (e.getCause().getCause() != null) {
371 cause = e.getCause().getCause();
373 cause = e.getCause();
376 Throwables.propagateIfInstanceOf(cause, Exception.class);
377 Throwables.propagate(cause);
381 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
382 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
383 ArgumentCaptor.forClass(BatchedModifications.class);
384 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
385 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture(), any(Timeout.class));
387 List<BatchedModifications> batchedModifications = filterCaptured(
388 batchedModificationsCaptor, BatchedModifications.class);
389 return batchedModifications;
392 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
393 List<T> captured = new ArrayList<>();
394 for (T c: captor.getAllValues()) {
395 if (type.isInstance(c)) {
403 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
404 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
405 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
407 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
410 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
411 verifyBatchedModifications(message, expIsReady, false, expected);
414 protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
415 Modification... expected) {
416 assertEquals("Message type", BatchedModifications.class, message.getClass());
417 BatchedModifications batchedModifications = (BatchedModifications)message;
418 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
419 assertEquals("isReady", expIsReady, batchedModifications.isReady());
420 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
421 for (int i = 0; i < batchedModifications.getModifications().size(); i++) {
422 Modification actual = batchedModifications.getModifications().get(i);
423 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
424 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
425 ((AbstractModification)actual).getPath());
426 if (actual instanceof WriteModification) {
427 assertEquals("getData", ((WriteModification)expected[i]).getData(),
428 ((WriteModification)actual).getData());
433 @SuppressWarnings("checkstyle:IllegalCatch")
434 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
435 Object... expReplies) throws Exception {
436 assertEquals("getReadyOperationFutures size", expReplies.length,
437 proxy.getCohortFutures().size());
439 List<Object> futureResults = new ArrayList<>();
440 for (Future<?> future : proxy.getCohortFutures()) {
441 assertNotNull("Ready operation Future is null", future);
443 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
444 } catch (Exception e) {
445 futureResults.add(e);
449 for (Object expReply : expReplies) {
450 boolean found = false;
451 Iterator<?> iter = futureResults.iterator();
452 while (iter.hasNext()) {
453 Object actual = iter.next();
454 if (CommitTransactionReply.isSerializedType(expReply)
455 && CommitTransactionReply.isSerializedType(actual)) {
457 } else if (expReply instanceof ActorSelection && Objects.equals(expReply, actual)) {
459 } else if (expReply instanceof Class && ((Class<?>) expReply).isInstance(actual)) {
470 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));