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.CheckedFuture;
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.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;
62 * Abstract base for shard unit tests.
64 * @author Thomas Pantelis
66 public abstract class AbstractShardTest extends AbstractActorTest{
67 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
69 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
71 protected final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1")
72 .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build();
74 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
75 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
76 shardHeartbeatIntervalInMillis(100);
80 InMemorySnapshotStore.clear();
81 InMemoryJournal.clear();
85 public void tearDown() {
86 InMemorySnapshotStore.clear();
87 InMemoryJournal.clear();
90 protected DatastoreContext newDatastoreContext() {
91 return dataStoreContextBuilder.build();
94 protected Props newShardProps() {
95 return Shard.props(shardID, Collections.<String,String>emptyMap(),
96 newDatastoreContext(), SCHEMA_CONTEXT);
99 protected void testRecovery(Set<Integer> listEntryKeys) throws Exception {
100 // Create the actor and wait for recovery complete.
102 int nListEntries = listEntryKeys.size();
104 final CountDownLatch recoveryComplete = new CountDownLatch(1);
106 @SuppressWarnings("serial")
107 Creator<Shard> creator = new Creator<Shard>() {
109 public Shard create() throws Exception {
110 return new Shard(shardID, Collections.<String,String>emptyMap(),
111 newDatastoreContext(), SCHEMA_CONTEXT) {
113 protected void onRecoveryComplete() {
115 super.onRecoveryComplete();
117 recoveryComplete.countDown();
124 TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
125 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
127 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
129 // Verify data in the data store.
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));
147 if(!listEntryKeys.isEmpty()) {
148 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
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());
159 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
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) {
169 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
172 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
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());
180 Optional<NormalizedNode<?, ?>> optional = read.checkedGet();
182 NormalizedNode<?, ?> normalizedNode = optional.get();
186 return normalizedNode;
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);
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) {
200 ReadWriteShardDataTreeTransaction tx = dataStore.newReadWriteTransaction("setup-mock-" + cohortName, null);
201 tx.getSnapshot().write(path, data);
202 DOMStoreThreePhaseCommitCohort cohort = createDelegatingMockCohort(cohortName, dataStore.finishTransaction(tx), preCommit);
204 modification.addModification(new WriteModification(path, data));
209 protected DOMStoreThreePhaseCommitCohort createDelegatingMockCohort(final String cohortName,
210 final DOMStoreThreePhaseCommitCohort actual) {
211 return createDelegatingMockCohort(cohortName, actual, null);
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);
219 doAnswer(new Answer<ListenableFuture<Boolean>>() {
221 public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
222 return actual.canCommit();
224 }).when(cohort).canCommit();
226 doAnswer(new Answer<ListenableFuture<Void>>() {
228 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
229 if(preCommit != null) {
230 return preCommit.apply(actual);
232 return actual.preCommit();
235 }).when(cohort).preCommit();
237 doAnswer(new Answer<ListenableFuture<Void>>() {
239 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
240 return actual.commit();
242 }).when(cohort).commit();
244 doAnswer(new Answer<ListenableFuture<Void>>() {
246 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
247 return actual.abort();
249 }).when(cohort).abort();
254 public static NormalizedNode<?,?> readStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id)
255 throws ExecutionException, InterruptedException {
256 return readStore(shard.underlyingActor().getDataStore().getDataTree(), id);
259 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
260 DataTreeSnapshot transaction = store.takeSnapshot();
262 Optional<NormalizedNode<?, ?>> optional = transaction.readNode(id);
263 NormalizedNode<?, ?> node = optional.isPresent()? optional.get() : null;
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);
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);
277 transaction.getSnapshot().write(id, node);
278 DOMStoreThreePhaseCommitCohort cohort = transaction.ready();
279 cohort.canCommit().get();
280 cohort.preCommit().get();
284 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
285 final NormalizedNode<?,?> node) throws DataValidationFailedException {
286 DataTreeModification transaction = store.takeSnapshot().newModification();
288 transaction.write(id, node);
290 store.validate(transaction);
291 final DataTreeCandidate candidate = store.prepare(transaction);
292 store.commit(candidate);
295 @SuppressWarnings("serial")
296 public static final class DelegatingShardCreator implements Creator<Shard> {
297 private final Creator<Shard> delegate;
299 DelegatingShardCreator(final Creator<Shard> delegate) {
300 this.delegate = delegate;
304 public Shard create() throws Exception {
305 return delegate.create();