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