c22b7acd386cf3c5ecc66ab8dbbf2cc1d75f7e8f
[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 com.codahale.metrics.MetricRegistry;
27 import com.codahale.metrics.Timer;
28 import com.google.common.base.Objects;
29 import com.google.common.base.Optional;
30 import com.google.common.collect.ImmutableMap;
31 import com.google.common.util.concurrent.CheckedFuture;
32 import com.typesafe.config.Config;
33 import com.typesafe.config.ConfigFactory;
34 import java.io.IOException;
35 import java.util.ArrayList;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
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.messages.BatchedModifications;
51 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
52 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
53 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
54 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
55 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
56 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
57 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
58 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
59 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
60 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
61 import org.opendaylight.controller.cluster.datastore.modification.Modification;
62 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
63 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
64 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
65 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
66 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
67 import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
68 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
69 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
70 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
71 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
75 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78 import scala.concurrent.Await;
79 import scala.concurrent.Future;
80 import scala.concurrent.duration.Duration;
81
82 /**
83  * Abstract base class for TransactionProxy unit tests.
84  *
85  * @author Thomas Pantelis
86  */
87 public abstract class AbstractTransactionProxyTest {
88     protected final Logger log = LoggerFactory.getLogger(getClass());
89
90     private static ActorSystem system;
91
92     private final Configuration configuration = new MockConfiguration() {
93         @Override
94         public Map<String, ShardStrategy> getModuleNameToShardStrategyMap() {
95             return ImmutableMap.<String, ShardStrategy>builder().put(
96                     "junk", new ShardStrategy() {
97                         @Override
98                         public String findShard(YangInstanceIdentifier path) {
99                             return "junk";
100                         }
101                     }).build();
102         }
103
104         @Override
105         public Optional<String> getModuleNameFromNameSpace(String nameSpace) {
106             return TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace) ?
107                     Optional.of("junk") : Optional.<String>absent();
108         }
109     };
110
111     @Mock
112     protected ActorContext mockActorContext;
113
114     private SchemaContext schemaContext;
115
116     @Mock
117     private ClusterWrapper mockClusterWrapper;
118
119     protected final String memberName = "mock-member";
120
121     protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
122
123     @BeforeClass
124     public static void setUpClass() throws IOException {
125
126         Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
127                 put("akka.actor.default-dispatcher.type",
128                         "akka.testkit.CallingThreadDispatcherConfigurator").build()).
129                 withFallback(ConfigFactory.load());
130         system = ActorSystem.create("test", config);
131     }
132
133     @AfterClass
134     public static void tearDownClass() throws IOException {
135         JavaTestKit.shutdownActorSystem(system);
136         system = null;
137     }
138
139     @Before
140     public void setUp(){
141         MockitoAnnotations.initMocks(this);
142
143         schemaContext = TestModel.createTestContext();
144
145         doReturn(getSystem()).when(mockActorContext).getActorSystem();
146         doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
147         doReturn(memberName).when(mockActorContext).getCurrentMemberName();
148         doReturn(schemaContext).when(mockActorContext).getSchemaContext();
149         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
150         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
151         doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
152         doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
153
154         Timer timer = new MetricRegistry().timer("test");
155         doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
156
157         ShardStrategyFactory.setConfiguration(configuration);
158     }
159
160     protected ActorSystem getSystem() {
161         return system;
162     }
163
164     protected CreateTransaction eqCreateTransaction(final String memberName,
165             final TransactionType type) {
166         ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
167             @Override
168             public boolean matches(Object argument) {
169                 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
170                     CreateTransaction obj = CreateTransaction.fromSerializable(argument);
171                     return obj.getTransactionId().startsWith(memberName) &&
172                             obj.getTransactionType() == type.ordinal();
173                 }
174
175                 return false;
176             }
177         };
178
179         return argThat(matcher);
180     }
181
182     protected DataExists eqSerializedDataExists() {
183         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
184             @Override
185             public boolean matches(Object argument) {
186                 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
187                        DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
188             }
189         };
190
191         return argThat(matcher);
192     }
193
194     protected DataExists eqDataExists() {
195         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
196             @Override
197             public boolean matches(Object argument) {
198                 return (argument instanceof DataExists) &&
199                     ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
200             }
201         };
202
203         return argThat(matcher);
204     }
205
206     protected ReadData eqSerializedReadData() {
207         return eqSerializedReadData(TestModel.TEST_PATH);
208     }
209
210     protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
211         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
212             @Override
213             public boolean matches(Object argument) {
214                 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
215                        ReadData.fromSerializable(argument).getPath().equals(path);
216             }
217         };
218
219         return argThat(matcher);
220     }
221
222     protected ReadData eqReadData() {
223         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
224             @Override
225             public boolean matches(Object argument) {
226                 return (argument instanceof ReadData) &&
227                     ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
228             }
229         };
230
231         return argThat(matcher);
232     }
233
234     protected Future<Object> readyTxReply(String path) {
235         return Futures.successful((Object)new ReadyTransactionReply(path));
236     }
237
238     protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
239             short transactionVersion) {
240         return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
241     }
242
243     protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
244         return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
245     }
246
247     protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
248         return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
249     }
250
251     protected Future<Object> dataExistsSerializedReply(boolean exists) {
252         return Futures.successful(DataExistsReply.create(exists).toSerializable());
253     }
254
255     protected Future<DataExistsReply> dataExistsReply(boolean exists) {
256         return Futures.successful(DataExistsReply.create(exists));
257     }
258
259     protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
260         return Futures.successful(new BatchedModificationsReply(count));
261     }
262
263     protected Future<Object> incompleteFuture() {
264         return mock(Future.class);
265     }
266
267     protected ActorSelection actorSelection(ActorRef actorRef) {
268         return getSystem().actorSelection(actorRef.path());
269     }
270
271     protected void expectBatchedModifications(ActorRef actorRef, int count) {
272         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
273                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
274     }
275
276     protected void expectBatchedModificationsReady(ActorRef actorRef) {
277         expectBatchedModificationsReady(actorRef, false);
278     }
279
280     protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
281         doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
282             readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
283                     eq(actorSelection(actorRef)), isA(BatchedModifications.class));
284     }
285
286     protected void expectBatchedModifications(int count) {
287         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
288                 any(ActorSelection.class), isA(BatchedModifications.class));
289     }
290
291     protected void expectIncompleteBatchedModifications() {
292         doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
293                 any(ActorSelection.class), isA(BatchedModifications.class));
294     }
295
296     protected void expectFailedBatchedModifications(ActorRef actorRef) {
297         doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
298                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
299     }
300
301     protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
302         return CreateTransactionReply.newBuilder()
303             .setTransactionActorPath(actorRef.path().toString())
304             .setTransactionId("txn-1")
305             .setMessageVersion(transactionVersion)
306             .build();
307     }
308
309     protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
310         return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
311     }
312
313     protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
314         return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
315                 Optional.<DataTree>absent()));
316     }
317
318     protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
319         ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
320         log.info("Created mock shard actor {}", actorRef);
321
322         doReturn(actorSystem.actorSelection(actorRef.path())).
323                 when(mockActorContext).actorSelection(actorRef.path().toString());
324
325         doReturn(primaryShardInfoReply(actorSystem, actorRef)).
326                 when(mockActorContext).findPrimaryShardAsync(eq(shardName));
327
328         doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
329
330         doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
331
332         return actorRef;
333     }
334
335     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
336             TransactionType type, int transactionVersion, String shardName) {
337         ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName);
338
339         return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
340                 memberName, shardActorRef);
341     }
342
343     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
344             TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
345
346         ActorRef txActorRef;
347         if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
348                 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
349             txActorRef = shardActorRef;
350         } else {
351             txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
352             log.info("Created mock shard Tx actor {}", txActorRef);
353
354             doReturn(actorSystem.actorSelection(txActorRef.path())).
355             when(mockActorContext).actorSelection(txActorRef.path().toString());
356
357             doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
358             executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
359                     eqCreateTransaction(prefix, type));
360         }
361
362         return txActorRef;
363     }
364
365     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
366         return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
367                 DefaultShardStrategy.DEFAULT_SHARD);
368     }
369
370     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type,
371             String shardName) {
372         return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
373                 shardName);
374     }
375
376     protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
377             throws Throwable {
378
379         try {
380             future.checkedGet(5, TimeUnit.SECONDS);
381             fail("Expected ReadFailedException");
382         } catch(ReadFailedException e) {
383             throw e.getCause();
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());
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(int i = 0; i < expReplies.length; i++) {
455                 Object expReply = expReplies[i];
456                 boolean found = false;
457                 Iterator<?> iter = futureResults.iterator();
458                 while(iter.hasNext()) {
459                     Object actual = iter.next();
460                     if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
461                        CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
462                         found = true;
463                     } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
464                         found = true;
465                     } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
466                         found = true;
467                     }
468
469                     if(found) {
470                         iter.remove();
471                         break;
472                     }
473                 }
474
475                 if(!found) {
476                     fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));
477                 }
478             }
479         }
480 }