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 akka.util.Timeout;
27 import com.codahale.metrics.MetricRegistry;
28 import com.codahale.metrics.Timer;
29 import com.google.common.base.Objects;
30 import com.google.common.base.Optional;
31 import com.google.common.collect.ImmutableMap;
32 import com.google.common.util.concurrent.CheckedFuture;
33 import com.typesafe.config.Config;
34 import com.typesafe.config.ConfigFactory;
35 import java.io.IOException;
36 import java.util.ArrayList;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.concurrent.TimeUnit;
41 import org.junit.AfterClass;
42 import org.junit.Before;
43 import org.junit.BeforeClass;
44 import org.mockito.ArgumentCaptor;
45 import org.mockito.ArgumentMatcher;
46 import org.mockito.Mock;
47 import org.mockito.Mockito;
48 import org.mockito.MockitoAnnotations;
49 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
50 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
51 import org.opendaylight.controller.cluster.datastore.config.Configuration;
52 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
53 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
54 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
55 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
56 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
57 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
58 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
59 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
60 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
61 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
62 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
63 import org.opendaylight.controller.cluster.datastore.modification.Modification;
64 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
65 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
66 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
67 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
68 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
69 import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
70 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
71 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
72 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
73 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
74 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
75 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
76 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
78 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81 import scala.concurrent.Await;
82 import scala.concurrent.Future;
83 import scala.concurrent.duration.Duration;
86 * Abstract base class for TransactionProxy unit tests.
88 * @author Thomas Pantelis
90 public abstract class AbstractTransactionProxyTest {
91 protected final Logger log = LoggerFactory.getLogger(getClass());
93 private static ActorSystem system;
95 private final Configuration configuration = new MockConfiguration() {
96 Map<String, ShardStrategy> strategyMap = 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) {
111 public ShardStrategy getStrategyForModule(String moduleName) {
112 return strategyMap.get(moduleName);
116 public String getModuleNameFromNameSpace(String nameSpace) {
117 if(TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
119 } else if(CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)){
127 protected ActorContext mockActorContext;
129 protected TransactionContextFactory mockComponentFactory;
131 private SchemaContext schemaContext;
134 private ClusterWrapper mockClusterWrapper;
136 protected final String memberName = "mock-member";
138 private final int operationTimeoutInSeconds = 2;
139 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
140 .operationTimeoutInSeconds(operationTimeoutInSeconds);
143 public static void setUpClass() throws IOException {
145 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
146 put("akka.actor.default-dispatcher.type",
147 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
148 withFallback(ConfigFactory.load());
149 system = ActorSystem.create("test", config);
153 public static void tearDownClass() throws IOException {
154 JavaTestKit.shutdownActorSystem(system);
160 MockitoAnnotations.initMocks(this);
162 schemaContext = TestModel.createTestContext();
164 doReturn(getSystem()).when(mockActorContext).getActorSystem();
165 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
166 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
167 doReturn(new ShardStrategyFactory(configuration)).when(mockActorContext).getShardStrategyFactory();
168 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
169 doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
170 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
171 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
172 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
174 mockComponentFactory = TransactionContextFactory.create(mockActorContext);
176 Timer timer = new MetricRegistry().timer("test");
177 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
180 protected ActorSystem getSystem() {
184 protected CreateTransaction eqCreateTransaction(final String memberName,
185 final TransactionType type) {
186 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
188 public boolean matches(Object argument) {
189 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
190 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
191 return obj.getTransactionId().startsWith(memberName) &&
192 obj.getTransactionType() == type.ordinal();
199 return argThat(matcher);
202 protected DataExists eqSerializedDataExists() {
203 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
205 public boolean matches(Object argument) {
206 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
207 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
211 return argThat(matcher);
214 protected DataExists eqDataExists() {
215 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
217 public boolean matches(Object argument) {
218 return (argument instanceof DataExists) &&
219 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
223 return argThat(matcher);
226 protected ReadData eqSerializedReadData() {
227 return eqSerializedReadData(TestModel.TEST_PATH);
230 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
231 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
233 public boolean matches(Object argument) {
234 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
235 ReadData.fromSerializable(argument).getPath().equals(path);
239 return argThat(matcher);
242 protected ReadData eqReadData() {
243 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
245 public boolean matches(Object argument) {
246 return (argument instanceof ReadData) &&
247 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
251 return argThat(matcher);
254 protected Future<Object> readyTxReply(String path) {
255 return Futures.successful((Object)new ReadyTransactionReply(path));
258 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
259 short transactionVersion) {
260 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
263 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
264 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
267 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
268 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
271 protected Future<Object> dataExistsSerializedReply(boolean exists) {
272 return Futures.successful(DataExistsReply.create(exists).toSerializable());
275 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
276 return Futures.successful(DataExistsReply.create(exists));
279 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
280 return Futures.successful(new BatchedModificationsReply(count));
283 @SuppressWarnings("unchecked")
284 protected Future<Object> incompleteFuture() {
285 return mock(Future.class);
288 protected ActorSelection actorSelection(ActorRef actorRef) {
289 return getSystem().actorSelection(actorRef.path());
292 protected void expectBatchedModifications(ActorRef actorRef, int count) {
293 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
294 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
297 protected void expectBatchedModificationsReady(ActorRef actorRef) {
298 expectBatchedModificationsReady(actorRef, false);
301 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
302 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
303 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
304 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
307 protected void expectBatchedModifications(int count) {
308 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
309 any(ActorSelection.class), isA(BatchedModifications.class));
312 protected void expectIncompleteBatchedModifications() {
313 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
314 any(ActorSelection.class), isA(BatchedModifications.class));
317 protected void expectFailedBatchedModifications(ActorRef actorRef) {
318 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
319 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
322 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
323 return CreateTransactionReply.newBuilder()
324 .setTransactionActorPath(actorRef.path().toString())
325 .setTransactionId("txn-1")
326 .setMessageVersion(transactionVersion)
330 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
331 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
334 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
335 return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
338 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef,
339 short transactionVersion) {
340 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
341 transactionVersion, Optional.<DataTree>absent()));
344 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
345 return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName, DataStoreVersions.CURRENT_VERSION);
348 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName,
349 short transactionVersion) {
350 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
351 log.info("Created mock shard actor {}", actorRef);
353 doReturn(actorSystem.actorSelection(actorRef.path())).
354 when(mockActorContext).actorSelection(actorRef.path().toString());
356 doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion)).
357 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
359 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
364 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
365 TransactionType type, short transactionVersion, String shardName) {
366 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
369 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
370 memberName, shardActorRef);
373 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
374 TransactionType type, short transactionVersion, String prefix, ActorRef shardActorRef) {
377 if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
378 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
379 txActorRef = shardActorRef;
381 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
382 log.info("Created mock shard Tx actor {}", txActorRef);
384 doReturn(actorSystem.actorSelection(txActorRef.path())).
385 when(mockActorContext).actorSelection(txActorRef.path().toString());
387 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
388 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
389 eqCreateTransaction(prefix, type), any(Timeout.class));
395 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
396 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
397 DefaultShardStrategy.DEFAULT_SHARD);
400 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
402 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
406 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
410 future.checkedGet(5, TimeUnit.SECONDS);
411 fail("Expected ReadFailedException");
412 } catch(ReadFailedException e) {
413 assertNotNull("Expected a cause", e.getCause());
414 if(e.getCause().getCause() != null) {
415 throw e.getCause().getCause();
422 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
423 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
424 ArgumentCaptor.forClass(BatchedModifications.class);
425 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
426 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
428 List<BatchedModifications> batchedModifications = filterCaptured(
429 batchedModificationsCaptor, BatchedModifications.class);
430 return batchedModifications;
433 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
434 List<T> captured = new ArrayList<>();
435 for(T c: captor.getAllValues()) {
436 if(type.isInstance(c)) {
444 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
445 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
446 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
448 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
451 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
452 verifyBatchedModifications(message, expIsReady, false, expected);
455 protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
456 Modification... expected) {
457 assertEquals("Message type", BatchedModifications.class, message.getClass());
458 BatchedModifications batchedModifications = (BatchedModifications)message;
459 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
460 assertEquals("isReady", expIsReady, batchedModifications.isReady());
461 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
462 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
463 Modification actual = batchedModifications.getModifications().get(i);
464 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
465 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
466 ((AbstractModification)actual).getPath());
467 if(actual instanceof WriteModification) {
468 assertEquals("getData", ((WriteModification)expected[i]).getData(),
469 ((WriteModification)actual).getData());
474 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
475 Object... expReplies) throws Exception {
476 assertEquals("getReadyOperationFutures size", expReplies.length,
477 proxy.getCohortFutures().size());
479 List<Object> futureResults = new ArrayList<>();
480 for( Future<?> future: proxy.getCohortFutures()) {
481 assertNotNull("Ready operation Future is null", future);
483 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
484 } catch(Exception e) {
485 futureResults.add(e);
489 for(int i = 0; i < expReplies.length; i++) {
490 Object expReply = expReplies[i];
491 boolean found = false;
492 Iterator<?> iter = futureResults.iterator();
493 while(iter.hasNext()) {
494 Object actual = iter.next();
495 if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
496 CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
498 } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
500 } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
511 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));