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.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;
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;
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 Shard.props(shardID, Collections.<ShardIdentifier,String>emptyMap(),
90 newDatastoreContext(), SCHEMA_CONTEXT);
93 protected void testRecovery(Set<Integer> listEntryKeys) throws Exception {
94 // Create the actor and wait for recovery complete.
96 int nListEntries = listEntryKeys.size();
98 final CountDownLatch recoveryComplete = new CountDownLatch(1);
100 @SuppressWarnings("serial")
101 Creator<Shard> creator = new Creator<Shard>() {
103 public Shard create() throws Exception {
104 return new Shard(shardID, Collections.<ShardIdentifier,String>emptyMap(),
105 newDatastoreContext(), SCHEMA_CONTEXT) {
107 protected void onRecoveryComplete() {
109 super.onRecoveryComplete();
111 recoveryComplete.countDown();
118 TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
119 Props.create(new DelegatingShardCreator(creator)), "testRecovery");
121 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
123 // Verify data in the data store.
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));
141 if(!listEntryKeys.isEmpty()) {
142 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
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());
153 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
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) {
162 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
165 assertEquals("Last log index", expectedValue, shard.underlyingActor().getShardMBean().getLastLogIndex());
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());
173 Optional<NormalizedNode<?, ?>> optional = read.checkedGet();
175 NormalizedNode<?, ?> normalizedNode = optional.get();
179 return normalizedNode;
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);
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) {
193 DOMStoreWriteTransaction tx = dataStore.newWriteOnlyTransaction();
194 tx.write(path, data);
195 DOMStoreThreePhaseCommitCohort cohort = createDelegatingMockCohort(cohortName, tx.ready(), preCommit);
197 modification.addModification(new WriteModification(path, data));
202 protected DOMStoreThreePhaseCommitCohort createDelegatingMockCohort(final String cohortName,
203 final DOMStoreThreePhaseCommitCohort actual) {
204 return createDelegatingMockCohort(cohortName, actual, null);
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);
212 doAnswer(new Answer<ListenableFuture<Boolean>>() {
214 public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
215 return actual.canCommit();
217 }).when(cohort).canCommit();
219 doAnswer(new Answer<ListenableFuture<Void>>() {
221 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
222 return actual.preCommit();
224 }).when(cohort).preCommit();
226 doAnswer(new Answer<ListenableFuture<Void>>() {
228 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
229 return actual.commit();
231 }).when(cohort).commit();
233 doAnswer(new Answer<ListenableFuture<Void>>() {
235 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
236 return actual.abort();
238 }).when(cohort).abort();
243 public static NormalizedNode<?,?> readStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id)
244 throws ExecutionException, InterruptedException {
245 return readStore(shard.underlyingActor().getDataStore(), id);
248 public static NormalizedNode<?,?> readStore(final InMemoryDOMDataStore store, final YangInstanceIdentifier id)
249 throws ExecutionException, InterruptedException {
250 DOMStoreReadTransaction transaction = store.newReadOnlyTransaction();
252 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> future =
253 transaction.read(id);
255 Optional<NormalizedNode<?, ?>> optional = future.get();
256 NormalizedNode<?, ?> node = optional.isPresent()? optional.get() : null;
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);
268 public static void writeToStore(final InMemoryDOMDataStore store, final YangInstanceIdentifier id,
269 final NormalizedNode<?,?> node) throws ExecutionException, InterruptedException {
270 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
272 transaction.write(id, node);
274 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
275 commitCohort.preCommit().get();
276 commitCohort.commit().get();
279 @SuppressWarnings("serial")
280 public static final class DelegatingShardCreator implements Creator<Shard> {
281 private final Creator<Shard> delegate;
283 DelegatingShardCreator(final Creator<Shard> delegate) {
284 this.delegate = delegate;
288 public Shard create() throws Exception {
289 return delegate.create();