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