Fix intermittent ShardTest failures
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / AbstractShardTest.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.Mockito.doAnswer;
16 import static org.mockito.Mockito.doNothing;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
20 import akka.actor.ActorRef;
21 import akka.actor.PoisonPill;
22 import akka.actor.Props;
23 import akka.dispatch.Dispatchers;
24 import akka.japi.Creator;
25 import akka.pattern.Patterns;
26 import akka.testkit.TestActorRef;
27 import akka.util.Timeout;
28 import com.google.common.base.Function;
29 import com.google.common.base.Optional;
30 import com.google.common.util.concurrent.ListenableFuture;
31 import com.google.common.util.concurrent.Uninterruptibles;
32 import java.util.Set;
33 import java.util.concurrent.CountDownLatch;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.TimeoutException;
37 import java.util.concurrent.atomic.AtomicInteger;
38 import org.junit.After;
39 import org.junit.Assert;
40 import org.junit.Before;
41 import org.mockito.invocation.InvocationOnMock;
42 import org.mockito.stubbing.Answer;
43 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
44 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
45 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
46 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
47 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
48 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
49 import org.opendaylight.controller.cluster.raft.TestActorFactory;
50 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
51 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
52 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
55 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
56 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
59 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
60 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import scala.concurrent.Await;
65 import scala.concurrent.Future;
66 import scala.concurrent.duration.Duration;
67
68 /**
69  * Abstract base for shard unit tests.
70  *
71  * @author Thomas Pantelis
72  */
73 public abstract class AbstractShardTest extends AbstractActorTest{
74     protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
75
76     private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
77
78     protected final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1")
79             .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build();
80
81     protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
82             shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
83             shardHeartbeatIntervalInMillis(100);
84
85     protected final TestActorFactory actorFactory = new TestActorFactory(getSystem());
86
87     @Before
88     public void setUp() {
89         InMemorySnapshotStore.clear();
90         InMemoryJournal.clear();
91     }
92
93     @After
94     public void tearDown() {
95         InMemorySnapshotStore.clear();
96         InMemoryJournal.clear();
97         actorFactory.close();
98     }
99
100     protected DatastoreContext newDatastoreContext() {
101         return dataStoreContextBuilder.build();
102     }
103
104     protected Props newShardProps() {
105         return newShardBuilder().props();
106     }
107
108     protected Shard.Builder newShardBuilder() {
109         return Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).schemaContext(SCHEMA_CONTEXT);
110     }
111
112     protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
113         // Create the actor and wait for recovery complete.
114
115         final int nListEntries = listEntryKeys.size();
116
117         final CountDownLatch recoveryComplete = new CountDownLatch(1);
118
119         @SuppressWarnings("serial")
120         final
121         Creator<Shard> creator = new Creator<Shard>() {
122             @Override
123             public Shard create() throws Exception {
124                 return new Shard(newShardBuilder()) {
125                     @Override
126                     protected void onRecoveryComplete() {
127                         try {
128                             super.onRecoveryComplete();
129                         } finally {
130                             recoveryComplete.countDown();
131                         }
132                     }
133                 };
134             }
135         };
136
137         final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
138                 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
139
140         assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
141
142         // Verify data in the data store.
143
144         final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
145         assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
146         assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
147                 outerList.getValue() instanceof Iterable);
148         for(final Object entry: (Iterable<?>) outerList.getValue()) {
149             assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
150                     entry instanceof MapEntryNode);
151             final MapEntryNode mapEntry = (MapEntryNode)entry;
152             final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
153                     mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
154             assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
155             final Object value = idLeaf.get().getValue();
156             assertTrue("Unexpected value for leaf "+ TestModel.ID_QNAME.getLocalName() + ": " + value,
157                     listEntryKeys.remove(value));
158         }
159
160         if(!listEntryKeys.isEmpty()) {
161             fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
162                     listEntryKeys);
163         }
164
165         assertEquals("Last log index", nListEntries,
166                 shard.underlyingActor().getShardMBean().getLastLogIndex());
167         assertEquals("Commit index", nListEntries,
168                 shard.underlyingActor().getShardMBean().getCommitIndex());
169         assertEquals("Last applied", nListEntries,
170                 shard.underlyingActor().getShardMBean().getLastApplied());
171
172         shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
173     }
174
175     protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
176         long lastApplied = -1;
177         for(int i = 0; i < 20 * 5; i++) {
178             lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
179             if(lastApplied == expectedValue) {
180                 return;
181             }
182             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
183         }
184
185         Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
186     }
187
188     protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
189             final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
190             final MutableCompositeModification modification) {
191         return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null);
192     }
193
194     protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
195             final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
196             final MutableCompositeModification modification,
197             final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
198
199         final ReadWriteShardDataTreeTransaction tx = dataStore.newReadWriteTransaction("setup-mock-" + cohortName, null);
200         tx.getSnapshot().write(path, data);
201         final ShardDataTreeCohort cohort = createDelegatingMockCohort(cohortName, dataStore.finishTransaction(tx), preCommit);
202
203         modification.addModification(new WriteModification(path, data));
204
205         return cohort;
206     }
207
208     protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
209             final ShardDataTreeCohort actual) {
210         return createDelegatingMockCohort(cohortName, actual, null);
211     }
212
213     protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
214             final ShardDataTreeCohort actual,
215             final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
216         final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, cohortName);
217
218         doAnswer(new Answer<ListenableFuture<Boolean>>() {
219             @Override
220             public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
221                 return actual.canCommit();
222             }
223         }).when(cohort).canCommit();
224
225         doAnswer(new Answer<ListenableFuture<Void>>() {
226             @Override
227             public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
228                 if(preCommit != null) {
229                     return preCommit.apply(actual);
230                 } else {
231                     return actual.preCommit();
232                 }
233             }
234         }).when(cohort).preCommit();
235
236         doAnswer(new Answer<ListenableFuture<Void>>() {
237             @Override
238             public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
239                 return actual.commit();
240             }
241         }).when(cohort).commit();
242
243         doAnswer(new Answer<ListenableFuture<Void>>() {
244             @Override
245             public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
246                 return actual.abort();
247             }
248         }).when(cohort).abort();
249
250         doAnswer(new Answer<DataTreeCandidateTip>() {
251             @Override
252             public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
253                 return actual.getCandidate();
254             }
255         }).when(cohort).getCandidate();
256
257         return cohort;
258     }
259
260     protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
261                                                                   String transactionID,
262                                                                   MutableCompositeModification modification,
263                                                                   boolean doCommitOnReady) {
264         if(remoteReadWriteTransaction){
265             return prepareForwardedReadyTransaction(cohort, transactionID, CURRENT_VERSION,
266                     doCommitOnReady);
267         } else {
268             setupCohortDecorator(shard, cohort);
269             return prepareBatchedModifications(transactionID, modification, doCommitOnReady);
270         }
271     }
272
273     static ShardDataTreeTransactionParent newShardDataTreeTransactionParent(ShardDataTreeCohort cohort) {
274         ShardDataTreeTransactionParent mockParent = mock(ShardDataTreeTransactionParent.class);
275         doReturn(cohort).when(mockParent).finishTransaction(any(ReadWriteShardDataTreeTransaction.class));
276         doNothing().when(mockParent).abortTransaction(any(AbstractShardDataTreeTransaction.class));
277         return mockParent;
278     }
279
280     protected ForwardedReadyTransaction prepareForwardedReadyTransaction(ShardDataTreeCohort cohort,
281             String transactionID, short version, boolean doCommitOnReady) {
282         return new ForwardedReadyTransaction(transactionID, version,
283                 new ReadWriteShardDataTreeTransaction(newShardDataTreeTransactionParent(cohort), transactionID,
284                         mock(DataTreeModification.class)), true, doCommitOnReady);
285     }
286
287     protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
288                                                                   String transactionID,
289                                                                   MutableCompositeModification modification) {
290         return prepareReadyTransactionMessage(remoteReadWriteTransaction, shard, cohort, transactionID, modification, false);
291     }
292
293     protected void setupCohortDecorator(Shard shard, final ShardDataTreeCohort cohort) {
294         shard.getCommitCoordinator().setCohortDecorator(new ShardCommitCoordinator.CohortDecorator() {
295             @Override
296             public ShardDataTreeCohort decorate(String transactionID, ShardDataTreeCohort actual) {
297                 return cohort;
298             }
299         });
300     }
301
302     protected BatchedModifications prepareBatchedModifications(String transactionID,
303                                                                MutableCompositeModification modification) {
304         return prepareBatchedModifications(transactionID, modification, false);
305     }
306
307     private static BatchedModifications prepareBatchedModifications(String transactionID,
308                                                              MutableCompositeModification modification,
309                                                              boolean doCommitOnReady) {
310         final BatchedModifications batchedModifications = new BatchedModifications(transactionID, CURRENT_VERSION, null);
311         batchedModifications.addModification(modification);
312         batchedModifications.setReady(true);
313         batchedModifications.setDoCommitOnReady(doCommitOnReady);
314         batchedModifications.setTotalMessagesSent(1);
315         return batchedModifications;
316     }
317
318
319     public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard, final YangInstanceIdentifier id)
320             throws ExecutionException, InterruptedException {
321         return shard.underlyingActor().getDataStore().readNode(id).orNull();
322     }
323
324     public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
325         return store.takeSnapshot().readNode(id).orNull();
326     }
327
328     public static void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
329             final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
330         Future<Object> future = Patterns.ask(shard, newBatchedModifications("tx", id, node, true, true, 1),
331                 new Timeout(5, TimeUnit.SECONDS));
332         try {
333             Await.ready(future, Duration.create(5, TimeUnit.SECONDS));
334         } catch(TimeoutException e) {
335             throw new ExecutionException(e);
336         }
337     }
338
339     static BatchedModifications newBatchedModifications(final String transactionID, final YangInstanceIdentifier path,
340         final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady, final int messagesSent) {
341         return newBatchedModifications(transactionID, null, path, data, ready, doCommitOnReady, messagesSent);
342     }
343
344     static BatchedModifications newBatchedModifications(final String transactionID, final String transactionChainID,
345             final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady,
346             final int messagesSent) {
347         final BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, transactionChainID);
348         batched.addModification(new WriteModification(path, data));
349         batched.setReady(ready);
350         batched.setDoCommitOnReady(doCommitOnReady);
351         batched.setTotalMessagesSent(messagesSent);
352         return batched;
353     }
354
355     public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
356             final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
357         final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
358
359         transaction.getSnapshot().write(id, node);
360         final ShardDataTreeCohort cohort = transaction.ready();
361         cohort.canCommit().get();
362         cohort.preCommit().get();
363         cohort.commit();
364     }
365
366     public static void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
367             final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
368         final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
369
370         transaction.getSnapshot().merge(id, node);
371         final ShardDataTreeCohort cohort = transaction.ready();
372         cohort.canCommit().get();
373         cohort.preCommit().get();
374         cohort.commit();
375     }
376
377     public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
378             final NormalizedNode<?,?> node) throws DataValidationFailedException {
379         final DataTreeModification transaction = store.takeSnapshot().newModification();
380
381         transaction.write(id, node);
382         transaction.ready();
383         store.validate(transaction);
384         final DataTreeCandidate candidate = store.prepare(transaction);
385         store.commit(candidate);
386     }
387
388     @SuppressWarnings("serial")
389     public static final class DelegatingShardCreator implements Creator<Shard> {
390         private final Creator<Shard> delegate;
391
392         DelegatingShardCreator(final Creator<Shard> delegate) {
393             this.delegate = delegate;
394         }
395
396         @Override
397         public Shard create() throws Exception {
398             return delegate.create();
399         }
400     }
401 }