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