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.Matchers.any;
15 import static org.mockito.Mockito.doAnswer;
16 import static org.mockito.Mockito.doNothing;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
20 import akka.actor.ActorRef;
21 import akka.actor.PoisonPill;
22 import akka.actor.Props;
23 import akka.dispatch.Dispatchers;
24 import akka.japi.Creator;
25 import akka.pattern.Patterns;
26 import akka.testkit.TestActorRef;
27 import akka.util.Timeout;
28 import com.google.common.base.Function;
29 import com.google.common.base.Optional;
30 import com.google.common.util.concurrent.ListenableFuture;
31 import com.google.common.util.concurrent.Uninterruptibles;
33 import java.util.concurrent.CountDownLatch;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.TimeoutException;
37 import java.util.concurrent.atomic.AtomicInteger;
38 import org.junit.After;
39 import org.junit.Assert;
40 import org.junit.Before;
41 import org.mockito.invocation.InvocationOnMock;
42 import org.mockito.stubbing.Answer;
43 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
44 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
45 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
46 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
47 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
48 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
49 import org.opendaylight.controller.cluster.raft.TestActorFactory;
50 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
51 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
52 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
55 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
56 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
59 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
60 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import scala.concurrent.Await;
65 import scala.concurrent.Future;
66 import scala.concurrent.duration.Duration;
69 * Abstract base for shard unit tests.
71 * @author Thomas Pantelis
73 public abstract class AbstractShardTest extends AbstractActorTest{
74 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
76 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
78 protected final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1")
79 .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build();
81 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
82 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
83 shardHeartbeatIntervalInMillis(100);
85 protected final TestActorFactory actorFactory = new TestActorFactory(getSystem());
89 InMemorySnapshotStore.clear();
90 InMemoryJournal.clear();
94 public void tearDown() {
95 InMemorySnapshotStore.clear();
96 InMemoryJournal.clear();
100 protected DatastoreContext newDatastoreContext() {
101 return dataStoreContextBuilder.build();
104 protected Props newShardProps() {
105 return newShardBuilder().props();
108 protected Shard.Builder newShardBuilder() {
109 return Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).schemaContext(SCHEMA_CONTEXT);
112 protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
113 // Create the actor and wait for recovery complete.
115 final int nListEntries = listEntryKeys.size();
117 final CountDownLatch recoveryComplete = new CountDownLatch(1);
119 @SuppressWarnings("serial")
121 Creator<Shard> creator = new Creator<Shard>() {
123 public Shard create() throws Exception {
124 return new Shard(newShardBuilder()) {
126 protected void onRecoveryComplete() {
128 super.onRecoveryComplete();
130 recoveryComplete.countDown();
137 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
138 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
140 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
142 // Verify data in the data store.
144 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
145 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
146 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
147 outerList.getValue() instanceof Iterable);
148 for(final Object entry: (Iterable<?>) outerList.getValue()) {
149 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
150 entry instanceof MapEntryNode);
151 final MapEntryNode mapEntry = (MapEntryNode)entry;
152 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
153 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
154 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
155 final Object value = idLeaf.get().getValue();
156 assertTrue("Unexpected value for leaf "+ TestModel.ID_QNAME.getLocalName() + ": " + value,
157 listEntryKeys.remove(value));
160 if(!listEntryKeys.isEmpty()) {
161 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
165 assertEquals("Last log index", nListEntries,
166 shard.underlyingActor().getShardMBean().getLastLogIndex());
167 assertEquals("Commit index", nListEntries,
168 shard.underlyingActor().getShardMBean().getCommitIndex());
169 assertEquals("Last applied", nListEntries,
170 shard.underlyingActor().getShardMBean().getLastApplied());
172 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
175 protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
176 long lastApplied = -1;
177 for(int i = 0; i < 20 * 5; i++) {
178 lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
179 if(lastApplied == expectedValue) {
182 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
185 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
188 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
189 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
190 final MutableCompositeModification modification) {
191 return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null);
194 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
195 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
196 final MutableCompositeModification modification,
197 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
199 final ReadWriteShardDataTreeTransaction tx = dataStore.newReadWriteTransaction("setup-mock-" + cohortName, null);
200 tx.getSnapshot().write(path, data);
201 final ShardDataTreeCohort cohort = createDelegatingMockCohort(cohortName, dataStore.finishTransaction(tx), preCommit);
203 modification.addModification(new WriteModification(path, data));
208 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
209 final ShardDataTreeCohort actual) {
210 return createDelegatingMockCohort(cohortName, actual, null);
213 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
214 final ShardDataTreeCohort actual,
215 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
216 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, cohortName);
218 doAnswer(new Answer<ListenableFuture<Boolean>>() {
220 public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
221 return actual.canCommit();
223 }).when(cohort).canCommit();
225 doAnswer(new Answer<ListenableFuture<Void>>() {
227 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
228 if(preCommit != null) {
229 return preCommit.apply(actual);
231 return actual.preCommit();
234 }).when(cohort).preCommit();
236 doAnswer(new Answer<ListenableFuture<Void>>() {
238 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
239 return actual.commit();
241 }).when(cohort).commit();
243 doAnswer(new Answer<ListenableFuture<Void>>() {
245 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
246 return actual.abort();
248 }).when(cohort).abort();
250 doAnswer(new Answer<DataTreeCandidateTip>() {
252 public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
253 return actual.getCandidate();
255 }).when(cohort).getCandidate();
260 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
261 String transactionID,
262 MutableCompositeModification modification,
263 boolean doCommitOnReady) {
264 if(remoteReadWriteTransaction){
265 return prepareForwardedReadyTransaction(cohort, transactionID, CURRENT_VERSION,
268 setupCohortDecorator(shard, cohort);
269 return prepareBatchedModifications(transactionID, modification, doCommitOnReady);
273 static ShardDataTreeTransactionParent newShardDataTreeTransactionParent(ShardDataTreeCohort cohort) {
274 ShardDataTreeTransactionParent mockParent = mock(ShardDataTreeTransactionParent.class);
275 doReturn(cohort).when(mockParent).finishTransaction(any(ReadWriteShardDataTreeTransaction.class));
276 doNothing().when(mockParent).abortTransaction(any(AbstractShardDataTreeTransaction.class));
280 protected ForwardedReadyTransaction prepareForwardedReadyTransaction(ShardDataTreeCohort cohort,
281 String transactionID, short version, boolean doCommitOnReady) {
282 return new ForwardedReadyTransaction(transactionID, version,
283 new ReadWriteShardDataTreeTransaction(newShardDataTreeTransactionParent(cohort), transactionID,
284 mock(DataTreeModification.class)), true, doCommitOnReady);
287 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
288 String transactionID,
289 MutableCompositeModification modification) {
290 return prepareReadyTransactionMessage(remoteReadWriteTransaction, shard, cohort, transactionID, modification, false);
293 protected void setupCohortDecorator(Shard shard, final ShardDataTreeCohort cohort) {
294 shard.getCommitCoordinator().setCohortDecorator(new ShardCommitCoordinator.CohortDecorator() {
296 public ShardDataTreeCohort decorate(String transactionID, ShardDataTreeCohort actual) {
302 protected BatchedModifications prepareBatchedModifications(String transactionID,
303 MutableCompositeModification modification) {
304 return prepareBatchedModifications(transactionID, modification, false);
307 private static BatchedModifications prepareBatchedModifications(String transactionID,
308 MutableCompositeModification modification,
309 boolean doCommitOnReady) {
310 final BatchedModifications batchedModifications = new BatchedModifications(transactionID, CURRENT_VERSION, null);
311 batchedModifications.addModification(modification);
312 batchedModifications.setReady(true);
313 batchedModifications.setDoCommitOnReady(doCommitOnReady);
314 batchedModifications.setTotalMessagesSent(1);
315 return batchedModifications;
319 public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard, final YangInstanceIdentifier id)
320 throws ExecutionException, InterruptedException {
321 return shard.underlyingActor().getDataStore().readNode(id).orNull();
324 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
325 return store.takeSnapshot().readNode(id).orNull();
328 public static void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
329 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
330 Future<Object> future = Patterns.ask(shard, newBatchedModifications("tx", id, node, true, true, 1),
331 new Timeout(5, TimeUnit.SECONDS));
333 Await.ready(future, Duration.create(5, TimeUnit.SECONDS));
334 } catch(TimeoutException e) {
335 throw new ExecutionException(e);
339 static BatchedModifications newBatchedModifications(final String transactionID, final YangInstanceIdentifier path,
340 final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady, final int messagesSent) {
341 return newBatchedModifications(transactionID, null, path, data, ready, doCommitOnReady, messagesSent);
344 static BatchedModifications newBatchedModifications(final String transactionID, final String transactionChainID,
345 final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady,
346 final int messagesSent) {
347 final BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, transactionChainID);
348 batched.addModification(new WriteModification(path, data));
349 batched.setReady(ready);
350 batched.setDoCommitOnReady(doCommitOnReady);
351 batched.setTotalMessagesSent(messagesSent);
355 public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
356 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
357 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
359 transaction.getSnapshot().write(id, node);
360 final ShardDataTreeCohort cohort = transaction.ready();
361 cohort.canCommit().get();
362 cohort.preCommit().get();
366 public static void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
367 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
368 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
370 transaction.getSnapshot().merge(id, node);
371 final ShardDataTreeCohort cohort = transaction.ready();
372 cohort.canCommit().get();
373 cohort.preCommit().get();
377 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
378 final NormalizedNode<?,?> node) throws DataValidationFailedException {
379 final DataTreeModification transaction = store.takeSnapshot().newModification();
381 transaction.write(id, node);
383 store.validate(transaction);
384 final DataTreeCandidate candidate = store.prepare(transaction);
385 store.commit(candidate);
388 @SuppressWarnings("serial")
389 public static final class DelegatingShardCreator implements Creator<Shard> {
390 private final Creator<Shard> delegate;
392 DelegatingShardCreator(final Creator<Shard> delegate) {
393 this.delegate = delegate;
397 public Shard create() throws Exception {
398 return delegate.create();