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