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