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