Reduce use of scala.concurrent.duration.Duration
[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.assertTrue;
13 import static org.junit.Assert.fail;
14 import static org.mockito.ArgumentMatchers.any;
15 import static org.mockito.ArgumentMatchers.argThat;
16 import static org.mockito.ArgumentMatchers.eq;
17 import static org.mockito.ArgumentMatchers.isA;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.verify;
21
22 import akka.actor.ActorRef;
23 import akka.actor.ActorSelection;
24 import akka.actor.ActorSystem;
25 import akka.actor.Props;
26 import akka.dispatch.Futures;
27 import akka.testkit.javadsl.TestKit;
28 import akka.util.Timeout;
29 import com.codahale.metrics.MetricRegistry;
30 import com.codahale.metrics.Timer;
31 import com.google.common.base.Throwables;
32 import com.google.common.collect.ImmutableMap;
33 import com.google.common.util.concurrent.FluentFuture;
34 import com.typesafe.config.Config;
35 import com.typesafe.config.ConfigFactory;
36 import java.util.ArrayList;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Objects;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.TimeUnit;
43 import org.junit.AfterClass;
44 import org.junit.Before;
45 import org.junit.BeforeClass;
46 import org.mockito.ArgumentCaptor;
47 import org.mockito.ArgumentMatcher;
48 import org.mockito.Mock;
49 import org.mockito.Mockito;
50 import org.mockito.MockitoAnnotations;
51 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
52 import org.opendaylight.controller.cluster.access.concepts.MemberName;
53 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
54 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
55 import org.opendaylight.controller.cluster.datastore.config.Configuration;
56 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
57 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
58 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
59 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
61 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
62 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
63 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
64 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
65 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
66 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
68 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
69 import org.opendaylight.controller.cluster.datastore.modification.Modification;
70 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
71 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
72 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
73 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
74 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
75 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
76 import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
77 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
78 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
79 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
80 import org.opendaylight.mdsal.common.api.ReadFailedException;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
83 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
86 import scala.concurrent.Await;
87 import scala.concurrent.Future;
88 import scala.concurrent.duration.FiniteDuration;
89
90 /**
91  * Abstract base class for TransactionProxy unit tests.
92  *
93  * @author Thomas Pantelis
94  */
95 public abstract class AbstractTransactionProxyTest extends AbstractTest {
96     protected final Logger log = LoggerFactory.getLogger(getClass());
97
98     private static ActorSystem system;
99     private static SchemaContext SCHEMA_CONTEXT;
100
101     private final Configuration configuration = new MockConfiguration() {
102         Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
103                 TestModel.JUNK_QNAME.getLocalName(), new ShardStrategy() {
104                     @Override
105                     public String findShard(final YangInstanceIdentifier path) {
106                         return TestModel.JUNK_QNAME.getLocalName();
107                     }
108
109                     @Override
110                     public YangInstanceIdentifier getPrefixForPath(final YangInstanceIdentifier path) {
111                         return YangInstanceIdentifier.EMPTY;
112                     }
113                 }).put(
114                 CarsModel.BASE_QNAME.getLocalName(), new ShardStrategy() {
115                     @Override
116                     public String findShard(final YangInstanceIdentifier path) {
117                         return CarsModel.BASE_QNAME.getLocalName();
118                     }
119
120                     @Override
121                     public YangInstanceIdentifier getPrefixForPath(final YangInstanceIdentifier path) {
122                         return YangInstanceIdentifier.EMPTY;
123                     }
124                 }).build();
125
126         @Override
127         public ShardStrategy getStrategyForModule(final String moduleName) {
128             return strategyMap.get(moduleName);
129         }
130
131         @Override
132         public String getModuleNameFromNameSpace(final String nameSpace) {
133             if (TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
134                 return TestModel.JUNK_QNAME.getLocalName();
135             } else if (CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
136                 return CarsModel.BASE_QNAME.getLocalName();
137             }
138             return null;
139         }
140     };
141
142     @Mock
143     protected ActorContext mockActorContext;
144
145     protected TransactionContextFactory mockComponentFactory;
146
147     @Mock
148     private ClusterWrapper mockClusterWrapper;
149
150     protected final String memberName = "mock-member";
151
152     private final int operationTimeoutInSeconds = 2;
153     protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
154             .operationTimeoutInSeconds(operationTimeoutInSeconds);
155
156     @BeforeClass
157     public static void setUpClass() {
158
159         Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
160                 .put("akka.actor.default-dispatcher.type",
161                         "akka.testkit.CallingThreadDispatcherConfigurator").build())
162                 .withFallback(ConfigFactory.load());
163         system = ActorSystem.create("test", config);
164         SCHEMA_CONTEXT = TestModel.createTestContext();
165     }
166
167     @AfterClass
168     public static void tearDownClass() {
169         TestKit.shutdownActorSystem(system);
170         system = null;
171         SCHEMA_CONTEXT = null;
172     }
173
174     @Before
175     public void setUp() {
176         MockitoAnnotations.initMocks(this);
177
178         doReturn(getSystem()).when(mockActorContext).getActorSystem();
179         doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
180         doReturn(MemberName.forName(memberName)).when(mockActorContext).getCurrentMemberName();
181         doReturn(new ShardStrategyFactory(configuration,
182                 LogicalDatastoreType.CONFIGURATION)).when(mockActorContext).getShardStrategyFactory();
183         doReturn(SCHEMA_CONTEXT).when(mockActorContext).getSchemaContext();
184         doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
185         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
186         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
187         doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
188         doReturn(new Timeout(5, TimeUnit.SECONDS)).when(mockActorContext).getTransactionCommitOperationTimeout();
189
190         final ClientIdentifier mockClientId = MockIdentifiers.clientIdentifier(getClass(), memberName);
191         mockComponentFactory = new TransactionContextFactory(mockActorContext, mockClientId);
192
193         Timer timer = new MetricRegistry().timer("test");
194         doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
195     }
196
197     protected ActorSystem getSystem() {
198         return system;
199     }
200
201     protected CreateTransaction eqCreateTransaction(final String expMemberName,
202             final TransactionType type) {
203         class CreateTransactionArgumentMatcher implements ArgumentMatcher<CreateTransaction> {
204             @Override
205             public boolean matches(CreateTransaction argument) {
206                 return argument.getTransactionId().getHistoryId().getClientId().getFrontendId().getMemberName()
207                         .getName().equals(expMemberName) && argument.getTransactionType() == type.ordinal();
208             }
209         }
210
211         return argThat(new CreateTransactionArgumentMatcher());
212     }
213
214     protected DataExists eqDataExists() {
215         class DataExistsArgumentMatcher implements ArgumentMatcher<DataExists> {
216             @Override
217             public boolean matches(DataExists argument) {
218                 return argument.getPath().equals(TestModel.TEST_PATH);
219             }
220         }
221
222         return argThat(new DataExistsArgumentMatcher());
223     }
224
225     protected ReadData eqReadData() {
226         return eqReadData(TestModel.TEST_PATH);
227     }
228
229     protected ReadData eqReadData(final YangInstanceIdentifier path) {
230         class ReadDataArgumentMatcher implements ArgumentMatcher<ReadData> {
231             @Override
232             public boolean matches(ReadData argument) {
233                 return argument.getPath().equals(path);
234             }
235         }
236
237         return argThat(new ReadDataArgumentMatcher());
238     }
239
240     protected Future<Object> readyTxReply(final String path) {
241         return Futures.successful((Object)new ReadyTransactionReply(path));
242     }
243
244
245     protected Future<ReadDataReply> readDataReply(final NormalizedNode<?, ?> data) {
246         return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
247     }
248
249     protected Future<DataExistsReply> dataExistsReply(final boolean exists) {
250         return Futures.successful(new DataExistsReply(exists, DataStoreVersions.CURRENT_VERSION));
251     }
252
253     protected Future<BatchedModificationsReply> batchedModificationsReply(final int count) {
254         return Futures.successful(new BatchedModificationsReply(count));
255     }
256
257     @SuppressWarnings("unchecked")
258     protected Future<Object> incompleteFuture() {
259         return mock(Future.class);
260     }
261
262     protected ActorSelection actorSelection(final ActorRef actorRef) {
263         return getSystem().actorSelection(actorRef.path());
264     }
265
266     protected void expectBatchedModifications(final ActorRef actorRef, final int count) {
267         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
268                 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
269     }
270
271     protected void expectBatchedModifications(final int count) {
272         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
273                 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
274     }
275
276     protected void expectBatchedModificationsReady(final ActorRef actorRef) {
277         expectBatchedModificationsReady(actorRef, false);
278     }
279
280     protected void expectBatchedModificationsReady(final ActorRef actorRef, final boolean doCommitOnReady) {
281         doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
282             readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
283                     eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
284     }
285
286     protected void expectIncompleteBatchedModifications() {
287         doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
288                 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
289     }
290
291     protected void expectFailedBatchedModifications(final ActorRef actorRef) {
292         doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
293                 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
294     }
295
296     protected void expectReadyLocalTransaction(final ActorRef actorRef, final boolean doCommitOnReady) {
297         doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
298             readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
299                     eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
300     }
301
302     protected CreateTransactionReply createTransactionReply(final ActorRef actorRef, final short transactionVersion) {
303         return new CreateTransactionReply(actorRef.path().toString(), nextTransactionId(), transactionVersion);
304     }
305
306     protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem) {
307         return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
308     }
309
310     protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
311             final String shardName) {
312         return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
313                 DataStoreVersions.CURRENT_VERSION);
314     }
315
316     protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
317             final String shardName, final short transactionVersion) {
318         ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
319         log.info("Created mock shard actor {}", actorRef);
320
321         doReturn(actorSystem.actorSelection(actorRef.path()))
322                 .when(mockActorContext).actorSelection(actorRef.path().toString());
323
324         doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion))
325                 .when(mockActorContext).findPrimaryShardAsync(eq(shardName));
326
327         return actorRef;
328     }
329
330     protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef) {
331         return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
332     }
333
334     protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef,
335             final short transactionVersion) {
336         return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
337                 transactionVersion));
338     }
339
340     protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
341             final TransactionType type, final short transactionVersion, final String shardName) {
342         ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
343                 transactionVersion);
344
345         return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
346                 memberName, shardActorRef);
347     }
348
349     protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
350             final TransactionType type, final short transactionVersion, final String prefix,
351             final ActorRef shardActorRef) {
352
353         ActorRef txActorRef;
354         if (type == TransactionType.WRITE_ONLY
355                 && dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
356             txActorRef = shardActorRef;
357         } else {
358             txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
359             log.info("Created mock shard Tx actor {}", txActorRef);
360
361             doReturn(actorSystem.actorSelection(txActorRef.path()))
362                 .when(mockActorContext).actorSelection(txActorRef.path().toString());
363
364             doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext)
365                 .executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
366                         eqCreateTransaction(prefix, type), any(Timeout.class));
367         }
368
369         return txActorRef;
370     }
371
372     protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
373             final TransactionType type) {
374         return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
375                 DefaultShardStrategy.DEFAULT_SHARD);
376     }
377
378     protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
379             final TransactionType type,
380             final String shardName) {
381         return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
382                 shardName);
383     }
384
385     @SuppressWarnings({"checkstyle:avoidHidingCauseException", "checkstyle:IllegalThrows"})
386     protected void propagateReadFailedExceptionCause(final FluentFuture<?> future) throws Throwable {
387         try {
388             future.get(5, TimeUnit.SECONDS);
389             fail("Expected ReadFailedException");
390         } catch (ExecutionException e) {
391             final Throwable cause = e.getCause();
392             assertTrue("Unexpected cause: " + cause.getClass(), cause instanceof ReadFailedException);
393             throw Throwables.getRootCause(cause);
394         }
395     }
396
397     protected List<BatchedModifications> captureBatchedModifications(final ActorRef actorRef) {
398         ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
399                 ArgumentCaptor.forClass(BatchedModifications.class);
400         verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
401                 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture(), any(Timeout.class));
402
403         List<BatchedModifications> batchedModifications = filterCaptured(
404                 batchedModificationsCaptor, BatchedModifications.class);
405         return batchedModifications;
406     }
407
408     protected <T> List<T> filterCaptured(final ArgumentCaptor<T> captor, final Class<T> type) {
409         List<T> captured = new ArrayList<>();
410         for (T c: captor.getAllValues()) {
411             if (type.isInstance(c)) {
412                 captured.add(c);
413             }
414         }
415
416         return captured;
417     }
418
419     protected void verifyOneBatchedModification(final ActorRef actorRef, final Modification expected,
420             final boolean expIsReady) {
421         List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
422         assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
423
424         verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
425     }
426
427     protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
428             final Modification... expected) {
429         verifyBatchedModifications(message, expIsReady, false, expected);
430     }
431
432     protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
433             final boolean expIsDoCommitOnReady, final Modification... expected) {
434         assertEquals("Message type", BatchedModifications.class, message.getClass());
435         BatchedModifications batchedModifications = (BatchedModifications)message;
436         assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
437         assertEquals("isReady", expIsReady, batchedModifications.isReady());
438         assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
439         for (int i = 0; i < batchedModifications.getModifications().size(); i++) {
440             Modification actual = batchedModifications.getModifications().get(i);
441             assertEquals("Modification type", expected[i].getClass(), actual.getClass());
442             assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
443                     ((AbstractModification)actual).getPath());
444             if (actual instanceof WriteModification) {
445                 assertEquals("getData", ((WriteModification)expected[i]).getData(),
446                         ((WriteModification)actual).getData());
447             }
448         }
449     }
450
451     @SuppressWarnings("checkstyle:IllegalCatch")
452     protected void verifyCohortFutures(final AbstractThreePhaseCommitCohort<?> proxy,
453             final Object... expReplies) {
454         assertEquals("getReadyOperationFutures size", expReplies.length,
455                 proxy.getCohortFutures().size());
456
457         List<Object> futureResults = new ArrayList<>();
458         for (Future<?> future : proxy.getCohortFutures()) {
459             assertNotNull("Ready operation Future is null", future);
460             try {
461                 futureResults.add(Await.result(future, FiniteDuration.create(5, TimeUnit.SECONDS)));
462             } catch (Exception e) {
463                 futureResults.add(e);
464             }
465         }
466
467         for (Object expReply : expReplies) {
468             boolean found = false;
469             Iterator<?> iter = futureResults.iterator();
470             while (iter.hasNext()) {
471                 Object actual = iter.next();
472                 if (CommitTransactionReply.isSerializedType(expReply)
473                         && CommitTransactionReply.isSerializedType(actual)) {
474                     found = true;
475                 } else if (expReply instanceof ActorSelection && Objects.equals(expReply, actual)) {
476                     found = true;
477                 } else if (expReply instanceof Class && ((Class<?>) expReply).isInstance(actual)) {
478                     found = true;
479                 }
480
481                 if (found) {
482                     iter.remove();
483                     break;
484                 }
485             }
486
487             if (!found) {
488                 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));
489             }
490         }
491     }
492 }