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