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