Deprecate CreateTransaction protobuff message
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / AbstractTransactionProxyTest.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.datastore;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.fail;
13 import static org.mockito.Matchers.any;
14 import static org.mockito.Matchers.argThat;
15 import static org.mockito.Matchers.eq;
16 import static org.mockito.Matchers.isA;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.verify;
20 import akka.actor.ActorRef;
21 import akka.actor.ActorSelection;
22 import akka.actor.ActorSystem;
23 import akka.actor.Props;
24 import akka.dispatch.Futures;
25 import akka.testkit.JavaTestKit;
26 import akka.util.Timeout;
27 import com.codahale.metrics.MetricRegistry;
28 import com.codahale.metrics.Timer;
29 import com.google.common.base.Objects;
30 import com.google.common.base.Optional;
31 import com.google.common.collect.ImmutableMap;
32 import com.google.common.util.concurrent.CheckedFuture;
33 import com.typesafe.config.Config;
34 import com.typesafe.config.ConfigFactory;
35 import java.io.IOException;
36 import java.util.ArrayList;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.concurrent.TimeUnit;
41 import org.junit.AfterClass;
42 import org.junit.Before;
43 import org.junit.BeforeClass;
44 import org.mockito.ArgumentCaptor;
45 import org.mockito.ArgumentMatcher;
46 import org.mockito.Mock;
47 import org.mockito.Mockito;
48 import org.mockito.MockitoAnnotations;
49 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
50 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
51 import org.opendaylight.controller.cluster.datastore.config.Configuration;
52 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
53 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
54 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
55 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
56 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
57 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
58 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
59 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
60 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
61 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
62 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
64 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
65 import org.opendaylight.controller.cluster.datastore.modification.Modification;
66 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
67 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
68 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
69 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
70 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
71 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
72 import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
73 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
74 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
75 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
76 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
77 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
79 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
82 import scala.concurrent.Await;
83 import scala.concurrent.Future;
84 import scala.concurrent.duration.Duration;
85
86 /**
87  * Abstract base class for TransactionProxy unit tests.
88  *
89  * @author Thomas Pantelis
90  */
91 public abstract class AbstractTransactionProxyTest {
92     protected final Logger log = LoggerFactory.getLogger(getClass());
93
94     private static ActorSystem system;
95
96     private final Configuration configuration = new MockConfiguration() {
97         Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
98                 "junk", new ShardStrategy() {
99                     @Override
100                     public String findShard(YangInstanceIdentifier path) {
101                         return "junk";
102                     }
103                 }).put(
104                 "cars", new ShardStrategy() {
105                     @Override
106                     public String findShard(YangInstanceIdentifier path) {
107                         return "cars";
108                     }
109                 }).build();
110
111         @Override
112         public ShardStrategy getStrategyForModule(String moduleName) {
113             return strategyMap.get(moduleName);
114         }
115
116         @Override
117         public String getModuleNameFromNameSpace(String nameSpace) {
118             if(TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
119                 return "junk";
120             } else if(CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)){
121                 return "cars";
122             }
123             return null;
124         }
125     };
126
127     @Mock
128     protected ActorContext mockActorContext;
129
130     protected TransactionContextFactory mockComponentFactory;
131
132     private SchemaContext schemaContext;
133
134     @Mock
135     private ClusterWrapper mockClusterWrapper;
136
137     protected final String memberName = "mock-member";
138
139     private final int operationTimeoutInSeconds = 2;
140     protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
141             .operationTimeoutInSeconds(operationTimeoutInSeconds);
142
143     @BeforeClass
144     public static void setUpClass() throws IOException {
145
146         Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
147                 put("akka.actor.default-dispatcher.type",
148                         "akka.testkit.CallingThreadDispatcherConfigurator").build()).
149                 withFallback(ConfigFactory.load());
150         system = ActorSystem.create("test", config);
151     }
152
153     @AfterClass
154     public static void tearDownClass() throws IOException {
155         JavaTestKit.shutdownActorSystem(system);
156         system = null;
157     }
158
159     @Before
160     public void setUp(){
161         MockitoAnnotations.initMocks(this);
162
163         schemaContext = TestModel.createTestContext();
164
165         doReturn(getSystem()).when(mockActorContext).getActorSystem();
166         doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
167         doReturn(memberName).when(mockActorContext).getCurrentMemberName();
168         doReturn(new ShardStrategyFactory(configuration)).when(mockActorContext).getShardStrategyFactory();
169         doReturn(schemaContext).when(mockActorContext).getSchemaContext();
170         doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
171         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
172         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
173         doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
174
175         mockComponentFactory = TransactionContextFactory.create(mockActorContext);
176
177         Timer timer = new MetricRegistry().timer("test");
178         doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
179     }
180
181     protected ActorSystem getSystem() {
182         return system;
183     }
184
185     protected CreateTransaction eqCreateTransaction(final String memberName,
186             final TransactionType type) {
187         ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
188             @Override
189             public boolean matches(Object argument) {
190                 if(CreateTransaction.class.equals(argument.getClass())) {
191                     CreateTransaction obj = CreateTransaction.fromSerializable(argument);
192                     return obj.getTransactionId().startsWith(memberName) &&
193                             obj.getTransactionType() == type.ordinal();
194                 }
195
196                 return false;
197             }
198         };
199
200         return argThat(matcher);
201     }
202
203     protected DataExists eqSerializedDataExists() {
204         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
205             @Override
206             public boolean matches(Object argument) {
207                 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
208                        DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
209             }
210         };
211
212         return argThat(matcher);
213     }
214
215     protected DataExists eqDataExists() {
216         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
217             @Override
218             public boolean matches(Object argument) {
219                 return (argument instanceof DataExists) &&
220                     ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
221             }
222         };
223
224         return argThat(matcher);
225     }
226
227     protected ReadData eqSerializedReadData() {
228         return eqSerializedReadData(TestModel.TEST_PATH);
229     }
230
231     protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
232         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
233             @Override
234             public boolean matches(Object argument) {
235                 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
236                        ReadData.fromSerializable(argument).getPath().equals(path);
237             }
238         };
239
240         return argThat(matcher);
241     }
242
243     protected ReadData eqReadData() {
244         return eqReadData(TestModel.TEST_PATH);
245     }
246
247     protected ReadData eqReadData(final YangInstanceIdentifier path) {
248         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
249             @Override
250             public boolean matches(Object argument) {
251                 return (argument instanceof ReadData) && ((ReadData)argument).getPath().equals(path);
252             }
253         };
254
255         return argThat(matcher);
256     }
257
258     protected Future<Object> readyTxReply(String path) {
259         return Futures.successful((Object)new ReadyTransactionReply(path));
260     }
261
262
263     protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
264         return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
265     }
266
267     protected Future<DataExistsReply> dataExistsReply(boolean exists) {
268         return Futures.successful(DataExistsReply.create(exists));
269     }
270
271     protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
272         return Futures.successful(new BatchedModificationsReply(count));
273     }
274
275     @SuppressWarnings("unchecked")
276     protected Future<Object> incompleteFuture() {
277         return mock(Future.class);
278     }
279
280     protected ActorSelection actorSelection(ActorRef actorRef) {
281         return getSystem().actorSelection(actorRef.path());
282     }
283
284     protected void expectBatchedModifications(ActorRef actorRef, int count) {
285         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
286                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
287     }
288
289     protected void expectBatchedModificationsReady(ActorRef actorRef) {
290         expectBatchedModificationsReady(actorRef, false);
291     }
292
293     protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) {
294         doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
295             readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
296                     eq(actorSelection(actorRef)), isA(BatchedModifications.class));
297     }
298
299     protected void expectBatchedModifications(int count) {
300         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
301                 any(ActorSelection.class), isA(BatchedModifications.class));
302     }
303
304     protected void expectIncompleteBatchedModifications() {
305         doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
306                 any(ActorSelection.class), isA(BatchedModifications.class));
307     }
308
309     protected void expectFailedBatchedModifications(ActorRef actorRef) {
310         doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
311                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
312     }
313
314     protected void expectReadyLocalTransaction(ActorRef actorRef, boolean doCommitOnReady) {
315         doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
316             readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
317                     eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
318     }
319
320     protected CreateTransactionReply createTransactionReply(ActorRef actorRef, short transactionVersion){
321         return new CreateTransactionReply(actorRef.path().toString(), "txn-1", transactionVersion);
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 &&
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), any(Timeout.class));
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             assertNotNull("Expected a cause", e.getCause());
408             if(e.getCause().getCause() != null) {
409                 throw e.getCause().getCause();
410             } else {
411                 throw e.getCause();
412             }
413         }
414     }
415
416     protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
417         ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
418                 ArgumentCaptor.forClass(BatchedModifications.class);
419         verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
420                 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
421
422         List<BatchedModifications> batchedModifications = filterCaptured(
423                 batchedModificationsCaptor, BatchedModifications.class);
424         return batchedModifications;
425     }
426
427     protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
428         List<T> captured = new ArrayList<>();
429         for(T c: captor.getAllValues()) {
430             if(type.isInstance(c)) {
431                 captured.add(c);
432             }
433         }
434
435         return captured;
436     }
437
438     protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
439         List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
440         assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
441
442         verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
443     }
444
445     protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
446         verifyBatchedModifications(message, expIsReady, false, expected);
447     }
448
449     protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady,
450             Modification... expected) {
451         assertEquals("Message type", BatchedModifications.class, message.getClass());
452         BatchedModifications batchedModifications = (BatchedModifications)message;
453         assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
454         assertEquals("isReady", expIsReady, batchedModifications.isReady());
455         assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
456         for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
457             Modification actual = batchedModifications.getModifications().get(i);
458             assertEquals("Modification type", expected[i].getClass(), actual.getClass());
459             assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
460                     ((AbstractModification)actual).getPath());
461             if(actual instanceof WriteModification) {
462                 assertEquals("getData", ((WriteModification)expected[i]).getData(),
463                         ((WriteModification)actual).getData());
464             }
465         }
466     }
467
468     protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
469             Object... expReplies) throws Exception {
470             assertEquals("getReadyOperationFutures size", expReplies.length,
471                     proxy.getCohortFutures().size());
472
473             List<Object> futureResults = new ArrayList<>();
474             for( Future<?> future: proxy.getCohortFutures()) {
475                 assertNotNull("Ready operation Future is null", future);
476                 try {
477                     futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
478                 } catch(Exception e) {
479                     futureResults.add(e);
480                 }
481             }
482
483             for(int i = 0; i < expReplies.length; i++) {
484                 Object expReply = expReplies[i];
485                 boolean found = false;
486                 Iterator<?> iter = futureResults.iterator();
487                 while(iter.hasNext()) {
488                     Object actual = iter.next();
489                     if(CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(expReply) &&
490                        CommitTransactionReply.SERIALIZABLE_CLASS.isInstance(actual)) {
491                         found = true;
492                     } else if(expReply instanceof ActorSelection && Objects.equal(expReply, actual)) {
493                         found = true;
494                     } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
495                         found = true;
496                     }
497
498                     if(found) {
499                         iter.remove();
500                         break;
501                     }
502                 }
503
504                 if(!found) {
505                     fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));
506                 }
507             }
508         }
509 }