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