Remove unused exceptions
[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.Matchers.any;
15 import static org.mockito.Matchers.argThat;
16 import static org.mockito.Matchers.eq;
17 import static org.mockito.Matchers.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.Duration;
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
100     private final Configuration configuration = new MockConfiguration() {
101         Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
102                 TestModel.JUNK_QNAME.getLocalName(), new ShardStrategy() {
103                     @Override
104                     public String findShard(final YangInstanceIdentifier path) {
105                         return TestModel.JUNK_QNAME.getLocalName();
106                     }
107
108                     @Override
109                     public YangInstanceIdentifier getPrefixForPath(final YangInstanceIdentifier path) {
110                         return YangInstanceIdentifier.EMPTY;
111                     }
112                 }).put(
113                 CarsModel.BASE_QNAME.getLocalName(), new ShardStrategy() {
114                     @Override
115                     public String findShard(final YangInstanceIdentifier path) {
116                         return CarsModel.BASE_QNAME.getLocalName();
117                     }
118
119                     @Override
120                     public YangInstanceIdentifier getPrefixForPath(final YangInstanceIdentifier path) {
121                         return YangInstanceIdentifier.EMPTY;
122                     }
123                 }).build();
124
125         @Override
126         public ShardStrategy getStrategyForModule(final String moduleName) {
127             return strategyMap.get(moduleName);
128         }
129
130         @Override
131         public String getModuleNameFromNameSpace(final String nameSpace) {
132             if (TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
133                 return TestModel.JUNK_QNAME.getLocalName();
134             } else if (CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
135                 return CarsModel.BASE_QNAME.getLocalName();
136             }
137             return null;
138         }
139     };
140
141     @Mock
142     protected ActorContext mockActorContext;
143
144     protected TransactionContextFactory mockComponentFactory;
145
146     private SchemaContext schemaContext;
147
148     @Mock
149     private ClusterWrapper mockClusterWrapper;
150
151     protected final String memberName = "mock-member";
152
153     private final int operationTimeoutInSeconds = 2;
154     protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
155             .operationTimeoutInSeconds(operationTimeoutInSeconds);
156
157     @BeforeClass
158     public static void setUpClass() {
159
160         Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
161                 .put("akka.actor.default-dispatcher.type",
162                         "akka.testkit.CallingThreadDispatcherConfigurator").build())
163                 .withFallback(ConfigFactory.load());
164         system = ActorSystem.create("test", config);
165     }
166
167     @AfterClass
168     public static void tearDownClass() {
169         TestKit.shutdownActorSystem(system);
170         system = null;
171     }
172
173     @Before
174     public void setUp() {
175         MockitoAnnotations.initMocks(this);
176
177         schemaContext = TestModel.createTestContext();
178
179         doReturn(getSystem()).when(mockActorContext).getActorSystem();
180         doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
181         doReturn(MemberName.forName(memberName)).when(mockActorContext).getCurrentMemberName();
182         doReturn(new ShardStrategyFactory(configuration,
183                 LogicalDatastoreType.CONFIGURATION)).when(mockActorContext).getShardStrategyFactory();
184         doReturn(schemaContext).when(mockActorContext).getSchemaContext();
185         doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
186         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
187         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
188         doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
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         ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
204             @Override
205             public boolean matches(final Object argument) {
206                 if (CreateTransaction.class.equals(argument.getClass())) {
207                     CreateTransaction obj = CreateTransaction.fromSerializable(argument);
208                     return obj.getTransactionId().getHistoryId().getClientId().getFrontendId().getMemberName()
209                             .getName().equals(expMemberName) && obj.getTransactionType() == type.ordinal();
210                 }
211
212                 return false;
213             }
214         };
215
216         return argThat(matcher);
217     }
218
219     protected DataExists eqDataExists() {
220         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
221             @Override
222             public boolean matches(final Object argument) {
223                 return argument instanceof DataExists && ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
224             }
225         };
226
227         return argThat(matcher);
228     }
229
230     protected ReadData eqReadData() {
231         return eqReadData(TestModel.TEST_PATH);
232     }
233
234     protected ReadData eqReadData(final YangInstanceIdentifier path) {
235         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
236             @Override
237             public boolean matches(final Object argument) {
238                 return argument instanceof ReadData && ((ReadData)argument).getPath().equals(path);
239             }
240         };
241
242         return argThat(matcher);
243     }
244
245     protected Future<Object> readyTxReply(final String path) {
246         return Futures.successful((Object)new ReadyTransactionReply(path));
247     }
248
249
250     protected Future<ReadDataReply> readDataReply(final NormalizedNode<?, ?> data) {
251         return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
252     }
253
254     protected Future<DataExistsReply> dataExistsReply(final boolean exists) {
255         return Futures.successful(new DataExistsReply(exists, DataStoreVersions.CURRENT_VERSION));
256     }
257
258     protected Future<BatchedModificationsReply> batchedModificationsReply(final int count) {
259         return Futures.successful(new BatchedModificationsReply(count));
260     }
261
262     @SuppressWarnings("unchecked")
263     protected Future<Object> incompleteFuture() {
264         return mock(Future.class);
265     }
266
267     protected ActorSelection actorSelection(final ActorRef actorRef) {
268         return getSystem().actorSelection(actorRef.path());
269     }
270
271     protected void expectBatchedModifications(final ActorRef actorRef, final int count) {
272         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
273                 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
274     }
275
276     protected void expectBatchedModifications(final int count) {
277         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
278                 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
279     }
280
281     protected void expectBatchedModificationsReady(final ActorRef actorRef) {
282         expectBatchedModificationsReady(actorRef, false);
283     }
284
285     protected void expectBatchedModificationsReady(final ActorRef actorRef, final boolean doCommitOnReady) {
286         doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
287             readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
288                     eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
289     }
290
291     protected void expectIncompleteBatchedModifications() {
292         doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
293                 any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
294     }
295
296     protected void expectFailedBatchedModifications(final ActorRef actorRef) {
297         doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
298                 eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
299     }
300
301     protected void expectReadyLocalTransaction(final ActorRef actorRef, final boolean doCommitOnReady) {
302         doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
303             readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
304                     eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
305     }
306
307     protected CreateTransactionReply createTransactionReply(final ActorRef actorRef, final short transactionVersion) {
308         return new CreateTransactionReply(actorRef.path().toString(), nextTransactionId(), transactionVersion);
309     }
310
311     protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem) {
312         return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
313     }
314
315     protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
316             final String shardName) {
317         return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
318                 DataStoreVersions.CURRENT_VERSION);
319     }
320
321     protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
322             final String shardName, final short transactionVersion) {
323         ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
324         log.info("Created mock shard actor {}", actorRef);
325
326         doReturn(actorSystem.actorSelection(actorRef.path()))
327                 .when(mockActorContext).actorSelection(actorRef.path().toString());
328
329         doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion))
330                 .when(mockActorContext).findPrimaryShardAsync(eq(shardName));
331
332         return actorRef;
333     }
334
335     protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef) {
336         return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
337     }
338
339     protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef,
340             final short transactionVersion) {
341         return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
342                 transactionVersion));
343     }
344
345     protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
346             final TransactionType type, final short transactionVersion, final String shardName) {
347         ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
348                 transactionVersion);
349
350         return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
351                 memberName, shardActorRef);
352     }
353
354     protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
355             final TransactionType type, final short transactionVersion, final String prefix,
356             final ActorRef shardActorRef) {
357
358         ActorRef txActorRef;
359         if (type == TransactionType.WRITE_ONLY
360                 && dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
361             txActorRef = shardActorRef;
362         } else {
363             txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
364             log.info("Created mock shard Tx actor {}", txActorRef);
365
366             doReturn(actorSystem.actorSelection(txActorRef.path()))
367                 .when(mockActorContext).actorSelection(txActorRef.path().toString());
368
369             doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext)
370                 .executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
371                         eqCreateTransaction(prefix, type), any(Timeout.class));
372         }
373
374         return txActorRef;
375     }
376
377     protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
378             final TransactionType type) {
379         return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
380                 DefaultShardStrategy.DEFAULT_SHARD);
381     }
382
383     protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
384             final TransactionType type,
385             final String shardName) {
386         return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
387                 shardName);
388     }
389
390     @SuppressWarnings({"checkstyle:avoidHidingCauseException", "checkstyle:IllegalThrows"})
391     protected void propagateReadFailedExceptionCause(final FluentFuture<?> future) throws Throwable {
392         try {
393             future.get(5, TimeUnit.SECONDS);
394             fail("Expected ReadFailedException");
395         } catch (ExecutionException e) {
396             final Throwable cause = e.getCause();
397             assertTrue("Unexpected cause: " + cause.getClass(), cause instanceof ReadFailedException);
398             throw Throwables.getRootCause(cause);
399         }
400     }
401
402     protected List<BatchedModifications> captureBatchedModifications(final ActorRef actorRef) {
403         ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
404                 ArgumentCaptor.forClass(BatchedModifications.class);
405         verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
406                 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture(), any(Timeout.class));
407
408         List<BatchedModifications> batchedModifications = filterCaptured(
409                 batchedModificationsCaptor, BatchedModifications.class);
410         return batchedModifications;
411     }
412
413     protected <T> List<T> filterCaptured(final ArgumentCaptor<T> captor, final Class<T> type) {
414         List<T> captured = new ArrayList<>();
415         for (T c: captor.getAllValues()) {
416             if (type.isInstance(c)) {
417                 captured.add(c);
418             }
419         }
420
421         return captured;
422     }
423
424     protected void verifyOneBatchedModification(final ActorRef actorRef, final Modification expected,
425             final boolean expIsReady) {
426         List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
427         assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
428
429         verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
430     }
431
432     protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
433             final Modification... expected) {
434         verifyBatchedModifications(message, expIsReady, false, expected);
435     }
436
437     protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
438             final boolean expIsDoCommitOnReady, final Modification... expected) {
439         assertEquals("Message type", BatchedModifications.class, message.getClass());
440         BatchedModifications batchedModifications = (BatchedModifications)message;
441         assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
442         assertEquals("isReady", expIsReady, batchedModifications.isReady());
443         assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
444         for (int i = 0; i < batchedModifications.getModifications().size(); i++) {
445             Modification actual = batchedModifications.getModifications().get(i);
446             assertEquals("Modification type", expected[i].getClass(), actual.getClass());
447             assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
448                     ((AbstractModification)actual).getPath());
449             if (actual instanceof WriteModification) {
450                 assertEquals("getData", ((WriteModification)expected[i]).getData(),
451                         ((WriteModification)actual).getData());
452             }
453         }
454     }
455
456     @SuppressWarnings("checkstyle:IllegalCatch")
457     protected void verifyCohortFutures(final AbstractThreePhaseCommitCohort<?> proxy,
458             final Object... expReplies) {
459         assertEquals("getReadyOperationFutures size", expReplies.length,
460                 proxy.getCohortFutures().size());
461
462         List<Object> futureResults = new ArrayList<>();
463         for (Future<?> future : proxy.getCohortFutures()) {
464             assertNotNull("Ready operation Future is null", future);
465             try {
466                 futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
467             } catch (Exception e) {
468                 futureResults.add(e);
469             }
470         }
471
472         for (Object expReply : expReplies) {
473             boolean found = false;
474             Iterator<?> iter = futureResults.iterator();
475             while (iter.hasNext()) {
476                 Object actual = iter.next();
477                 if (CommitTransactionReply.isSerializedType(expReply)
478                         && CommitTransactionReply.isSerializedType(actual)) {
479                     found = true;
480                 } else if (expReply instanceof ActorSelection && Objects.equals(expReply, actual)) {
481                     found = true;
482                 } else if (expReply instanceof Class && ((Class<?>) expReply).isInstance(actual)) {
483                     found = true;
484                 }
485
486                 if (found) {
487                     iter.remove();
488                     break;
489                 }
490             }
491
492             if (!found) {
493                 fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));
494             }
495         }
496     }
497 }