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