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.TransactionProxy.TransactionType;
50 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
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.DataExists;
56 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
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.TestModel;
70 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
71 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import scala.concurrent.Await;
78 import scala.concurrent.Future;
79 import scala.concurrent.duration.Duration;
82 * Abstract base class for TransactionProxy unit tests.
84 * @author Thomas Pantelis
86 public abstract class AbstractTransactionProxyTest {
87 protected final Logger log = LoggerFactory.getLogger(getClass());
89 private static ActorSystem system;
91 private final Configuration configuration = new MockConfiguration() {
93 public Map<String, ShardStrategy> getModuleNameToShardStrategyMap() {
94 return ImmutableMap.<String, ShardStrategy>builder().put(
95 "junk", new ShardStrategy() {
97 public String findShard(YangInstanceIdentifier path) {
104 public Optional<String> getModuleNameFromNameSpace(String nameSpace) {
105 return TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace) ?
106 Optional.of("junk") : Optional.<String>absent();
111 protected ActorContext mockActorContext;
113 private SchemaContext schemaContext;
116 private ClusterWrapper mockClusterWrapper;
118 protected final String memberName = "mock-member";
120 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
123 public static void setUpClass() throws IOException {
125 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
126 put("akka.actor.default-dispatcher.type",
127 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
128 withFallback(ConfigFactory.load());
129 system = ActorSystem.create("test", config);
133 public static void tearDownClass() throws IOException {
134 JavaTestKit.shutdownActorSystem(system);
140 MockitoAnnotations.initMocks(this);
142 schemaContext = TestModel.createTestContext();
144 doReturn(getSystem()).when(mockActorContext).getActorSystem();
145 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
146 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
147 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
148 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
149 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
150 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
151 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
153 Timer timer = new MetricRegistry().timer("test");
154 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
156 ShardStrategyFactory.setConfiguration(configuration);
159 protected ActorSystem getSystem() {
163 protected CreateTransaction eqCreateTransaction(final String memberName,
164 final TransactionType type) {
165 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
167 public boolean matches(Object argument) {
168 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
169 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
170 return obj.getTransactionId().startsWith(memberName) &&
171 obj.getTransactionType() == type.ordinal();
178 return argThat(matcher);
181 protected DataExists eqSerializedDataExists() {
182 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
184 public boolean matches(Object argument) {
185 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
186 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
190 return argThat(matcher);
193 protected DataExists eqDataExists() {
194 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
196 public boolean matches(Object argument) {
197 return (argument instanceof DataExists) &&
198 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
202 return argThat(matcher);
205 protected ReadData eqSerializedReadData() {
206 return eqSerializedReadData(TestModel.TEST_PATH);
209 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
210 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
212 public boolean matches(Object argument) {
213 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
214 ReadData.fromSerializable(argument).getPath().equals(path);
218 return argThat(matcher);
221 protected ReadData eqReadData() {
222 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
224 public boolean matches(Object argument) {
225 return (argument instanceof ReadData) &&
226 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
230 return argThat(matcher);
233 protected Future<Object> readyTxReply(String path) {
234 return Futures.successful((Object)new ReadyTransactionReply(path));
237 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
238 short transactionVersion) {
239 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
242 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
243 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
246 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
247 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
250 protected Future<Object> dataExistsSerializedReply(boolean exists) {
251 return Futures.successful(DataExistsReply.create(exists).toSerializable());
254 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
255 return Futures.successful(DataExistsReply.create(exists));
258 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
259 return Futures.successful(new BatchedModificationsReply(count));
262 protected Future<Object> incompleteFuture() {
263 return mock(Future.class);
266 protected ActorSelection actorSelection(ActorRef actorRef) {
267 return getSystem().actorSelection(actorRef.path());
270 protected void expectBatchedModifications(ActorRef actorRef, int count) {
271 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
272 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
275 protected void expectBatchedModificationsReady(ActorRef actorRef) {
276 expectBatchedModificationsReady(actorRef, false);
279 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
280 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
281 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
282 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
285 protected void expectBatchedModifications(int count) {
286 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
287 any(ActorSelection.class), isA(BatchedModifications.class));
290 protected void expectIncompleteBatchedModifications() {
291 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
292 any(ActorSelection.class), isA(BatchedModifications.class));
295 protected void expectFailedBatchedModifications(ActorRef actorRef) {
296 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
297 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
300 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
301 return CreateTransactionReply.newBuilder()
302 .setTransactionActorPath(actorRef.path().toString())
303 .setTransactionId("txn-1")
304 .setMessageVersion(transactionVersion)
308 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
309 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
312 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
313 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
314 log.info("Created mock shard actor {}", actorRef);
316 doReturn(actorSystem.actorSelection(actorRef.path())).
317 when(mockActorContext).actorSelection(actorRef.path().toString());
319 doReturn(Futures.successful(actorSystem.actorSelection(actorRef.path()))).
320 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
322 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
324 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
329 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
330 TransactionType type, int transactionVersion, String shardName) {
331 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName);
333 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
334 memberName, shardActorRef);
337 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
338 TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
341 if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
342 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
343 txActorRef = shardActorRef;
345 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
346 log.info("Created mock shard Tx actor {}", txActorRef);
348 doReturn(actorSystem.actorSelection(txActorRef.path())).
349 when(mockActorContext).actorSelection(txActorRef.path().toString());
351 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
352 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
353 eqCreateTransaction(prefix, type));
359 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
360 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
361 DefaultShardStrategy.DEFAULT_SHARD);
364 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
366 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
370 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
374 future.checkedGet(5, TimeUnit.SECONDS);
375 fail("Expected ReadFailedException");
376 } catch(ReadFailedException e) {
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());
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 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
434 Object... expReplies) throws Exception {
435 assertEquals("getReadyOperationFutures size", expReplies.length,
436 proxy.getCohortFutures().size());
438 List<Object> futureResults = new ArrayList<>();
439 for( Future<?> future: proxy.getCohortFutures()) {
440 assertNotNull("Ready operation Future is null", future);
442 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
443 } catch(Exception e) {
444 futureResults.add(e);
448 for(int i = 0; i < expReplies.length; i++) {
449 Object expReply = expReplies[i];
450 boolean found = false;
451 Iterator<?> iter = futureResults.iterator();
452 while(iter.hasNext()) {
453 Object actual = iter.next();
454 if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
455 CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
457 } else if(expReply instanceof ActorSelection && Objects.equal(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));