Do not use MoreExecutors.sameThreadExecutor()
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / AbstractTransactionProxyTest.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore;
9
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;
39 import java.util.Map;
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;
84
85 /**
86  * Abstract base class for TransactionProxy unit tests.
87  *
88  * @author Thomas Pantelis
89  */
90 public abstract class AbstractTransactionProxyTest {
91     protected final Logger log = LoggerFactory.getLogger(getClass());
92
93     private static ActorSystem system;
94
95     private final Configuration configuration = new MockConfiguration() {
96         Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
97                 "junk", new ShardStrategy() {
98                     @Override
99                     public String findShard(YangInstanceIdentifier path) {
100                         return "junk";
101                     }
102                 }).put(
103                 "cars", new ShardStrategy() {
104                     @Override
105                     public String findShard(YangInstanceIdentifier path) {
106                         return "cars";
107                     }
108                 }).build();
109
110         @Override
111         public ShardStrategy getStrategyForModule(String moduleName) {
112             return strategyMap.get(moduleName);
113         }
114
115         @Override
116         public String getModuleNameFromNameSpace(String nameSpace) {
117             if(TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
118                 return "junk";
119             } else if(CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)){
120                 return "cars";
121             }
122             return null;
123         }
124     };
125
126     @Mock
127     protected ActorContext mockActorContext;
128
129     protected TransactionContextFactory mockComponentFactory;
130
131     private SchemaContext schemaContext;
132
133     @Mock
134     private ClusterWrapper mockClusterWrapper;
135
136     protected final String memberName = "mock-member";
137
138     private final int operationTimeoutInSeconds = 2;
139     protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
140             .operationTimeoutInSeconds(operationTimeoutInSeconds);
141
142     @BeforeClass
143     public static void setUpClass() throws IOException {
144
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);
150     }
151
152     @AfterClass
153     public static void tearDownClass() throws IOException {
154         JavaTestKit.shutdownActorSystem(system);
155         system = null;
156     }
157
158     @Before
159     public void setUp(){
160         MockitoAnnotations.initMocks(this);
161
162         schemaContext = TestModel.createTestContext();
163
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();
173
174         mockComponentFactory = TransactionContextFactory.create(mockActorContext);
175
176         Timer timer = new MetricRegistry().timer("test");
177         doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
178     }
179
180     protected ActorSystem getSystem() {
181         return system;
182     }
183
184     protected CreateTransaction eqCreateTransaction(final String memberName,
185             final TransactionType type) {
186         ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
187             @Override
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();
193                 }
194
195                 return false;
196             }
197         };
198
199         return argThat(matcher);
200     }
201
202     protected DataExists eqSerializedDataExists() {
203         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
204             @Override
205             public boolean matches(Object argument) {
206                 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
207                        DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
208             }
209         };
210
211         return argThat(matcher);
212     }
213
214     protected DataExists eqDataExists() {
215         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
216             @Override
217             public boolean matches(Object argument) {
218                 return (argument instanceof DataExists) &&
219                     ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
220             }
221         };
222
223         return argThat(matcher);
224     }
225
226     protected ReadData eqSerializedReadData() {
227         return eqSerializedReadData(TestModel.TEST_PATH);
228     }
229
230     protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
231         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
232             @Override
233             public boolean matches(Object argument) {
234                 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
235                        ReadData.fromSerializable(argument).getPath().equals(path);
236             }
237         };
238
239         return argThat(matcher);
240     }
241
242     protected ReadData eqReadData() {
243         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
244             @Override
245             public boolean matches(Object argument) {
246                 return (argument instanceof ReadData) &&
247                     ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
248             }
249         };
250
251         return argThat(matcher);
252     }
253
254     protected Future<Object> readyTxReply(String path) {
255         return Futures.successful((Object)new ReadyTransactionReply(path));
256     }
257
258     protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
259             short transactionVersion) {
260         return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
261     }
262
263     protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
264         return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
265     }
266
267     protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
268         return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
269     }
270
271     protected Future<Object> dataExistsSerializedReply(boolean exists) {
272         return Futures.successful(DataExistsReply.create(exists).toSerializable());
273     }
274
275     protected Future<DataExistsReply> dataExistsReply(boolean exists) {
276         return Futures.successful(DataExistsReply.create(exists));
277     }
278
279     protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
280         return Futures.successful(new BatchedModificationsReply(count));
281     }
282
283     @SuppressWarnings("unchecked")
284     protected Future<Object> incompleteFuture() {
285         return mock(Future.class);
286     }
287
288     protected ActorSelection actorSelection(ActorRef actorRef) {
289         return getSystem().actorSelection(actorRef.path());
290     }
291
292     protected void expectBatchedModifications(ActorRef actorRef, int count) {
293         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
294                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
295     }
296
297     protected void expectBatchedModificationsReady(ActorRef actorRef) {
298         expectBatchedModificationsReady(actorRef, false);
299     }
300
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));
305     }
306
307     protected void expectBatchedModifications(int count) {
308         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
309                 any(ActorSelection.class), isA(BatchedModifications.class));
310     }
311
312     protected void expectIncompleteBatchedModifications() {
313         doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
314                 any(ActorSelection.class), isA(BatchedModifications.class));
315     }
316
317     protected void expectFailedBatchedModifications(ActorRef actorRef) {
318         doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
319                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
320     }
321
322     protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
323         return CreateTransactionReply.newBuilder()
324             .setTransactionActorPath(actorRef.path().toString())
325             .setTransactionId("txn-1")
326             .setMessageVersion(transactionVersion)
327             .build();
328     }
329
330     protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
331         return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
332     }
333
334     protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
335         return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
336     }
337
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()));
342     }
343
344     protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
345         return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName, DataStoreVersions.CURRENT_VERSION);
346     }
347
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);
352
353         doReturn(actorSystem.actorSelection(actorRef.path())).
354                 when(mockActorContext).actorSelection(actorRef.path().toString());
355
356         doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion)).
357                 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
358
359         doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
360
361         return actorRef;
362     }
363
364     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
365             TransactionType type, short transactionVersion, String shardName) {
366         ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
367                 transactionVersion);
368
369         return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
370                 memberName, shardActorRef);
371     }
372
373     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
374             TransactionType type, short transactionVersion, String prefix, ActorRef shardActorRef) {
375
376         ActorRef txActorRef;
377         if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
378                 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
379             txActorRef = shardActorRef;
380         } else {
381             txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
382             log.info("Created mock shard Tx actor {}", txActorRef);
383
384             doReturn(actorSystem.actorSelection(txActorRef.path())).
385                 when(mockActorContext).actorSelection(txActorRef.path().toString());
386
387             doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
388                 executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
389                         eqCreateTransaction(prefix, type), any(Timeout.class));
390         }
391
392         return txActorRef;
393     }
394
395     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
396         return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
397                 DefaultShardStrategy.DEFAULT_SHARD);
398     }
399
400     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
401             String shardName) {
402         return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
403                 shardName);
404     }
405
406     protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
407             throws Throwable {
408
409         try {
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();
416             } else {
417                 throw e.getCause();
418             }
419         }
420     }
421
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());
427
428         List<BatchedModifications> batchedModifications = filterCaptured(
429                 batchedModificationsCaptor, BatchedModifications.class);
430         return batchedModifications;
431     }
432
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)) {
437                 captured.add(c);
438             }
439         }
440
441         return captured;
442     }
443
444     protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
445         List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
446         assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
447
448         verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
449     }
450
451     protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
452         verifyBatchedModifications(message, expIsReady, false, expected);
453     }
454
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());
470             }
471         }
472     }
473
474     protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
475             Object... expReplies) throws Exception {
476             assertEquals("getReadyOperationFutures size", expReplies.length,
477                     proxy.getCohortFutures().size());
478
479             List<Object> futureResults = new ArrayList<>();
480             for( Future<?> future: proxy.getCohortFutures()) {
481                 assertNotNull("Ready operation Future is null", future);
482                 try {
483                     futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
484                 } catch(Exception e) {
485                     futureResults.add(e);
486                 }
487             }
488
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)) {
497                         found = true;
498                     } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
499                         found = true;
500                     } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
501                         found = true;
502                     }
503
504                     if(found) {
505                         iter.remove();
506                         break;
507                     }
508                 }
509
510                 if(!found) {
511                     fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));
512                 }
513             }
514         }
515 }