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 protected TransactionContextFactory mockComponentFactory;
116 private SchemaContext schemaContext;
119 private ClusterWrapper mockClusterWrapper;
121 protected final String memberName = "mock-member";
123 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
126 public static void setUpClass() throws IOException {
128 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
129 put("akka.actor.default-dispatcher.type",
130 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
131 withFallback(ConfigFactory.load());
132 system = ActorSystem.create("test", config);
136 public static void tearDownClass() throws IOException {
137 JavaTestKit.shutdownActorSystem(system);
143 MockitoAnnotations.initMocks(this);
145 schemaContext = TestModel.createTestContext();
147 doReturn(getSystem()).when(mockActorContext).getActorSystem();
148 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
149 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
150 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
151 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
152 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
153 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
154 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
156 mockComponentFactory = TransactionContextFactory.create(mockActorContext);
158 Timer timer = new MetricRegistry().timer("test");
159 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
161 ShardStrategyFactory.setConfiguration(configuration);
164 protected ActorSystem getSystem() {
168 protected CreateTransaction eqCreateTransaction(final String memberName,
169 final TransactionType type) {
170 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
172 public boolean matches(Object argument) {
173 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
174 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
175 return obj.getTransactionId().startsWith(memberName) &&
176 obj.getTransactionType() == type.ordinal();
183 return argThat(matcher);
186 protected DataExists eqSerializedDataExists() {
187 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
189 public boolean matches(Object argument) {
190 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
191 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
195 return argThat(matcher);
198 protected DataExists eqDataExists() {
199 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
201 public boolean matches(Object argument) {
202 return (argument instanceof DataExists) &&
203 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
207 return argThat(matcher);
210 protected ReadData eqSerializedReadData() {
211 return eqSerializedReadData(TestModel.TEST_PATH);
214 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
215 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
217 public boolean matches(Object argument) {
218 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
219 ReadData.fromSerializable(argument).getPath().equals(path);
223 return argThat(matcher);
226 protected ReadData eqReadData() {
227 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
229 public boolean matches(Object argument) {
230 return (argument instanceof ReadData) &&
231 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
235 return argThat(matcher);
238 protected Future<Object> readyTxReply(String path) {
239 return Futures.successful((Object)new ReadyTransactionReply(path));
242 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
243 short transactionVersion) {
244 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
247 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
248 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
251 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
252 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
255 protected Future<Object> dataExistsSerializedReply(boolean exists) {
256 return Futures.successful(DataExistsReply.create(exists).toSerializable());
259 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
260 return Futures.successful(DataExistsReply.create(exists));
263 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
264 return Futures.successful(new BatchedModificationsReply(count));
267 @SuppressWarnings("unchecked")
268 protected Future<Object> incompleteFuture() {
269 return mock(Future.class);
272 protected ActorSelection actorSelection(ActorRef actorRef) {
273 return getSystem().actorSelection(actorRef.path());
276 protected void expectBatchedModifications(ActorRef actorRef, int count) {
277 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
278 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
281 protected void expectBatchedModificationsReady(ActorRef actorRef) {
282 expectBatchedModificationsReady(actorRef, false);
285 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
286 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
287 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
288 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
291 protected void expectBatchedModifications(int count) {
292 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
293 any(ActorSelection.class), isA(BatchedModifications.class));
296 protected void expectIncompleteBatchedModifications() {
297 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
298 any(ActorSelection.class), isA(BatchedModifications.class));
301 protected void expectFailedBatchedModifications(ActorRef actorRef) {
302 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
303 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
306 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
307 return CreateTransactionReply.newBuilder()
308 .setTransactionActorPath(actorRef.path().toString())
309 .setTransactionId("txn-1")
310 .setMessageVersion(transactionVersion)
314 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
315 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
318 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
319 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
320 Optional.<DataTree>absent()));
323 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
324 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
325 log.info("Created mock shard actor {}", actorRef);
327 doReturn(actorSystem.actorSelection(actorRef.path())).
328 when(mockActorContext).actorSelection(actorRef.path().toString());
330 doReturn(primaryShardInfoReply(actorSystem, actorRef)).
331 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
333 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
335 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
340 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
341 TransactionType type, int transactionVersion, String shardName) {
342 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName);
344 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
345 memberName, shardActorRef);
348 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
349 TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
352 if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
353 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
354 txActorRef = shardActorRef;
356 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
357 log.info("Created mock shard Tx actor {}", txActorRef);
359 doReturn(actorSystem.actorSelection(txActorRef.path())).
360 when(mockActorContext).actorSelection(txActorRef.path().toString());
362 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
363 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
364 eqCreateTransaction(prefix, type));
370 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
371 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
372 DefaultShardStrategy.DEFAULT_SHARD);
375 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
377 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
381 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
385 future.checkedGet(5, TimeUnit.SECONDS);
386 fail("Expected ReadFailedException");
387 } catch(ReadFailedException e) {
392 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
393 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
394 ArgumentCaptor.forClass(BatchedModifications.class);
395 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
396 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
398 List<BatchedModifications> batchedModifications = filterCaptured(
399 batchedModificationsCaptor, BatchedModifications.class);
400 return batchedModifications;
403 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
404 List<T> captured = new ArrayList<>();
405 for(T c: captor.getAllValues()) {
406 if(type.isInstance(c)) {
414 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
415 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
416 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
418 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
421 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
422 verifyBatchedModifications(message, expIsReady, false, expected);
425 protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
426 Modification... expected) {
427 assertEquals("Message type", BatchedModifications.class, message.getClass());
428 BatchedModifications batchedModifications = (BatchedModifications)message;
429 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
430 assertEquals("isReady", expIsReady, batchedModifications.isReady());
431 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
432 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
433 Modification actual = batchedModifications.getModifications().get(i);
434 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
435 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
436 ((AbstractModification)actual).getPath());
437 if(actual instanceof WriteModification) {
438 assertEquals("getData", ((WriteModification)expected[i]).getData(),
439 ((WriteModification)actual).getData());
444 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
445 Object... expReplies) throws Exception {
446 assertEquals("getReadyOperationFutures size", expReplies.length,
447 proxy.getCohortFutures().size());
449 List<Object> futureResults = new ArrayList<>();
450 for( Future<?> future: proxy.getCohortFutures()) {
451 assertNotNull("Ready operation Future is null", future);
453 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
454 } catch(Exception e) {
455 futureResults.add(e);
459 for(int i = 0; i < expReplies.length; i++) {
460 Object expReply = expReplies[i];
461 boolean found = false;
462 Iterator<?> iter = futureResults.iterator();
463 while(iter.hasNext()) {
464 Object actual = iter.next();
465 if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
466 CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
468 } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
470 } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
481 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));