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