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.TransactionProxy.TransactionType;
50 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
51 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
52 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
53 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
54 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
55 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
56 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
57 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
58 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
59 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
60 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
61 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
62 import org.opendaylight.controller.cluster.datastore.modification.Modification;
63 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
64 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
65 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
66 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
67 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
68 import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
69 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
70 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
71 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
72 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
73 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
74 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79 import scala.concurrent.Await;
80 import scala.concurrent.Future;
81 import scala.concurrent.duration.Duration;
84 * Abstract base class for TransactionProxy unit tests.
86 * @author Thomas Pantelis
88 public abstract class AbstractTransactionProxyTest {
89 protected final Logger log = LoggerFactory.getLogger(getClass());
91 private static ActorSystem system;
93 private final Configuration configuration = new MockConfiguration() {
95 public Map<String, ShardStrategy> getModuleNameToShardStrategyMap() {
96 return ImmutableMap.<String, ShardStrategy>builder().put(
97 "junk", new ShardStrategy() {
99 public String findShard(YangInstanceIdentifier path) {
106 public Optional<String> getModuleNameFromNameSpace(String nameSpace) {
107 return TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace) ?
108 Optional.of("junk") : Optional.<String>absent();
113 protected ActorContext mockActorContext;
115 private SchemaContext schemaContext;
118 private ClusterWrapper mockClusterWrapper;
120 protected final String memberName = "mock-member";
122 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
125 public static void setUpClass() throws IOException {
127 Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
128 put("akka.actor.default-dispatcher.type",
129 "akka.testkit.CallingThreadDispatcherConfigurator").build()).
130 withFallback(ConfigFactory.load());
131 system = ActorSystem.create("test", config);
135 public static void tearDownClass() throws IOException {
136 JavaTestKit.shutdownActorSystem(system);
142 MockitoAnnotations.initMocks(this);
144 schemaContext = TestModel.createTestContext();
146 doReturn(getSystem()).when(mockActorContext).getActorSystem();
147 doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
148 doReturn(memberName).when(mockActorContext).getCurrentMemberName();
149 doReturn(schemaContext).when(mockActorContext).getSchemaContext();
150 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
151 doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
152 doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
153 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
155 Timer timer = new MetricRegistry().timer("test");
156 doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
158 ShardStrategyFactory.setConfiguration(configuration);
161 protected ActorSystem getSystem() {
165 protected CreateTransaction eqCreateTransaction(final String memberName,
166 final TransactionType type) {
167 ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
169 public boolean matches(Object argument) {
170 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
171 CreateTransaction obj = CreateTransaction.fromSerializable(argument);
172 return obj.getTransactionId().startsWith(memberName) &&
173 obj.getTransactionType() == type.ordinal();
180 return argThat(matcher);
183 protected DataExists eqSerializedDataExists() {
184 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
186 public boolean matches(Object argument) {
187 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
188 DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
192 return argThat(matcher);
195 protected DataExists eqDataExists() {
196 ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
198 public boolean matches(Object argument) {
199 return (argument instanceof DataExists) &&
200 ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
204 return argThat(matcher);
207 protected ReadData eqSerializedReadData() {
208 return eqSerializedReadData(TestModel.TEST_PATH);
211 protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
212 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
214 public boolean matches(Object argument) {
215 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
216 ReadData.fromSerializable(argument).getPath().equals(path);
220 return argThat(matcher);
223 protected ReadData eqReadData() {
224 ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
226 public boolean matches(Object argument) {
227 return (argument instanceof ReadData) &&
228 ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
232 return argThat(matcher);
235 protected Future<Object> readyTxReply(String path) {
236 return Futures.successful((Object)new ReadyTransactionReply(path));
239 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
240 short transactionVersion) {
241 return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
244 protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
245 return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
248 protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
249 return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
252 protected Future<Object> dataExistsSerializedReply(boolean exists) {
253 return Futures.successful(DataExistsReply.create(exists).toSerializable());
256 protected Future<DataExistsReply> dataExistsReply(boolean exists) {
257 return Futures.successful(DataExistsReply.create(exists));
260 protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
261 return Futures.successful(new BatchedModificationsReply(count));
264 protected Future<Object> incompleteFuture() {
265 return mock(Future.class);
268 protected ActorSelection actorSelection(ActorRef actorRef) {
269 return getSystem().actorSelection(actorRef.path());
272 protected void expectBatchedModifications(ActorRef actorRef, int count) {
273 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
274 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
277 protected void expectBatchedModificationsReady(ActorRef actorRef) {
278 expectBatchedModificationsReady(actorRef, false);
281 protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
282 doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
283 readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
284 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
287 protected void expectBatchedModifications(int count) {
288 doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
289 any(ActorSelection.class), isA(BatchedModifications.class));
292 protected void expectIncompleteBatchedModifications() {
293 doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
294 any(ActorSelection.class), isA(BatchedModifications.class));
297 protected void expectFailedBatchedModifications(ActorRef actorRef) {
298 doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
299 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
302 protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
303 return CreateTransactionReply.newBuilder()
304 .setTransactionActorPath(actorRef.path().toString())
305 .setTransactionId("txn-1")
306 .setMessageVersion(transactionVersion)
310 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
311 return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
314 protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
315 return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
316 Optional.<DataTree>absent()));
319 protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
320 ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
321 log.info("Created mock shard actor {}", actorRef);
323 doReturn(actorSystem.actorSelection(actorRef.path())).
324 when(mockActorContext).actorSelection(actorRef.path().toString());
326 doReturn(primaryShardInfoReply(actorSystem, actorRef)).
327 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
329 doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
331 doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
336 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
337 TransactionType type, int transactionVersion, String shardName) {
338 ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName);
340 return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
341 memberName, shardActorRef);
344 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
345 TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
348 if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
349 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
350 txActorRef = shardActorRef;
352 txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
353 log.info("Created mock shard Tx actor {}", txActorRef);
355 doReturn(actorSystem.actorSelection(txActorRef.path())).
356 when(mockActorContext).actorSelection(txActorRef.path().toString());
358 doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
359 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
360 eqCreateTransaction(prefix, type));
366 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
367 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
368 DefaultShardStrategy.DEFAULT_SHARD);
371 protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
373 return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
377 protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
381 future.checkedGet(5, TimeUnit.SECONDS);
382 fail("Expected ReadFailedException");
383 } catch(ReadFailedException e) {
388 protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
389 ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
390 ArgumentCaptor.forClass(BatchedModifications.class);
391 verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
392 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
394 List<BatchedModifications> batchedModifications = filterCaptured(
395 batchedModificationsCaptor, BatchedModifications.class);
396 return batchedModifications;
399 protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
400 List<T> captured = new ArrayList<>();
401 for(T c: captor.getAllValues()) {
402 if(type.isInstance(c)) {
410 protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
411 List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
412 assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
414 verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
417 protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
418 verifyBatchedModifications(message, expIsReady, false, expected);
421 protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
422 Modification... expected) {
423 assertEquals("Message type", BatchedModifications.class, message.getClass());
424 BatchedModifications batchedModifications = (BatchedModifications)message;
425 assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
426 assertEquals("isReady", expIsReady, batchedModifications.isReady());
427 assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
428 for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
429 Modification actual = batchedModifications.getModifications().get(i);
430 assertEquals("Modification type", expected[i].getClass(), actual.getClass());
431 assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
432 ((AbstractModification)actual).getPath());
433 if(actual instanceof WriteModification) {
434 assertEquals("getData", ((WriteModification)expected[i]).getData(),
435 ((WriteModification)actual).getData());
440 protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
441 Object... expReplies) throws Exception {
442 assertEquals("getReadyOperationFutures size", expReplies.length,
443 proxy.getCohortFutures().size());
445 List<Object> futureResults = new ArrayList<>();
446 for( Future<?> future: proxy.getCohortFutures()) {
447 assertNotNull("Ready operation Future is null", future);
449 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
450 } catch(Exception e) {
451 futureResults.add(e);
455 for(int i = 0; i < expReplies.length; i++) {
456 Object expReply = expReplies[i];
457 boolean found = false;
458 Iterator<?> iter = futureResults.iterator();
459 while(iter.hasNext()) {
460 Object actual = iter.next();
461 if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
462 CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
464 } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
466 } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
477 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));