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;
20 import akka.actor.ActorRef;
21 import akka.actor.ActorSelection;
22 import akka.actor.ActorSystem;
23 import akka.actor.Props;
24 import akka.dispatch.Futures;
25 import akka.testkit.JavaTestKit;
26 import akka.util.Timeout;
27 import com.codahale.metrics.MetricRegistry;
28 import com.codahale.metrics.Timer;
29 import com.google.common.collect.ImmutableMap;
30 import com.google.common.util.concurrent.CheckedFuture;
31 import com.typesafe.config.Config;
32 import com.typesafe.config.ConfigFactory;
33 import java.io.IOException;
34 import java.util.ArrayList;
35 import java.util.Iterator;
36 import java.util.List;
38 import java.util.Objects;
39 import java.util.concurrent.TimeUnit;
40 import org.junit.AfterClass;
41 import org.junit.Before;
42 import org.junit.BeforeClass;
43 import org.mockito.ArgumentCaptor;
44 import org.mockito.ArgumentMatcher;
45 import org.mockito.Mock;
46 import org.mockito.Mockito;
47 import org.mockito.MockitoAnnotations;
48 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
49 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
50 import org.opendaylight.controller.cluster.datastore.config.Configuration;
51 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
52 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
53 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
54 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
55 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
56 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
57 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
58 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
59 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
60 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
61 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
62 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
63 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
64 import org.opendaylight.controller.cluster.datastore.modification.Modification;
65 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
66 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
67 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
68 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
69 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
70 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
71 import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
72 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
73 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
74 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
75 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
76 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
77 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80 import scala.concurrent.Await;
81 import scala.concurrent.Future;
82 import scala.concurrent.duration.Duration;
85 * Abstract base class for TransactionProxy unit tests.
87 * @author Thomas Pantelis
89 public abstract class AbstractTransactionProxyTest {
90 protected final Logger log = LoggerFactory.getLogger(getClass());
92 private static ActorSystem system;
94 private final Configuration configuration = new MockConfiguration() {
95 Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
96 "junk", new ShardStrategy() {
98 public String findShard(YangInstanceIdentifier path) {
102 "cars", new ShardStrategy() {
104 public String findShard(YangInstanceIdentifier path) {
110 public ShardStrategy getStrategyForModule(String moduleName) {
111 return strategyMap.get(moduleName);
115 public String getModuleNameFromNameSpace(String nameSpace) {
116 if(TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
118 } else if(CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)){
126 protected ActorContext mockActorContext;
128 protected TransactionContextFactory mockComponentFactory;
130 private SchemaContext schemaContext;
133 private ClusterWrapper mockClusterWrapper;
135 protected final String memberName = "mock-member";
137 private final int operationTimeoutInSeconds = 2;
138 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
139 .operationTimeoutInSeconds(operationTimeoutInSeconds);
142 public static void setUpClass() throws IOException {
144 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
145 put("akka.actor.default-dispatcher.type",
146 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
147 withFallback(ConfigFactory.load());
148 system = ActorSystem.create("test", config);
152 public static void tearDownClass() throws IOException {
153 JavaTestKit.shutdownActorSystem(system);
159 MockitoAnnotations.initMocks(this);
161 schemaContext = TestModel.createTestContext();
163 doReturn(getSystem()).when(mockActorContext).getActorSystem();
164 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
165 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
166 doReturn(new ShardStrategyFactory(configuration)).when(mockActorContext).getShardStrategyFactory();
167 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
168 doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
169 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
170 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
171 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
173 mockComponentFactory = TransactionContextFactory.create(mockActorContext);
175 Timer timer = new MetricRegistry().timer("test");
176 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
179 protected ActorSystem getSystem() {
183 protected CreateTransaction eqCreateTransaction(final String memberName,
184 final TransactionType type) {
185 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
187 public boolean matches(Object argument) {
188 if(CreateTransaction.class.equals(argument.getClass())) {
189 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
190 return obj.getTransactionId().startsWith(memberName) &&
191 obj.getTransactionType() == type.ordinal();
198 return argThat(matcher);
201 protected DataExists eqDataExists() {
202 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
204 public boolean matches(Object argument) {
205 return (argument instanceof DataExists) &&
206 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
210 return argThat(matcher);
213 protected ReadData eqReadData() {
214 return eqReadData(TestModel.TEST_PATH);
217 protected ReadData eqReadData(final YangInstanceIdentifier path) {
218 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
220 public boolean matches(Object argument) {
221 return (argument instanceof ReadData) && ((ReadData)argument).getPath().equals(path);
225 return argThat(matcher);
228 protected Future<Object> readyTxReply(String path) {
229 return Futures.successful((Object)new ReadyTransactionReply(path));
233 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
234 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
237 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
238 return Futures.successful(new DataExistsReply(exists, DataStoreVersions.CURRENT_VERSION));
241 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
242 return Futures.successful(new BatchedModificationsReply(count));
245 @SuppressWarnings("unchecked")
246 protected Future<Object> incompleteFuture() {
247 return mock(Future.class);
250 protected ActorSelection actorSelection(ActorRef actorRef) {
251 return getSystem().actorSelection(actorRef.path());
254 protected void expectBatchedModifications(ActorRef actorRef, int count) {
255 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
256 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
259 protected void expectBatchedModificationsReady(ActorRef actorRef) {
260 expectBatchedModificationsReady(actorRef, false);
263 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
264 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
265 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
266 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
269 protected void expectBatchedModifications(int count) {
270 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
271 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
274 protected void expectIncompleteBatchedModifications() {
275 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
276 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
279 protected void expectFailedBatchedModifications(ActorRef actorRef) {
280 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
281 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
284 protected void expectReadyLocalTransaction(ActorRef actorRef, boolean doCommitOnReady) {
285 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
286 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
287 eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
290 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, short transactionVersion){
291 return new CreateTransactionReply(actorRef.path().toString(), "txn-1", transactionVersion);
294 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
295 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
298 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
299 return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
302 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef,
303 short transactionVersion) {
304 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
305 transactionVersion));
308 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
309 return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName, DataStoreVersions.CURRENT_VERSION);
312 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName,
313 short transactionVersion) {
314 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
315 log.info("Created mock shard actor {}", actorRef);
317 doReturn(actorSystem.actorSelection(actorRef.path())).
318 when(mockActorContext).actorSelection(actorRef.path().toString());
320 doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion)).
321 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
326 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
327 TransactionType type, short transactionVersion, String shardName) {
328 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
331 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
332 memberName, shardActorRef);
335 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
336 TransactionType type, short transactionVersion, String prefix, ActorRef shardActorRef) {
339 if(type == TransactionType.WRITE_ONLY &&
340 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
341 txActorRef = shardActorRef;
343 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
344 log.info("Created mock shard Tx actor {}", txActorRef);
346 doReturn(actorSystem.actorSelection(txActorRef.path())).
347 when(mockActorContext).actorSelection(txActorRef.path().toString());
349 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
350 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
351 eqCreateTransaction(prefix, type), any(Timeout.class));
357 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
358 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
359 DefaultShardStrategy.DEFAULT_SHARD);
362 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
364 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
368 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
372 future.checkedGet(5, TimeUnit.SECONDS);
373 fail("Expected ReadFailedException");
374 } catch(ReadFailedException e) {
375 assertNotNull("Expected a cause", e.getCause());
376 if(e.getCause().getCause() != null) {
377 throw e.getCause().getCause();
384 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
385 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
386 ArgumentCaptor.forClass(BatchedModifications.class);
387 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
388 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture(), any(Timeout.class));
390 List<BatchedModifications> batchedModifications = filterCaptured(
391 batchedModificationsCaptor, BatchedModifications.class);
392 return batchedModifications;
395 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
396 List<T> captured = new ArrayList<>();
397 for(T c: captor.getAllValues()) {
398 if(type.isInstance(c)) {
406 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
407 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
408 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
410 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
413 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
414 verifyBatchedModifications(message, expIsReady, false, expected);
417 protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
418 Modification... expected) {
419 assertEquals("Message type", BatchedModifications.class, message.getClass());
420 BatchedModifications batchedModifications = (BatchedModifications)message;
421 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
422 assertEquals("isReady", expIsReady, batchedModifications.isReady());
423 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
424 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
425 Modification actual = batchedModifications.getModifications().get(i);
426 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
427 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
428 ((AbstractModification)actual).getPath());
429 if(actual instanceof WriteModification) {
430 assertEquals("getData", ((WriteModification)expected[i]).getData(),
431 ((WriteModification)actual).getData());
436 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
437 Object... expReplies) throws Exception {
438 assertEquals("getReadyOperationFutures size", expReplies.length,
439 proxy.getCohortFutures().size());
441 List<Object> futureResults = new ArrayList<>();
442 for( Future<?> future: proxy.getCohortFutures()) {
443 assertNotNull("Ready operation Future is null", future);
445 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
446 } catch(Exception e) {
447 futureResults.add(e);
451 for (Object expReply : expReplies) {
452 boolean found = false;
453 Iterator<?> iter = futureResults.iterator();
454 while(iter.hasNext()) {
455 Object actual = iter.next();
456 if(CommitTransactionReply.isSerializedType(expReply) &&
457 CommitTransactionReply.isSerializedType(actual)) {
459 } else if(expReply instanceof ActorSelection && Objects.equals(expReply, actual)) {
461 } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
472 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));