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