Do not use MoreExecutors.sameThreadExecutor()
[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.Collections;
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.modification.MutableCompositeModification;
40 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
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     @Before
74     public void setUp() {
75         InMemorySnapshotStore.clear();
76         InMemoryJournal.clear();
77     }
78
79     @After
80     public void tearDown() {
81         InMemorySnapshotStore.clear();
82         InMemoryJournal.clear();
83     }
84
85     protected DatastoreContext newDatastoreContext() {
86         return dataStoreContextBuilder.build();
87     }
88
89     protected Props newShardProps() {
90         return Shard.props(shardID, Collections.<String,String>emptyMap(),
91                 newDatastoreContext(), SCHEMA_CONTEXT);
92     }
93
94     protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
95         // Create the actor and wait for recovery complete.
96
97         final int nListEntries = listEntryKeys.size();
98
99         final CountDownLatch recoveryComplete = new CountDownLatch(1);
100
101         @SuppressWarnings("serial")
102         final
103         Creator<Shard> creator = new Creator<Shard>() {
104             @Override
105             public Shard create() throws Exception {
106                 return new Shard(shardID, Collections.<String,String>emptyMap(),
107                         newDatastoreContext(), SCHEMA_CONTEXT) {
108                     @Override
109                     protected void onRecoveryComplete() {
110                         try {
111                             super.onRecoveryComplete();
112                         } finally {
113                             recoveryComplete.countDown();
114                         }
115                     }
116                 };
117             }
118         };
119
120         final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
121                 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
122
123         assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
124
125         // Verify data in the data store.
126
127         final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
128         assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
129         assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
130                 outerList.getValue() instanceof Iterable);
131         for(final Object entry: (Iterable<?>) outerList.getValue()) {
132             assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
133                     entry instanceof MapEntryNode);
134             final MapEntryNode mapEntry = (MapEntryNode)entry;
135             final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
136                     mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
137             assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
138             final Object value = idLeaf.get().getValue();
139             assertTrue("Unexpected value for leaf "+ TestModel.ID_QNAME.getLocalName() + ": " + value,
140                     listEntryKeys.remove(value));
141         }
142
143         if(!listEntryKeys.isEmpty()) {
144             fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
145                     listEntryKeys);
146         }
147
148         assertEquals("Last log index", nListEntries,
149                 shard.underlyingActor().getShardMBean().getLastLogIndex());
150         assertEquals("Commit index", nListEntries,
151                 shard.underlyingActor().getShardMBean().getCommitIndex());
152         assertEquals("Last applied", nListEntries,
153                 shard.underlyingActor().getShardMBean().getLastApplied());
154
155         shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
156     }
157
158     protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
159         long lastApplied = -1;
160         for(int i = 0; i < 20 * 5; i++) {
161             lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
162             if(lastApplied == expectedValue) {
163                 return;
164             }
165             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
166         }
167
168         Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
169     }
170
171     protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
172             final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
173             final MutableCompositeModification modification) {
174         return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null);
175     }
176
177     protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
178             final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
179             final MutableCompositeModification modification,
180             final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
181
182         final ReadWriteShardDataTreeTransaction tx = dataStore.newReadWriteTransaction("setup-mock-" + cohortName, null);
183         tx.getSnapshot().write(path, data);
184         final ShardDataTreeCohort cohort = createDelegatingMockCohort(cohortName, dataStore.finishTransaction(tx), preCommit);
185
186         modification.addModification(new WriteModification(path, data));
187
188         return cohort;
189     }
190
191     protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
192             final ShardDataTreeCohort actual) {
193         return createDelegatingMockCohort(cohortName, actual, null);
194     }
195
196     protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
197             final ShardDataTreeCohort actual,
198             final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
199         final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, cohortName);
200
201         doAnswer(new Answer<ListenableFuture<Boolean>>() {
202             @Override
203             public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
204                 return actual.canCommit();
205             }
206         }).when(cohort).canCommit();
207
208         doAnswer(new Answer<ListenableFuture<Void>>() {
209             @Override
210             public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
211                 if(preCommit != null) {
212                     return preCommit.apply(actual);
213                 } else {
214                     return actual.preCommit();
215                 }
216             }
217         }).when(cohort).preCommit();
218
219         doAnswer(new Answer<ListenableFuture<Void>>() {
220             @Override
221             public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
222                 return actual.commit();
223             }
224         }).when(cohort).commit();
225
226         doAnswer(new Answer<ListenableFuture<Void>>() {
227             @Override
228             public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
229                 return actual.abort();
230             }
231         }).when(cohort).abort();
232
233         doAnswer(new Answer<DataTreeCandidateTip>() {
234             @Override
235             public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
236                 return actual.getCandidate();
237             }
238         }).when(cohort).getCandidate();
239
240         return cohort;
241     }
242
243     public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard, final YangInstanceIdentifier id)
244             throws ExecutionException, InterruptedException {
245         return shard.underlyingActor().getDataStore().readNode(id).orNull();
246     }
247
248     public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
249         return store.takeSnapshot().readNode(id).orNull();
250     }
251
252     public static void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
253             final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
254         writeToStore(shard.underlyingActor().getDataStore(), id, node);
255     }
256
257     public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
258             final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
259         final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
260
261         transaction.getSnapshot().write(id, node);
262         final ShardDataTreeCohort cohort = transaction.ready();
263         cohort.canCommit().get();
264         cohort.preCommit().get();
265         cohort.commit();
266     }
267
268     public static void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
269             final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
270         final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
271
272         transaction.getSnapshot().merge(id, node);
273         final ShardDataTreeCohort cohort = transaction.ready();
274         cohort.canCommit().get();
275         cohort.preCommit().get();
276         cohort.commit();
277     }
278
279     public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
280             final NormalizedNode<?,?> node) throws DataValidationFailedException {
281         final DataTreeModification transaction = store.takeSnapshot().newModification();
282
283         transaction.write(id, node);
284         transaction.ready();
285         store.validate(transaction);
286         final DataTreeCandidate candidate = store.prepare(transaction);
287         store.commit(candidate);
288     }
289
290     @SuppressWarnings("serial")
291     public static final class DelegatingShardCreator implements Creator<Shard> {
292         private final Creator<Shard> delegate;
293
294         DelegatingShardCreator(final Creator<Shard> delegate) {
295             this.delegate = delegate;
296         }
297
298         @Override
299         public Shard create() throws Exception {
300             return delegate.create();
301         }
302     }
303 }