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() {
97 public Map<String, ShardStrategy> getModuleNameToShardStrategyMap() {
98 return ImmutableMap.<String, ShardStrategy>builder().put(
99 "junk", new ShardStrategy() {
101 public String findShard(YangInstanceIdentifier path) {
105 "cars", new ShardStrategy() {
107 public String findShard(YangInstanceIdentifier path) {
114 public Optional<String> getModuleNameFromNameSpace(String nameSpace) {
115 if(TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
116 return Optional.of("junk");
117 } else if(CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)){
118 return Optional.of("cars");
120 return Optional.<String>absent();
125 protected ActorContext mockActorContext;
127 protected TransactionContextFactory mockComponentFactory;
129 private SchemaContext schemaContext;
132 private ClusterWrapper mockClusterWrapper;
134 protected final String memberName = "mock-member";
136 private final int operationTimeoutInSeconds = 2;
137 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
138 .operationTimeoutInSeconds(operationTimeoutInSeconds);
141 public static void setUpClass() throws IOException {
143 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
144 put("akka.actor.default-dispatcher.type",
145 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
146 withFallback(ConfigFactory.load());
147 system = ActorSystem.create("test", config);
151 public static void tearDownClass() throws IOException {
152 JavaTestKit.shutdownActorSystem(system);
158 MockitoAnnotations.initMocks(this);
160 schemaContext = TestModel.createTestContext();
162 doReturn(getSystem()).when(mockActorContext).getActorSystem();
163 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
164 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
165 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
166 doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
167 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
168 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
169 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
171 mockComponentFactory = TransactionContextFactory.create(mockActorContext);
173 Timer timer = new MetricRegistry().timer("test");
174 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
176 ShardStrategyFactory.setConfiguration(configuration);
179 protected ActorSystem getSystem() {
183 protected CreateTransaction eqCreateTransaction(final String memberName,
184 final TransactionType type) {
185 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
187 public boolean matches(Object argument) {
188 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
189 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
190 return obj.getTransactionId().startsWith(memberName) &&
191 obj.getTransactionType() == type.ordinal();
198 return argThat(matcher);
201 protected DataExists eqSerializedDataExists() {
202 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
204 public boolean matches(Object argument) {
205 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
206 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
210 return argThat(matcher);
213 protected DataExists eqDataExists() {
214 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
216 public boolean matches(Object argument) {
217 return (argument instanceof DataExists) &&
218 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
222 return argThat(matcher);
225 protected ReadData eqSerializedReadData() {
226 return eqSerializedReadData(TestModel.TEST_PATH);
229 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
230 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
232 public boolean matches(Object argument) {
233 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
234 ReadData.fromSerializable(argument).getPath().equals(path);
238 return argThat(matcher);
241 protected ReadData eqReadData() {
242 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
244 public boolean matches(Object argument) {
245 return (argument instanceof ReadData) &&
246 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
250 return argThat(matcher);
253 protected Future<Object> readyTxReply(String path) {
254 return Futures.successful((Object)new ReadyTransactionReply(path));
257 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
258 short transactionVersion) {
259 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
262 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
263 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
266 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
267 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
270 protected Future<Object> dataExistsSerializedReply(boolean exists) {
271 return Futures.successful(DataExistsReply.create(exists).toSerializable());
274 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
275 return Futures.successful(DataExistsReply.create(exists));
278 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
279 return Futures.successful(new BatchedModificationsReply(count));
282 @SuppressWarnings("unchecked")
283 protected Future<Object> incompleteFuture() {
284 return mock(Future.class);
287 protected ActorSelection actorSelection(ActorRef actorRef) {
288 return getSystem().actorSelection(actorRef.path());
291 protected void expectBatchedModifications(ActorRef actorRef, int count) {
292 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
293 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
296 protected void expectBatchedModificationsReady(ActorRef actorRef) {
297 expectBatchedModificationsReady(actorRef, false);
300 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
301 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
302 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
303 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
306 protected void expectBatchedModifications(int count) {
307 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
308 any(ActorSelection.class), isA(BatchedModifications.class));
311 protected void expectIncompleteBatchedModifications() {
312 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
313 any(ActorSelection.class), isA(BatchedModifications.class));
316 protected void expectFailedBatchedModifications(ActorRef actorRef) {
317 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
318 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
321 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
322 return CreateTransactionReply.newBuilder()
323 .setTransactionActorPath(actorRef.path().toString())
324 .setTransactionId("txn-1")
325 .setMessageVersion(transactionVersion)
329 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
330 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
333 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
334 return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
337 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef,
338 short transactionVersion) {
339 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
340 transactionVersion, Optional.<DataTree>absent()));
343 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
344 return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName, DataStoreVersions.CURRENT_VERSION);
347 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName,
348 short transactionVersion) {
349 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
350 log.info("Created mock shard actor {}", actorRef);
352 doReturn(actorSystem.actorSelection(actorRef.path())).
353 when(mockActorContext).actorSelection(actorRef.path().toString());
355 doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion)).
356 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
358 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
363 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
364 TransactionType type, short transactionVersion, String shardName) {
365 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
368 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
369 memberName, shardActorRef);
372 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
373 TransactionType type, short transactionVersion, String prefix, ActorRef shardActorRef) {
376 if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
377 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
378 txActorRef = shardActorRef;
380 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
381 log.info("Created mock shard Tx actor {}", txActorRef);
383 doReturn(actorSystem.actorSelection(txActorRef.path())).
384 when(mockActorContext).actorSelection(txActorRef.path().toString());
386 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
387 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
388 eqCreateTransaction(prefix, type), any(Timeout.class));
394 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
395 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
396 DefaultShardStrategy.DEFAULT_SHARD);
399 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
401 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
405 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
409 future.checkedGet(5, TimeUnit.SECONDS);
410 fail("Expected ReadFailedException");
411 } catch(ReadFailedException e) {
412 assertNotNull("Expected a cause", e.getCause());
413 if(e.getCause().getCause() != null) {
414 throw e.getCause().getCause();
421 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
422 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
423 ArgumentCaptor.forClass(BatchedModifications.class);
424 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
425 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
427 List<BatchedModifications> batchedModifications = filterCaptured(
428 batchedModificationsCaptor, BatchedModifications.class);
429 return batchedModifications;
432 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
433 List<T> captured = new ArrayList<>();
434 for(T c: captor.getAllValues()) {
435 if(type.isInstance(c)) {
443 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
444 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
445 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
447 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
450 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
451 verifyBatchedModifications(message, expIsReady, false, expected);
454 protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
455 Modification... expected) {
456 assertEquals("Message type", BatchedModifications.class, message.getClass());
457 BatchedModifications batchedModifications = (BatchedModifications)message;
458 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
459 assertEquals("isReady", expIsReady, batchedModifications.isReady());
460 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
461 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
462 Modification actual = batchedModifications.getModifications().get(i);
463 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
464 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
465 ((AbstractModification)actual).getPath());
466 if(actual instanceof WriteModification) {
467 assertEquals("getData", ((WriteModification)expected[i]).getData(),
468 ((WriteModification)actual).getData());
473 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
474 Object... expReplies) throws Exception {
475 assertEquals("getReadyOperationFutures size", expReplies.length,
476 proxy.getCohortFutures().size());
478 List<Object> futureResults = new ArrayList<>();
479 for( Future<?> future: proxy.getCohortFutures()) {
480 assertNotNull("Ready operation Future is null", future);
482 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
483 } catch(Exception e) {
484 futureResults.add(e);
488 for(int i = 0; i < expReplies.length; i++) {
489 Object expReply = expReplies[i];
490 boolean found = false;
491 Iterator<?> iter = futureResults.iterator();
492 while(iter.hasNext()) {
493 Object actual = iter.next();
494 if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
495 CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
497 } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
499 } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
510 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));