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