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.cluster.datastore.utils.ShardInfoListener;
70 import org.opendaylight.controller.cluster.datastore.utils.ShardInfoListenerRegistration;
71 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
72 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
73 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
74 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
75 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
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() {
96 public Map<String, ShardStrategy> getModuleNameToShardStrategyMap() {
97 return ImmutableMap.<String, ShardStrategy>builder().put(
98 "junk", new ShardStrategy() {
100 public String findShard(YangInstanceIdentifier path) {
107 public Optional<String> getModuleNameFromNameSpace(String nameSpace) {
108 return TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace) ?
109 Optional.of("junk") : Optional.<String>absent();
114 protected ActorContext mockActorContext;
116 protected TransactionContextFactory mockComponentFactory;
118 private SchemaContext schemaContext;
121 private ClusterWrapper mockClusterWrapper;
123 protected final String memberName = "mock-member";
125 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
128 public static void setUpClass() throws IOException {
130 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
131 put("akka.actor.default-dispatcher.type",
132 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
133 withFallback(ConfigFactory.load());
134 system = ActorSystem.create("test", config);
138 public static void tearDownClass() throws IOException {
139 JavaTestKit.shutdownActorSystem(system);
145 MockitoAnnotations.initMocks(this);
147 schemaContext = TestModel.createTestContext();
149 doReturn(getSystem()).when(mockActorContext).getActorSystem();
150 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
151 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
152 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
153 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
154 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
155 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
156 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
157 doReturn(mock(ShardInfoListenerRegistration.class)).when(mockActorContext).registerShardInfoListener(
158 any(ShardInfoListener.class));
160 mockComponentFactory = TransactionContextFactory.create(mockActorContext);
162 Timer timer = new MetricRegistry().timer("test");
163 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
165 ShardStrategyFactory.setConfiguration(configuration);
168 protected ActorSystem getSystem() {
172 protected CreateTransaction eqCreateTransaction(final String memberName,
173 final TransactionType type) {
174 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
176 public boolean matches(Object argument) {
177 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
178 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
179 return obj.getTransactionId().startsWith(memberName) &&
180 obj.getTransactionType() == type.ordinal();
187 return argThat(matcher);
190 protected DataExists eqSerializedDataExists() {
191 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
193 public boolean matches(Object argument) {
194 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
195 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
199 return argThat(matcher);
202 protected DataExists eqDataExists() {
203 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
205 public boolean matches(Object argument) {
206 return (argument instanceof DataExists) &&
207 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
211 return argThat(matcher);
214 protected ReadData eqSerializedReadData() {
215 return eqSerializedReadData(TestModel.TEST_PATH);
218 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
219 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
221 public boolean matches(Object argument) {
222 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
223 ReadData.fromSerializable(argument).getPath().equals(path);
227 return argThat(matcher);
230 protected ReadData eqReadData() {
231 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
233 public boolean matches(Object argument) {
234 return (argument instanceof ReadData) &&
235 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
239 return argThat(matcher);
242 protected Future<Object> readyTxReply(String path) {
243 return Futures.successful((Object)new ReadyTransactionReply(path));
246 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
247 short transactionVersion) {
248 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
251 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
252 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
255 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
256 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
259 protected Future<Object> dataExistsSerializedReply(boolean exists) {
260 return Futures.successful(DataExistsReply.create(exists).toSerializable());
263 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
264 return Futures.successful(DataExistsReply.create(exists));
267 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
268 return Futures.successful(new BatchedModificationsReply(count));
271 @SuppressWarnings("unchecked")
272 protected Future<Object> incompleteFuture() {
273 return mock(Future.class);
276 protected ActorSelection actorSelection(ActorRef actorRef) {
277 return getSystem().actorSelection(actorRef.path());
280 protected void expectBatchedModifications(ActorRef actorRef, int count) {
281 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
282 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
285 protected void expectBatchedModificationsReady(ActorRef actorRef) {
286 expectBatchedModificationsReady(actorRef, false);
289 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
290 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
291 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
292 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
295 protected void expectBatchedModifications(int count) {
296 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
297 any(ActorSelection.class), isA(BatchedModifications.class));
300 protected void expectIncompleteBatchedModifications() {
301 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
302 any(ActorSelection.class), isA(BatchedModifications.class));
305 protected void expectFailedBatchedModifications(ActorRef actorRef) {
306 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
307 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
310 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
311 return CreateTransactionReply.newBuilder()
312 .setTransactionActorPath(actorRef.path().toString())
313 .setTransactionId("txn-1")
314 .setMessageVersion(transactionVersion)
318 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
319 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
322 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
323 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
324 Optional.<DataTree>absent()));
327 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
328 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
329 log.info("Created mock shard actor {}", actorRef);
331 doReturn(actorSystem.actorSelection(actorRef.path())).
332 when(mockActorContext).actorSelection(actorRef.path().toString());
334 doReturn(primaryShardInfoReply(actorSystem, actorRef)).
335 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
337 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
339 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
344 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
345 TransactionType type, int transactionVersion, String shardName) {
346 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName);
348 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
349 memberName, shardActorRef);
352 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
353 TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
356 if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
357 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
358 txActorRef = shardActorRef;
360 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
361 log.info("Created mock shard Tx actor {}", txActorRef);
363 doReturn(actorSystem.actorSelection(txActorRef.path())).
364 when(mockActorContext).actorSelection(txActorRef.path().toString());
366 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
367 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
368 eqCreateTransaction(prefix, type));
374 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
375 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
376 DefaultShardStrategy.DEFAULT_SHARD);
379 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
381 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
385 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
389 future.checkedGet(5, TimeUnit.SECONDS);
390 fail("Expected ReadFailedException");
391 } catch(ReadFailedException e) {
396 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
397 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
398 ArgumentCaptor.forClass(BatchedModifications.class);
399 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
400 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
402 List<BatchedModifications> batchedModifications = filterCaptured(
403 batchedModificationsCaptor, BatchedModifications.class);
404 return batchedModifications;
407 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
408 List<T> captured = new ArrayList<>();
409 for(T c: captor.getAllValues()) {
410 if(type.isInstance(c)) {
418 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
419 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
420 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
422 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
425 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
426 verifyBatchedModifications(message, expIsReady, false, expected);
429 protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
430 Modification... expected) {
431 assertEquals("Message type", BatchedModifications.class, message.getClass());
432 BatchedModifications batchedModifications = (BatchedModifications)message;
433 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
434 assertEquals("isReady", expIsReady, batchedModifications.isReady());
435 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
436 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
437 Modification actual = batchedModifications.getModifications().get(i);
438 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
439 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
440 ((AbstractModification)actual).getPath());
441 if(actual instanceof WriteModification) {
442 assertEquals("getData", ((WriteModification)expected[i]).getData(),
443 ((WriteModification)actual).getData());
448 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
449 Object... expReplies) throws Exception {
450 assertEquals("getReadyOperationFutures size", expReplies.length,
451 proxy.getCohortFutures().size());
453 List<Object> futureResults = new ArrayList<>();
454 for( Future<?> future: proxy.getCohortFutures()) {
455 assertNotNull("Ready operation Future is null", future);
457 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
458 } catch(Exception e) {
459 futureResults.add(e);
463 for(int i = 0; i < expReplies.length; i++) {
464 Object expReply = expReplies[i];
465 boolean found = false;
466 Iterator<?> iter = futureResults.iterator();
467 while(iter.hasNext()) {
468 Object actual = iter.next();
469 if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
470 CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
472 } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
474 } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
485 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));