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