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