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 static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
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;
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.Assert;
34 import org.junit.Before;
35 import org.mockito.invocation.InvocationOnMock;
36 import org.mockito.stubbing.Answer;
37 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
38 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
39 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
40 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
41 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
42 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
43 import org.opendaylight.controller.cluster.raft.TestActorFactory;
44 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
45 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
46 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
53 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
54 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
55 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
56 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
57 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 * Abstract base for shard unit tests.
62 * @author Thomas Pantelis
64 public abstract class AbstractShardTest extends AbstractActorTest{
65 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
67 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
69 protected final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1")
70 .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build();
72 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
73 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
74 shardHeartbeatIntervalInMillis(100);
76 protected final TestActorFactory actorFactory = new TestActorFactory(getSystem());
80 InMemorySnapshotStore.clear();
81 InMemoryJournal.clear();
85 public void tearDown() {
86 InMemorySnapshotStore.clear();
87 InMemoryJournal.clear();
91 protected DatastoreContext newDatastoreContext() {
92 return dataStoreContextBuilder.build();
95 protected Props newShardProps() {
96 return newShardBuilder().props();
99 protected Shard.Builder newShardBuilder() {
100 return Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).schemaContext(SCHEMA_CONTEXT);
103 protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
104 // Create the actor and wait for recovery complete.
106 final int nListEntries = listEntryKeys.size();
108 final CountDownLatch recoveryComplete = new CountDownLatch(1);
110 @SuppressWarnings("serial")
112 Creator<Shard> creator = new Creator<Shard>() {
114 public Shard create() throws Exception {
115 return new Shard(newShardBuilder()) {
117 protected void onRecoveryComplete() {
119 super.onRecoveryComplete();
121 recoveryComplete.countDown();
128 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
129 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
131 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
133 // Verify data in the data store.
135 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
136 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
137 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
138 outerList.getValue() instanceof Iterable);
139 for(final Object entry: (Iterable<?>) outerList.getValue()) {
140 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
141 entry instanceof MapEntryNode);
142 final MapEntryNode mapEntry = (MapEntryNode)entry;
143 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
144 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
145 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
146 final Object value = idLeaf.get().getValue();
147 assertTrue("Unexpected value for leaf "+ TestModel.ID_QNAME.getLocalName() + ": " + value,
148 listEntryKeys.remove(value));
151 if(!listEntryKeys.isEmpty()) {
152 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
156 assertEquals("Last log index", nListEntries,
157 shard.underlyingActor().getShardMBean().getLastLogIndex());
158 assertEquals("Commit index", nListEntries,
159 shard.underlyingActor().getShardMBean().getCommitIndex());
160 assertEquals("Last applied", nListEntries,
161 shard.underlyingActor().getShardMBean().getLastApplied());
163 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
166 protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
167 long lastApplied = -1;
168 for(int i = 0; i < 20 * 5; i++) {
169 lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
170 if(lastApplied == expectedValue) {
173 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
176 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
179 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
180 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
181 final MutableCompositeModification modification) {
182 return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null);
185 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
186 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
187 final MutableCompositeModification modification,
188 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
190 final ReadWriteShardDataTreeTransaction tx = dataStore.newReadWriteTransaction("setup-mock-" + cohortName, null);
191 tx.getSnapshot().write(path, data);
192 final ShardDataTreeCohort cohort = createDelegatingMockCohort(cohortName, dataStore.finishTransaction(tx), preCommit);
194 modification.addModification(new WriteModification(path, data));
199 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
200 final ShardDataTreeCohort actual) {
201 return createDelegatingMockCohort(cohortName, actual, null);
204 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
205 final ShardDataTreeCohort actual,
206 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
207 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, cohortName);
209 doAnswer(new Answer<ListenableFuture<Boolean>>() {
211 public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
212 return actual.canCommit();
214 }).when(cohort).canCommit();
216 doAnswer(new Answer<ListenableFuture<Void>>() {
218 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
219 if(preCommit != null) {
220 return preCommit.apply(actual);
222 return actual.preCommit();
225 }).when(cohort).preCommit();
227 doAnswer(new Answer<ListenableFuture<Void>>() {
229 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
230 return actual.commit();
232 }).when(cohort).commit();
234 doAnswer(new Answer<ListenableFuture<Void>>() {
236 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
237 return actual.abort();
239 }).when(cohort).abort();
241 doAnswer(new Answer<DataTreeCandidateTip>() {
243 public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
244 return actual.getCandidate();
246 }).when(cohort).getCandidate();
251 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
252 String transactionID,
253 MutableCompositeModification modification,
254 boolean doCommitOnReady) {
255 if(remoteReadWriteTransaction){
256 return new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, cohort, true, doCommitOnReady);
258 setupCohortDecorator(shard, cohort);
259 return prepareBatchedModifications(transactionID, modification, doCommitOnReady);
263 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
264 String transactionID,
265 MutableCompositeModification modification) {
266 return prepareReadyTransactionMessage(remoteReadWriteTransaction, shard, cohort, transactionID, modification, false);
269 protected void setupCohortDecorator(Shard shard, final ShardDataTreeCohort cohort) {
270 shard.getCommitCoordinator().setCohortDecorator(new ShardCommitCoordinator.CohortDecorator() {
272 public ShardDataTreeCohort decorate(String transactionID, ShardDataTreeCohort actual) {
278 protected BatchedModifications prepareBatchedModifications(String transactionID,
279 MutableCompositeModification modification) {
280 return prepareBatchedModifications(transactionID, modification, false);
283 private BatchedModifications prepareBatchedModifications(String transactionID,
284 MutableCompositeModification modification,
285 boolean doCommitOnReady) {
286 final BatchedModifications batchedModifications = new BatchedModifications(transactionID, CURRENT_VERSION, null);
287 batchedModifications.addModification(modification);
288 batchedModifications.setReady(true);
289 batchedModifications.setDoCommitOnReady(doCommitOnReady);
290 batchedModifications.setTotalMessagesSent(1);
291 return batchedModifications;
295 public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard, final YangInstanceIdentifier id)
296 throws ExecutionException, InterruptedException {
297 return shard.underlyingActor().getDataStore().readNode(id).orNull();
300 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
301 return store.takeSnapshot().readNode(id).orNull();
304 public static void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
305 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
306 writeToStore(shard.underlyingActor().getDataStore(), id, node);
309 public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
310 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
311 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
313 transaction.getSnapshot().write(id, node);
314 final ShardDataTreeCohort cohort = transaction.ready();
315 cohort.canCommit().get();
316 cohort.preCommit().get();
320 public static void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
321 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
322 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
324 transaction.getSnapshot().merge(id, node);
325 final ShardDataTreeCohort cohort = transaction.ready();
326 cohort.canCommit().get();
327 cohort.preCommit().get();
331 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
332 final NormalizedNode<?,?> node) throws DataValidationFailedException {
333 final DataTreeModification transaction = store.takeSnapshot().newModification();
335 transaction.write(id, node);
337 store.validate(transaction);
338 final DataTreeCandidate candidate = store.prepare(transaction);
339 store.commit(candidate);
342 @SuppressWarnings("serial")
343 public static final class DelegatingShardCreator implements Creator<Shard> {
344 private final Creator<Shard> delegate;
346 DelegatingShardCreator(final Creator<Shard> delegate) {
347 this.delegate = delegate;
351 public Shard create() throws Exception {
352 return delegate.create();