2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore;
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;
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;
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;
59 * Abstract base for shard unit tests.
61 * @author Thomas Pantelis
63 public abstract class AbstractShardTest extends AbstractActorTest{
64 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
66 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
68 protected final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1")
69 .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build();
71 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
72 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
73 shardHeartbeatIntervalInMillis(100);
77 InMemorySnapshotStore.clear();
78 InMemoryJournal.clear();
82 public void tearDown() {
83 InMemorySnapshotStore.clear();
84 InMemoryJournal.clear();
87 protected DatastoreContext newDatastoreContext() {
88 return dataStoreContextBuilder.build();
91 protected Props newShardProps() {
92 return Shard.props(shardID, Collections.<String,String>emptyMap(),
93 newDatastoreContext(), SCHEMA_CONTEXT);
96 protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
97 // Create the actor and wait for recovery complete.
99 final int nListEntries = listEntryKeys.size();
101 final CountDownLatch recoveryComplete = new CountDownLatch(1);
103 @SuppressWarnings("serial")
105 Creator<Shard> creator = new Creator<Shard>() {
107 public Shard create() throws Exception {
108 return new Shard(shardID, Collections.<String,String>emptyMap(),
109 newDatastoreContext(), SCHEMA_CONTEXT) {
111 protected void onRecoveryComplete() {
113 super.onRecoveryComplete();
115 recoveryComplete.countDown();
122 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
123 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
125 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
127 // Verify data in the data store.
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));
145 if(!listEntryKeys.isEmpty()) {
146 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
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());
157 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
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) {
167 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
170 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
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);
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) {
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);
188 modification.addModification(new WriteModification(path, data));
193 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
194 final ShardDataTreeCohort actual) {
195 return createDelegatingMockCohort(cohortName, actual, null);
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);
203 doAnswer(new Answer<ListenableFuture<Boolean>>() {
205 public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
206 return actual.canCommit();
208 }).when(cohort).canCommit();
210 doAnswer(new Answer<ListenableFuture<Void>>() {
212 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
213 if(preCommit != null) {
214 return preCommit.apply(actual);
216 return actual.preCommit();
219 }).when(cohort).preCommit();
221 doAnswer(new Answer<ListenableFuture<Void>>() {
223 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
224 return actual.commit();
226 }).when(cohort).commit();
228 doAnswer(new Answer<ListenableFuture<Void>>() {
230 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
231 return actual.abort();
233 }).when(cohort).abort();
235 doAnswer(new Answer<DataTreeCandidateTip>() {
237 public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
238 return actual.getCandidate();
240 }).when(cohort).getCandidate();
245 public static NormalizedNode<?,?> readStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id)
246 throws ExecutionException, InterruptedException {
247 return readStore(shard.underlyingActor().getDataStore().getDataTree(), id);
250 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
251 final DataTreeSnapshot transaction = store.takeSnapshot();
253 final Optional<NormalizedNode<?, ?>> optional = transaction.readNode(id);
254 final NormalizedNode<?, ?> node = optional.isPresent()? optional.get() : null;
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);
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);
268 transaction.getSnapshot().write(id, node);
269 final ShardDataTreeCohort cohort = transaction.ready();
270 cohort.canCommit().get();
271 cohort.preCommit().get();
275 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
276 final NormalizedNode<?,?> node) throws DataValidationFailedException {
277 final DataTreeModification transaction = store.takeSnapshot().newModification();
279 transaction.write(id, node);
281 store.validate(transaction);
282 final DataTreeCandidate candidate = store.prepare(transaction);
283 store.commit(candidate);
286 @SuppressWarnings("serial")
287 public static final class DelegatingShardCreator implements Creator<Shard> {
288 private final Creator<Shard> delegate;
290 DelegatingShardCreator(final Creator<Shard> delegate) {
291 this.delegate = delegate;
295 public Shard create() throws Exception {
296 return delegate.create();