Merge "Bug 2948: Perform create snapshot synchronously"
[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.assertTrue;
13 import static org.junit.Assert.fail;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.argThat;
16 import static org.mockito.Matchers.eq;
17 import static org.mockito.Matchers.isA;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.verify;
21 import akka.actor.ActorRef;
22 import akka.actor.ActorSelection;
23 import akka.actor.ActorSystem;
24 import akka.actor.Props;
25 import akka.dispatch.Futures;
26 import akka.testkit.JavaTestKit;
27 import com.google.common.collect.ImmutableMap;
28 import com.google.common.util.concurrent.CheckedFuture;
29 import com.typesafe.config.Config;
30 import com.typesafe.config.ConfigFactory;
31 import java.io.IOException;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.concurrent.TimeUnit;
35 import org.junit.AfterClass;
36 import org.junit.Before;
37 import org.junit.BeforeClass;
38 import org.mockito.ArgumentCaptor;
39 import org.mockito.ArgumentMatcher;
40 import org.mockito.Mock;
41 import org.mockito.Mockito;
42 import org.mockito.MockitoAnnotations;
43 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
44 import org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType;
45 import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
46 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
47 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
48 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.DataExists;
50 import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
51 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
52 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
53 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
54 import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
55 import org.opendaylight.controller.cluster.datastore.modification.Modification;
56 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
57 import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
58 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
59 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
60 import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
61 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
62 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
63 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
64 import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70 import scala.concurrent.Await;
71 import scala.concurrent.Future;
72 import scala.concurrent.duration.Duration;
73
74 /**
75  * Abstract base class for TransactionProxy unit tests.
76  *
77  * @author Thomas Pantelis
78  */
79 public abstract class AbstractTransactionProxyTest {
80     protected final Logger log = LoggerFactory.getLogger(getClass());
81
82     private static ActorSystem system;
83
84     private final Configuration configuration = new MockConfiguration();
85
86     @Mock
87     protected ActorContext mockActorContext;
88
89     private SchemaContext schemaContext;
90
91     @Mock
92     private ClusterWrapper mockClusterWrapper;
93
94     protected final String memberName = "mock-member";
95
96     protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().operationTimeoutInSeconds(2);
97
98     @BeforeClass
99     public static void setUpClass() throws IOException {
100
101         Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
102                 put("akka.actor.default-dispatcher.type",
103                         "akka.testkit.CallingThreadDispatcherConfigurator").build()).
104                 withFallback(ConfigFactory.load());
105         system = ActorSystem.create("test", config);
106     }
107
108     @AfterClass
109     public static void tearDownClass() throws IOException {
110         JavaTestKit.shutdownActorSystem(system);
111         system = null;
112     }
113
114     @Before
115     public void setUp(){
116         MockitoAnnotations.initMocks(this);
117
118         schemaContext = TestModel.createTestContext();
119
120         doReturn(getSystem()).when(mockActorContext).getActorSystem();
121         doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
122         doReturn(memberName).when(mockActorContext).getCurrentMemberName();
123         doReturn(schemaContext).when(mockActorContext).getSchemaContext();
124         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
125         doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
126         doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
127         doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
128
129         ShardStrategyFactory.setConfiguration(configuration);
130     }
131
132     protected ActorSystem getSystem() {
133         return system;
134     }
135
136     protected CreateTransaction eqCreateTransaction(final String memberName,
137             final TransactionType type) {
138         ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
139             @Override
140             public boolean matches(Object argument) {
141                 if(CreateTransaction.SERIALIZABLE_CLASS.equals(argument.getClass())) {
142                     CreateTransaction obj = CreateTransaction.fromSerializable(argument);
143                     return obj.getTransactionId().startsWith(memberName) &&
144                             obj.getTransactionType() == type.ordinal();
145                 }
146
147                 return false;
148             }
149         };
150
151         return argThat(matcher);
152     }
153
154     protected DataExists eqSerializedDataExists() {
155         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
156             @Override
157             public boolean matches(Object argument) {
158                 return DataExists.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
159                        DataExists.fromSerializable(argument).getPath().equals(TestModel.TEST_PATH);
160             }
161         };
162
163         return argThat(matcher);
164     }
165
166     protected DataExists eqDataExists() {
167         ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
168             @Override
169             public boolean matches(Object argument) {
170                 return (argument instanceof DataExists) &&
171                     ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
172             }
173         };
174
175         return argThat(matcher);
176     }
177
178     protected ReadData eqSerializedReadData() {
179         return eqSerializedReadData(TestModel.TEST_PATH);
180     }
181
182     protected ReadData eqSerializedReadData(final YangInstanceIdentifier path) {
183         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
184             @Override
185             public boolean matches(Object argument) {
186                 return ReadData.SERIALIZABLE_CLASS.equals(argument.getClass()) &&
187                        ReadData.fromSerializable(argument).getPath().equals(path);
188             }
189         };
190
191         return argThat(matcher);
192     }
193
194     protected ReadData eqReadData() {
195         ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
196             @Override
197             public boolean matches(Object argument) {
198                 return (argument instanceof ReadData) &&
199                     ((ReadData)argument).getPath().equals(TestModel.TEST_PATH);
200             }
201         };
202
203         return argThat(matcher);
204     }
205
206     protected Future<Object> readyTxReply(String path) {
207         return Futures.successful((Object)new ReadyTransactionReply(path));
208     }
209
210     protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data,
211             short transactionVersion) {
212         return Futures.successful(new ReadDataReply(data, transactionVersion).toSerializable());
213     }
214
215     protected Future<Object> readSerializedDataReply(NormalizedNode<?, ?> data) {
216         return readSerializedDataReply(data, DataStoreVersions.CURRENT_VERSION);
217     }
218
219     protected Future<ReadDataReply> readDataReply(NormalizedNode<?, ?> data) {
220         return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
221     }
222
223     protected Future<Object> dataExistsSerializedReply(boolean exists) {
224         return Futures.successful(DataExistsReply.create(exists).toSerializable());
225     }
226
227     protected Future<DataExistsReply> dataExistsReply(boolean exists) {
228         return Futures.successful(DataExistsReply.create(exists));
229     }
230
231     protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
232         return Futures.successful(new BatchedModificationsReply(count));
233     }
234
235     protected Future<Object> incompleteFuture() {
236         return mock(Future.class);
237     }
238
239     protected ActorSelection actorSelection(ActorRef actorRef) {
240         return getSystem().actorSelection(actorRef.path());
241     }
242
243     protected void expectBatchedModifications(ActorRef actorRef, int count) {
244         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
245                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
246     }
247
248     protected void expectBatchedModificationsReady(ActorRef actorRef) {
249         doReturn(readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
250                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
251     }
252
253     protected void expectBatchedModifications(int count) {
254         doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
255                 any(ActorSelection.class), isA(BatchedModifications.class));
256     }
257
258     protected void expectIncompleteBatchedModifications() {
259         doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
260                 any(ActorSelection.class), isA(BatchedModifications.class));
261     }
262
263     protected void expectFailedBatchedModifications(ActorRef actorRef) {
264         doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
265                 eq(actorSelection(actorRef)), isA(BatchedModifications.class));
266     }
267
268     protected CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){
269         return CreateTransactionReply.newBuilder()
270             .setTransactionActorPath(actorRef.path().toString())
271             .setTransactionId("txn-1")
272             .setMessageVersion(transactionVersion)
273             .build();
274     }
275
276     protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) {
277         ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
278         log.info("Created mock shard actor {}", actorRef);
279
280         doReturn(actorSystem.actorSelection(actorRef.path())).
281                 when(mockActorContext).actorSelection(actorRef.path().toString());
282
283         doReturn(Futures.successful(actorSystem.actorSelection(actorRef.path()))).
284                 when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
285
286         doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString());
287
288         doReturn(10).when(mockActorContext).getTransactionOutstandingOperationLimit();
289
290         return actorRef;
291     }
292
293     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
294             TransactionType type, int transactionVersion) {
295         ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem);
296
297         return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
298                 memberName, shardActorRef);
299     }
300
301     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
302             TransactionType type, int transactionVersion, String prefix, ActorRef shardActorRef) {
303
304         ActorRef txActorRef;
305         if(type == TransactionType.WRITE_ONLY && transactionVersion >= DataStoreVersions.LITHIUM_VERSION &&
306                 dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
307             txActorRef = shardActorRef;
308         } else {
309             txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
310             log.info("Created mock shard Tx actor {}", txActorRef);
311
312             doReturn(actorSystem.actorSelection(txActorRef.path())).
313             when(mockActorContext).actorSelection(txActorRef.path().toString());
314
315             doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
316             executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
317                     eqCreateTransaction(prefix, type));
318         }
319
320         return txActorRef;
321     }
322
323     protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) {
324         return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION);
325     }
326
327
328     protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
329             throws Throwable {
330
331         try {
332             future.checkedGet(5, TimeUnit.SECONDS);
333             fail("Expected ReadFailedException");
334         } catch(ReadFailedException e) {
335             throw e.getCause();
336         }
337     }
338
339     protected List<BatchedModifications> captureBatchedModifications(ActorRef actorRef) {
340         ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
341                 ArgumentCaptor.forClass(BatchedModifications.class);
342         verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
343                 eq(actorSelection(actorRef)), batchedModificationsCaptor.capture());
344
345         List<BatchedModifications> batchedModifications = filterCaptured(
346                 batchedModificationsCaptor, BatchedModifications.class);
347         return batchedModifications;
348     }
349
350     protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
351         List<T> captured = new ArrayList<>();
352         for(T c: captor.getAllValues()) {
353             if(type.isInstance(c)) {
354                 captured.add(c);
355             }
356         }
357
358         return captured;
359     }
360
361     protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) {
362         List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
363         assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
364
365         verifyBatchedModifications(batchedModifications.get(0), expIsReady, expected);
366     }
367
368     protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) {
369         assertEquals("Message type", BatchedModifications.class, message.getClass());
370         BatchedModifications batchedModifications = (BatchedModifications)message;
371         assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
372         assertEquals("isReady", expIsReady, batchedModifications.isReady());
373         for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
374             Modification actual = batchedModifications.getModifications().get(i);
375             assertEquals("Modification type", expected[i].getClass(), actual.getClass());
376             assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
377                     ((AbstractModification)actual).getPath());
378             if(actual instanceof WriteModification) {
379                 assertEquals("getData", ((WriteModification)expected[i]).getData(),
380                         ((WriteModification)actual).getData());
381             }
382         }
383     }
384
385     protected void verifyCohortFutures(ThreePhaseCommitCohortProxy proxy,
386             Object... expReplies) throws Exception {
387             assertEquals("getReadyOperationFutures size", expReplies.length,
388                     proxy.getCohortFutures().size());
389
390             int i = 0;
391             for( Future<ActorSelection> future: proxy.getCohortFutures()) {
392                 assertNotNull("Ready operation Future is null", future);
393
394                 Object expReply = expReplies[i++];
395                 if(expReply instanceof ActorSelection) {
396                     ActorSelection actual = Await.result(future, Duration.create(5, TimeUnit.SECONDS));
397                     assertEquals("Cohort actor path", expReply, actual);
398                 } else {
399                     try {
400                         Await.result(future, Duration.create(5, TimeUnit.SECONDS));
401                         fail("Expected exception from ready operation Future");
402                     } catch(Exception e) {
403                         assertTrue(String.format("Expected exception type %s. Actual %s",
404                                 expReply, e.getClass()), ((Class<?>)expReply).isInstance(e));
405                     }
406                 }
407             }
408         }
409 }