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