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 com.codahale.metrics.MetricRegistry;
27 import com.codahale.metrics.Timer;
28 import com.google.common.base.Objects;
29 import com.google.common.base.Optional;
30 import com.google.common.collect.ImmutableMap;
31 import com.google.common.util.concurrent.CheckedFuture;
32 import com.typesafe.config.Config;
33 import com.typesafe.config.ConfigFactory;
34 import java.io.IOException;
35 import java.util.ArrayList;
36 import java.util.Iterator;
37 import java.util.List;
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.messages.BatchedModifications;
51 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
52 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
53 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
54 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
55 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
56 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
57 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
58 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
59 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
60 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
61 import org.opendaylight.controller.cluster.datastore.modification.Modification;
62 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
63 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
64 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
65 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
66 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
67 import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
68 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
69 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
70 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
71 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
72 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
73 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
74 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79 import scala.concurrent.Await;
80 import scala.concurrent.Future;
81 import scala.concurrent.duration.Duration;
84 * Abstract base class for TransactionProxy unit tests.
86 * @author Thomas Pantelis
88 public abstract class AbstractTransactionProxyTest {
89 protected final Logger log = LoggerFactory.getLogger(getClass());
91 private static ActorSystem system;
93 private final Configuration configuration = new MockConfiguration() {
95 public Map<String, ShardStrategy> getModuleNameToShardStrategyMap() {
96 return ImmutableMap.<String, ShardStrategy>builder().put(
97 "junk", new ShardStrategy() {
99 public String findShard(YangInstanceIdentifier path) {
103 "cars", new ShardStrategy() {
105 public String findShard(YangInstanceIdentifier path) {
112 public Optional<String> getModuleNameFromNameSpace(String nameSpace) {
113 if(TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
114 return Optional.of("junk");
115 } else if(CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)){
116 return Optional.of("cars");
118 return Optional.<String>absent();
123 protected ActorContext mockActorContext;
125 protected TransactionContextFactory mockComponentFactory;
127 private SchemaContext schemaContext;
130 private ClusterWrapper mockClusterWrapper;
132 protected final String memberName = "mock-member";
134 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
137 public static void setUpClass() throws IOException {
139 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
140 put("akka.actor.default-dispatcher.type",
141 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
142 withFallback(ConfigFactory.load());
143 system = ActorSystem.create("test", config);
147 public static void tearDownClass() throws IOException {
148 JavaTestKit.shutdownActorSystem(system);
154 MockitoAnnotations.initMocks(this);
156 schemaContext = TestModel.createTestContext();
158 doReturn(getSystem()).when(mockActorContext).getActorSystem();
159 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
160 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
161 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
162 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
163 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
164 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
166 mockComponentFactory = TransactionContextFactory.create(mockActorContext);
168 Timer timer = new MetricRegistry().timer("test");
169 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
171 ShardStrategyFactory.setConfiguration(configuration);
174 protected ActorSystem getSystem() {
178 protected CreateTransaction eqCreateTransaction(final String memberName,
179 final TransactionType type) {
180 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
182 public boolean matches(Object argument) {
183 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
184 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
185 return obj.getTransactionId().startsWith(memberName) &&
186 obj.getTransactionType() == type.ordinal();
193 return argThat(matcher);
196 protected DataExists eqSerializedDataExists() {
197 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
199 public boolean matches(Object argument) {
200 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
201 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
205 return argThat(matcher);
208 protected DataExists eqDataExists() {
209 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
211 public boolean matches(Object argument) {
212 return (argument instanceof DataExists) &&
213 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
217 return argThat(matcher);
220 protected ReadData eqSerializedReadData() {
221 return eqSerializedReadData(TestModel.TEST_PATH);
224 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
225 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
227 public boolean matches(Object argument) {
228 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
229 ReadData.fromSerializable(argument).getPath().equals(path);
233 return argThat(matcher);
236 protected ReadData eqReadData() {
237 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
239 public boolean matches(Object argument) {
240 return (argument instanceof ReadData) &&
241 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
245 return argThat(matcher);
248 protected Future<Object> readyTxReply(String path) {
249 return Futures.successful((Object)new ReadyTransactionReply(path));
252 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
253 short transactionVersion) {
254 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
257 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
258 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
261 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
262 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
265 protected Future<Object> dataExistsSerializedReply(boolean exists) {
266 return Futures.successful(DataExistsReply.create(exists).toSerializable());
269 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
270 return Futures.successful(DataExistsReply.create(exists));
273 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
274 return Futures.successful(new BatchedModificationsReply(count));
277 @SuppressWarnings("unchecked")
278 protected Future<Object> incompleteFuture() {
279 return mock(Future.class);
282 protected ActorSelection actorSelection(ActorRef actorRef) {
283 return getSystem().actorSelection(actorRef.path());
286 protected void expectBatchedModifications(ActorRef actorRef, int count) {
287 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
288 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
291 protected void expectBatchedModificationsReady(ActorRef actorRef) {
292 expectBatchedModificationsReady(actorRef, false);
295 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
296 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
297 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
298 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
301 protected void expectBatchedModifications(int count) {
302 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
303 any(ActorSelection.class), isA(BatchedModifications.class));
306 protected void expectIncompleteBatchedModifications() {
307 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
308 any(ActorSelection.class), isA(BatchedModifications.class));
311 protected void expectFailedBatchedModifications(ActorRef actorRef) {
312 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
313 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
316 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
317 return CreateTransactionReply.newBuilder()
318 .setTransactionActorPath(actorRef.path().toString())
319 .setTransactionId("txn-1")
320 .setMessageVersion(transactionVersion)
324 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
325 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
328 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
329 return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
332 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef,
333 short transactionVersion) {
334 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
335 transactionVersion, Optional.<DataTree>absent()));
338 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
339 return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName, DataStoreVersions.CURRENT_VERSION);
342 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName,
343 short transactionVersion) {
344 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
345 log.info("Created mock shard actor {}", actorRef);
347 doReturn(actorSystem.actorSelection(actorRef.path())).
348 when(mockActorContext).actorSelection(actorRef.path().toString());
350 doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion)).
351 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
353 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
358 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
359 TransactionType type, short transactionVersion, String shardName) {
360 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
363 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
364 memberName, shardActorRef);
367 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
368 TransactionType type, short transactionVersion, String prefix, ActorRef shardActorRef) {
371 if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
372 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
373 txActorRef = shardActorRef;
375 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
376 log.info("Created mock shard Tx actor {}", txActorRef);
378 doReturn(actorSystem.actorSelection(txActorRef.path())).
379 when(mockActorContext).actorSelection(txActorRef.path().toString());
381 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
382 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
383 eqCreateTransaction(prefix, type));
389 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
390 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
391 DefaultShardStrategy.DEFAULT_SHARD);
394 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
396 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
400 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
404 future.checkedGet(5, TimeUnit.SECONDS);
405 fail("Expected ReadFailedException");
406 } catch(ReadFailedException e) {
411 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
412 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
413 ArgumentCaptor.forClass(BatchedModifications.class);
414 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
415 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
417 List<BatchedModifications> batchedModifications = filterCaptured(
418 batchedModificationsCaptor, BatchedModifications.class);
419 return batchedModifications;
422 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
423 List<T> captured = new ArrayList<>();
424 for(T c: captor.getAllValues()) {
425 if(type.isInstance(c)) {
433 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
434 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
435 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
437 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
440 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
441 verifyBatchedModifications(message, expIsReady, false, expected);
444 protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
445 Modification... expected) {
446 assertEquals("Message type", BatchedModifications.class, message.getClass());
447 BatchedModifications batchedModifications = (BatchedModifications)message;
448 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
449 assertEquals("isReady", expIsReady, batchedModifications.isReady());
450 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
451 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
452 Modification actual = batchedModifications.getModifications().get(i);
453 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
454 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
455 ((AbstractModification)actual).getPath());
456 if(actual instanceof WriteModification) {
457 assertEquals("getData", ((WriteModification)expected[i]).getData(),
458 ((WriteModification)actual).getData());
463 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
464 Object... expReplies) throws Exception {
465 assertEquals("getReadyOperationFutures size", expReplies.length,
466 proxy.getCohortFutures().size());
468 List<Object> futureResults = new ArrayList<>();
469 for( Future<?> future: proxy.getCohortFutures()) {
470 assertNotNull("Ready operation Future is null", future);
472 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
473 } catch(Exception e) {
474 futureResults.add(e);
478 for(int i = 0; i < expReplies.length; i++) {
479 Object expReply = expReplies[i];
480 boolean found = false;
481 Iterator<?> iter = futureResults.iterator();
482 while(iter.hasNext()) {
483 Object actual = iter.next();
484 if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
485 CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
487 } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
489 } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
500 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));