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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.