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.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.data.api.schema.tree.DataTree;
75 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78 import scala.concurrent.Await;
79 import scala.concurrent.Future;
80 import scala.concurrent.duration.Duration;
83 * Abstract base class for TransactionProxy unit tests.
85 * @author Thomas Pantelis
87 public abstract class AbstractTransactionProxyTest {
88 protected final Logger log = LoggerFactory.getLogger(getClass());
90 private static ActorSystem system;
92 private final Configuration configuration = new MockConfiguration() {
94 public Map<String, ShardStrategy> getModuleNameToShardStrategyMap() {
95 return ImmutableMap.<String, ShardStrategy>builder().put(
96 "junk", new ShardStrategy() {
98 public String findShard(YangInstanceIdentifier path) {
105 public Optional<String> getModuleNameFromNameSpace(String nameSpace) {
106 return TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace) ?
107 Optional.of("junk") : Optional.<String>absent();
112 protected ActorContext mockActorContext;
114 private SchemaContext schemaContext;
117 private ClusterWrapper mockClusterWrapper;
119 protected final String memberName = "mock-member";
121 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
124 public static void setUpClass() throws IOException {
126 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
127 put("akka.actor.default-dispatcher.type",
128 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
129 withFallback(ConfigFactory.load());
130 system = ActorSystem.create("test", config);
134 public static void tearDownClass() throws IOException {
135 JavaTestKit.shutdownActorSystem(system);
141 MockitoAnnotations.initMocks(this);
143 schemaContext = TestModel.createTestContext();
145 doReturn(getSystem()).when(mockActorContext).getActorSystem();
146 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
147 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
148 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
149 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
150 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
151 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
152 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
154 Timer timer = new MetricRegistry().timer("test");
155 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
157 ShardStrategyFactory.setConfiguration(configuration);
160 protected ActorSystem getSystem() {
164 protected CreateTransaction eqCreateTransaction(final String memberName,
165 final TransactionType type) {
166 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
168 public boolean matches(Object argument) {
169 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
170 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
171 return obj.getTransactionId().startsWith(memberName) &&
172 obj.getTransactionType() == type.ordinal();
179 return argThat(matcher);
182 protected DataExists eqSerializedDataExists() {
183 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
185 public boolean matches(Object argument) {
186 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
187 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
191 return argThat(matcher);
194 protected DataExists eqDataExists() {
195 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
197 public boolean matches(Object argument) {
198 return (argument instanceof DataExists) &&
199 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
203 return argThat(matcher);
206 protected ReadData eqSerializedReadData() {
207 return eqSerializedReadData(TestModel.TEST_PATH);
210 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
211 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
213 public boolean matches(Object argument) {
214 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
215 ReadData.fromSerializable(argument).getPath().equals(path);
219 return argThat(matcher);
222 protected ReadData eqReadData() {
223 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
225 public boolean matches(Object argument) {
226 return (argument instanceof ReadData) &&
227 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
231 return argThat(matcher);
234 protected Future<Object> readyTxReply(String path) {
235 return Futures.successful((Object)new ReadyTransactionReply(path));
238 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
239 short transactionVersion) {
240 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
243 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
244 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
247 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
248 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
251 protected Future<Object> dataExistsSerializedReply(boolean exists) {
252 return Futures.successful(DataExistsReply.create(exists).toSerializable());
255 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
256 return Futures.successful(DataExistsReply.create(exists));
259 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
260 return Futures.successful(new BatchedModificationsReply(count));
263 protected Future<Object> incompleteFuture() {
264 return mock(Future.class);
267 protected ActorSelection actorSelection(ActorRef actorRef) {
268 return getSystem().actorSelection(actorRef.path());
271 protected void expectBatchedModifications(ActorRef actorRef, int count) {
272 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
273 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
276 protected void expectBatchedModificationsReady(ActorRef actorRef) {
277 expectBatchedModificationsReady(actorRef, false);
280 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
281 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
282 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
283 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
286 protected void expectBatchedModifications(int count) {
287 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
288 any(ActorSelection.class), isA(BatchedModifications.class));
291 protected void expectIncompleteBatchedModifications() {
292 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
293 any(ActorSelection.class), isA(BatchedModifications.class));
296 protected void expectFailedBatchedModifications(ActorRef actorRef) {
297 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
298 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
301 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
302 return CreateTransactionReply.newBuilder()
303 .setTransactionActorPath(actorRef.path().toString())
304 .setTransactionId("txn-1")
305 .setMessageVersion(transactionVersion)
309 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
310 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
313 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
314 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
315 Optional.<DataTree>absent()));
318 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
319 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
320 log.info("Created mock shard actor {}", actorRef);
322 doReturn(actorSystem.actorSelection(actorRef.path())).
323 when(mockActorContext).actorSelection(actorRef.path().toString());
325 doReturn(primaryShardInfoReply(actorSystem, actorRef)).
326 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
328 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
330 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
335 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
336 TransactionType type, int transactionVersion, String shardName) {
337 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName);
339 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
340 memberName, shardActorRef);
343 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
344 TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
347 if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
348 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
349 txActorRef = shardActorRef;
351 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
352 log.info("Created mock shard Tx actor {}", txActorRef);
354 doReturn(actorSystem.actorSelection(txActorRef.path())).
355 when(mockActorContext).actorSelection(txActorRef.path().toString());
357 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
358 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
359 eqCreateTransaction(prefix, type));
365 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
366 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
367 DefaultShardStrategy.DEFAULT_SHARD);
370 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
372 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
376 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
380 future.checkedGet(5, TimeUnit.SECONDS);
381 fail("Expected ReadFailedException");
382 } catch(ReadFailedException e) {
387 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
388 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
389 ArgumentCaptor.forClass(BatchedModifications.class);
390 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
391 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
393 List<BatchedModifications> batchedModifications = filterCaptured(
394 batchedModificationsCaptor, BatchedModifications.class);
395 return batchedModifications;
398 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
399 List<T> captured = new ArrayList<>();
400 for(T c: captor.getAllValues()) {
401 if(type.isInstance(c)) {
409 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
410 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
411 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
413 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
416 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
417 verifyBatchedModifications(message, expIsReady, false, expected);
420 protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
421 Modification... expected) {
422 assertEquals("Message type", BatchedModifications.class, message.getClass());
423 BatchedModifications batchedModifications = (BatchedModifications)message;
424 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
425 assertEquals("isReady", expIsReady, batchedModifications.isReady());
426 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
427 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
428 Modification actual = batchedModifications.getModifications().get(i);
429 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
430 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
431 ((AbstractModification)actual).getPath());
432 if(actual instanceof WriteModification) {
433 assertEquals("getData", ((WriteModification)expected[i]).getData(),
434 ((WriteModification)actual).getData());
439 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
440 Object... expReplies) throws Exception {
441 assertEquals("getReadyOperationFutures size", expReplies.length,
442 proxy.getCohortFutures().size());
444 List<Object> futureResults = new ArrayList<>();
445 for( Future<?> future: proxy.getCohortFutures()) {
446 assertNotNull("Ready operation Future is null", future);
448 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
449 } catch(Exception e) {
450 futureResults.add(e);
454 for(int i = 0; i < expReplies.length; i++) {
455 Object expReply = expReplies[i];
456 boolean found = false;
457 Iterator<?> iter = futureResults.iterator();
458 while(iter.hasNext()) {
459 Object actual = iter.next();
460 if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
461 CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
463 } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
465 } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
476 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));