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