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;
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;
27 import java.util.concurrent.CountDownLatch;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.atomic.AtomicInteger;
31 import org.junit.After;
32 import org.junit.Assert;
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.raft.utils.InMemoryJournal;
41 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
42 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
45 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
46 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
49 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
50 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
51 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
52 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 * Abstract base for shard unit tests.
58 * @author Thomas Pantelis
60 public abstract class AbstractShardTest extends AbstractActorTest{
61 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
63 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
65 protected final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1")
66 .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build();
68 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
69 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
70 shardHeartbeatIntervalInMillis(100);
74 InMemorySnapshotStore.clear();
75 InMemoryJournal.clear();
79 public void tearDown() {
80 InMemorySnapshotStore.clear();
81 InMemoryJournal.clear();
84 protected DatastoreContext newDatastoreContext() {
85 return dataStoreContextBuilder.build();
88 protected Props newShardProps() {
89 return newShardBuilder().props();
92 protected Shard.Builder newShardBuilder() {
93 return Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).schemaContext(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(newShardBuilder()) {
110 protected void onRecoveryComplete() {
112 super.onRecoveryComplete();
114 recoveryComplete.countDown();
121 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
122 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
124 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
126 // Verify data in the data store.
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));
144 if(!listEntryKeys.isEmpty()) {
145 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
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());
156 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
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) {
166 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
169 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
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);
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) {
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);
187 modification.addModification(new WriteModification(path, data));
192 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
193 final ShardDataTreeCohort actual) {
194 return createDelegatingMockCohort(cohortName, actual, null);
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);
202 doAnswer(new Answer<ListenableFuture<Boolean>>() {
204 public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
205 return actual.canCommit();
207 }).when(cohort).canCommit();
209 doAnswer(new Answer<ListenableFuture<Void>>() {
211 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
212 if(preCommit != null) {
213 return preCommit.apply(actual);
215 return actual.preCommit();
218 }).when(cohort).preCommit();
220 doAnswer(new Answer<ListenableFuture<Void>>() {
222 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
223 return actual.commit();
225 }).when(cohort).commit();
227 doAnswer(new Answer<ListenableFuture<Void>>() {
229 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
230 return actual.abort();
232 }).when(cohort).abort();
234 doAnswer(new Answer<DataTreeCandidateTip>() {
236 public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
237 return actual.getCandidate();
239 }).when(cohort).getCandidate();
244 public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard, final YangInstanceIdentifier id)
245 throws ExecutionException, InterruptedException {
246 return shard.underlyingActor().getDataStore().readNode(id).orNull();
249 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
250 return store.takeSnapshot().readNode(id).orNull();
253 public static void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
254 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
255 writeToStore(shard.underlyingActor().getDataStore(), id, node);
258 public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
259 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
260 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
262 transaction.getSnapshot().write(id, node);
263 final ShardDataTreeCohort cohort = transaction.ready();
264 cohort.canCommit().get();
265 cohort.preCommit().get();
269 public static void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
270 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
271 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
273 transaction.getSnapshot().merge(id, node);
274 final ShardDataTreeCohort cohort = transaction.ready();
275 cohort.canCommit().get();
276 cohort.preCommit().get();
280 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
281 final NormalizedNode<?,?> node) throws DataValidationFailedException {
282 final DataTreeModification transaction = store.takeSnapshot().newModification();
284 transaction.write(id, node);
286 store.validate(transaction);
287 final DataTreeCandidate candidate = store.prepare(transaction);
288 store.commit(candidate);
291 @SuppressWarnings("serial")
292 public static final class DelegatingShardCreator implements Creator<Shard> {
293 private final Creator<Shard> delegate;
295 DelegatingShardCreator(final Creator<Shard> delegate) {
296 this.delegate = delegate;
300 public Shard create() throws Exception {
301 return delegate.create();