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