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