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