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.base.Objects;
30 import com.google.common.base.Optional;
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.concurrent.TimeUnit;
41 import org.junit.AfterClass;
42 import org.junit.Before;
43 import org.junit.BeforeClass;
44 import org.mockito.ArgumentCaptor;
45 import org.mockito.ArgumentMatcher;
46 import org.mockito.Mock;
47 import org.mockito.Mockito;
48 import org.mockito.MockitoAnnotations;
49 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
50 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
51 import org.opendaylight.controller.cluster.datastore.config.Configuration;
52 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
53 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
54 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
55 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
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.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
76 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
77 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
79 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
82 import scala.concurrent.Await;
83 import scala.concurrent.Future;
84 import scala.concurrent.duration.Duration;
87 * Abstract base class for TransactionProxy unit tests.
89 * @author Thomas Pantelis
91 public abstract class AbstractTransactionProxyTest {
92 protected final Logger log = LoggerFactory.getLogger(getClass());
94 private static ActorSystem system;
96 private final Configuration configuration = new MockConfiguration() {
97 Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
98 "junk", new ShardStrategy() {
100 public String findShard(YangInstanceIdentifier path) {
104 "cars", new ShardStrategy() {
106 public String findShard(YangInstanceIdentifier path) {
112 public ShardStrategy getStrategyForModule(String moduleName) {
113 return strategyMap.get(moduleName);
117 public String getModuleNameFromNameSpace(String nameSpace) {
118 if(TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
120 } else if(CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)){
128 protected ActorContext mockActorContext;
130 protected TransactionContextFactory mockComponentFactory;
132 private SchemaContext schemaContext;
135 private ClusterWrapper mockClusterWrapper;
137 protected final String memberName = "mock-member";
139 private final int operationTimeoutInSeconds = 2;
140 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
141 .operationTimeoutInSeconds(operationTimeoutInSeconds);
144 public static void setUpClass() throws IOException {
146 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
147 put("akka.actor.default-dispatcher.type",
148 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
149 withFallback(ConfigFactory.load());
150 system = ActorSystem.create("test", config);
154 public static void tearDownClass() throws IOException {
155 JavaTestKit.shutdownActorSystem(system);
161 MockitoAnnotations.initMocks(this);
163 schemaContext = TestModel.createTestContext();
165 doReturn(getSystem()).when(mockActorContext).getActorSystem();
166 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
167 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
168 doReturn(new ShardStrategyFactory(configuration)).when(mockActorContext).getShardStrategyFactory();
169 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
170 doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
171 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
172 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
173 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
175 mockComponentFactory = TransactionContextFactory.create(mockActorContext);
177 Timer timer = new MetricRegistry().timer("test");
178 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
181 protected ActorSystem getSystem() {
185 protected CreateTransaction eqCreateTransaction(final String memberName,
186 final TransactionType type) {
187 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
189 public boolean matches(Object argument) {
190 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
191 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
192 return obj.getTransactionId().startsWith(memberName) &&
193 obj.getTransactionType() == type.ordinal();
200 return argThat(matcher);
203 protected DataExists eqSerializedDataExists() {
204 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
206 public boolean matches(Object argument) {
207 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
208 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
212 return argThat(matcher);
215 protected DataExists eqDataExists() {
216 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
218 public boolean matches(Object argument) {
219 return (argument instanceof DataExists) &&
220 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
224 return argThat(matcher);
227 protected ReadData eqSerializedReadData() {
228 return eqSerializedReadData(TestModel.TEST_PATH);
231 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
232 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
234 public boolean matches(Object argument) {
235 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
236 ReadData.fromSerializable(argument).getPath().equals(path);
240 return argThat(matcher);
243 protected ReadData eqReadData() {
244 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
246 public boolean matches(Object argument) {
247 return (argument instanceof ReadData) &&
248 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
252 return argThat(matcher);
255 protected Future<Object> readyTxReply(String path) {
256 return Futures.successful((Object)new ReadyTransactionReply(path));
259 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
260 short transactionVersion) {
261 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
264 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
265 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
268 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
269 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
272 protected Future<Object> dataExistsSerializedReply(boolean exists) {
273 return Futures.successful(DataExistsReply.create(exists).toSerializable());
276 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
277 return Futures.successful(DataExistsReply.create(exists));
280 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
281 return Futures.successful(new BatchedModificationsReply(count));
284 @SuppressWarnings("unchecked")
285 protected Future<Object> incompleteFuture() {
286 return mock(Future.class);
289 protected ActorSelection actorSelection(ActorRef actorRef) {
290 return getSystem().actorSelection(actorRef.path());
293 protected void expectBatchedModifications(ActorRef actorRef, int count) {
294 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
295 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
298 protected void expectBatchedModificationsReady(ActorRef actorRef) {
299 expectBatchedModificationsReady(actorRef, false);
302 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
303 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
304 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
305 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
308 protected void expectBatchedModifications(int count) {
309 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
310 any(ActorSelection.class), isA(BatchedModifications.class));
313 protected void expectIncompleteBatchedModifications() {
314 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
315 any(ActorSelection.class), isA(BatchedModifications.class));
318 protected void expectFailedBatchedModifications(ActorRef actorRef) {
319 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
320 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
323 protected void expectReadyLocalTransaction(ActorRef actorRef, boolean doCommitOnReady) {
324 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
325 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
326 eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
329 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
330 return CreateTransactionReply.newBuilder()
331 .setTransactionActorPath(actorRef.path().toString())
332 .setTransactionId("txn-1")
333 .setMessageVersion(transactionVersion)
337 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
338 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
341 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
342 return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
345 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef,
346 short transactionVersion) {
347 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
348 transactionVersion, Optional.<DataTree>absent()));
351 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
352 return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName, DataStoreVersions.CURRENT_VERSION);
355 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName,
356 short transactionVersion) {
357 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
358 log.info("Created mock shard actor {}", actorRef);
360 doReturn(actorSystem.actorSelection(actorRef.path())).
361 when(mockActorContext).actorSelection(actorRef.path().toString());
363 doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion)).
364 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
366 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
371 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
372 TransactionType type, short transactionVersion, String shardName) {
373 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
376 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
377 memberName, shardActorRef);
380 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
381 TransactionType type, short transactionVersion, String prefix, ActorRef shardActorRef) {
384 if(type == TransactionType.WRITE_ONLY &&
385 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
386 txActorRef = shardActorRef;
388 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
389 log.info("Created mock shard Tx actor {}", txActorRef);
391 doReturn(actorSystem.actorSelection(txActorRef.path())).
392 when(mockActorContext).actorSelection(txActorRef.path().toString());
394 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
395 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
396 eqCreateTransaction(prefix, type), any(Timeout.class));
402 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
403 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
404 DefaultShardStrategy.DEFAULT_SHARD);
407 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
409 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
413 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
417 future.checkedGet(5, TimeUnit.SECONDS);
418 fail("Expected ReadFailedException");
419 } catch(ReadFailedException e) {
420 assertNotNull("Expected a cause", e.getCause());
421 if(e.getCause().getCause() != null) {
422 throw e.getCause().getCause();
429 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
430 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
431 ArgumentCaptor.forClass(BatchedModifications.class);
432 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
433 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
435 List<BatchedModifications> batchedModifications = filterCaptured(
436 batchedModificationsCaptor, BatchedModifications.class);
437 return batchedModifications;
440 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
441 List<T> captured = new ArrayList<>();
442 for(T c: captor.getAllValues()) {
443 if(type.isInstance(c)) {
451 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
452 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
453 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
455 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
458 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
459 verifyBatchedModifications(message, expIsReady, false, expected);
462 protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
463 Modification... expected) {
464 assertEquals("Message type", BatchedModifications.class, message.getClass());
465 BatchedModifications batchedModifications = (BatchedModifications)message;
466 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
467 assertEquals("isReady", expIsReady, batchedModifications.isReady());
468 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
469 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
470 Modification actual = batchedModifications.getModifications().get(i);
471 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
472 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
473 ((AbstractModification)actual).getPath());
474 if(actual instanceof WriteModification) {
475 assertEquals("getData", ((WriteModification)expected[i]).getData(),
476 ((WriteModification)actual).getData());
481 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
482 Object... expReplies) throws Exception {
483 assertEquals("getReadyOperationFutures size", expReplies.length,
484 proxy.getCohortFutures().size());
486 List<Object> futureResults = new ArrayList<>();
487 for( Future<?> future: proxy.getCohortFutures()) {
488 assertNotNull("Ready operation Future is null", future);
490 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
491 } catch(Exception e) {
492 futureResults.add(e);
496 for(int i = 0; i < expReplies.length; i++) {
497 Object expReply = expReplies[i];
498 boolean found = false;
499 Iterator<?> iter = futureResults.iterator();
500 while(iter.hasNext()) {
501 Object actual = iter.next();
502 if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
503 CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
505 } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
507 } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
518 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));