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