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