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