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.testkit.TestActorRef;
26 import com.google.common.base.Function;
27 import com.google.common.base.Optional;
28 import com.google.common.util.concurrent.ListenableFuture;
29 import com.google.common.util.concurrent.Uninterruptibles;
31 import java.util.concurrent.CountDownLatch;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.TimeUnit;
34 import java.util.concurrent.atomic.AtomicInteger;
35 import org.junit.After;
36 import org.junit.Assert;
37 import org.junit.Before;
38 import org.mockito.invocation.InvocationOnMock;
39 import org.mockito.stubbing.Answer;
40 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
41 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
42 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
43 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
44 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
45 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
46 import org.opendaylight.controller.cluster.raft.TestActorFactory;
47 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
48 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
49 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
52 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
53 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
56 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
57 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
58 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
59 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 * Abstract base for shard unit tests.
65 * @author Thomas Pantelis
67 public abstract class AbstractShardTest extends AbstractActorTest{
68 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
70 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
72 protected final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1")
73 .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build();
75 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
76 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
77 shardHeartbeatIntervalInMillis(100);
79 protected final TestActorFactory actorFactory = new TestActorFactory(getSystem());
83 InMemorySnapshotStore.clear();
84 InMemoryJournal.clear();
88 public void tearDown() {
89 InMemorySnapshotStore.clear();
90 InMemoryJournal.clear();
94 protected DatastoreContext newDatastoreContext() {
95 return dataStoreContextBuilder.build();
98 protected Props newShardProps() {
99 return newShardBuilder().props();
102 protected Shard.Builder newShardBuilder() {
103 return Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).schemaContext(SCHEMA_CONTEXT);
106 protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
107 // Create the actor and wait for recovery complete.
109 final int nListEntries = listEntryKeys.size();
111 final CountDownLatch recoveryComplete = new CountDownLatch(1);
113 @SuppressWarnings("serial")
115 Creator<Shard> creator = new Creator<Shard>() {
117 public Shard create() throws Exception {
118 return new Shard(newShardBuilder()) {
120 protected void onRecoveryComplete() {
122 super.onRecoveryComplete();
124 recoveryComplete.countDown();
131 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
132 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
134 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
136 // Verify data in the data store.
138 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
139 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
140 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
141 outerList.getValue() instanceof Iterable);
142 for(final Object entry: (Iterable<?>) outerList.getValue()) {
143 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
144 entry instanceof MapEntryNode);
145 final MapEntryNode mapEntry = (MapEntryNode)entry;
146 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
147 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
148 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
149 final Object value = idLeaf.get().getValue();
150 assertTrue("Unexpected value for leaf "+ TestModel.ID_QNAME.getLocalName() + ": " + value,
151 listEntryKeys.remove(value));
154 if(!listEntryKeys.isEmpty()) {
155 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
159 assertEquals("Last log index", nListEntries,
160 shard.underlyingActor().getShardMBean().getLastLogIndex());
161 assertEquals("Commit index", nListEntries,
162 shard.underlyingActor().getShardMBean().getCommitIndex());
163 assertEquals("Last applied", nListEntries,
164 shard.underlyingActor().getShardMBean().getLastApplied());
166 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
169 protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
170 long lastApplied = -1;
171 for(int i = 0; i < 20 * 5; i++) {
172 lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
173 if(lastApplied == expectedValue) {
176 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
179 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
182 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
183 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
184 final MutableCompositeModification modification) {
185 return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null);
188 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
189 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
190 final MutableCompositeModification modification,
191 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
193 final ReadWriteShardDataTreeTransaction tx = dataStore.newReadWriteTransaction("setup-mock-" + cohortName, null);
194 tx.getSnapshot().write(path, data);
195 final ShardDataTreeCohort cohort = createDelegatingMockCohort(cohortName, dataStore.finishTransaction(tx), preCommit);
197 modification.addModification(new WriteModification(path, data));
202 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
203 final ShardDataTreeCohort actual) {
204 return createDelegatingMockCohort(cohortName, actual, null);
207 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
208 final ShardDataTreeCohort actual,
209 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
210 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.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 if(preCommit != null) {
223 return preCommit.apply(actual);
225 return actual.preCommit();
228 }).when(cohort).preCommit();
230 doAnswer(new Answer<ListenableFuture<Void>>() {
232 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
233 return actual.commit();
235 }).when(cohort).commit();
237 doAnswer(new Answer<ListenableFuture<Void>>() {
239 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
240 return actual.abort();
242 }).when(cohort).abort();
244 doAnswer(new Answer<DataTreeCandidateTip>() {
246 public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
247 return actual.getCandidate();
249 }).when(cohort).getCandidate();
254 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
255 String transactionID,
256 MutableCompositeModification modification,
257 boolean doCommitOnReady) {
258 if(remoteReadWriteTransaction){
259 return prepareForwardedReadyTransaction(cohort, transactionID, CURRENT_VERSION,
262 setupCohortDecorator(shard, cohort);
263 return prepareBatchedModifications(transactionID, modification, doCommitOnReady);
267 static ShardDataTreeTransactionParent newShardDataTreeTransactionParent(ShardDataTreeCohort cohort) {
268 ShardDataTreeTransactionParent mockParent = mock(ShardDataTreeTransactionParent.class);
269 doReturn(cohort).when(mockParent).finishTransaction(any(ReadWriteShardDataTreeTransaction.class));
270 doNothing().when(mockParent).abortTransaction(any(AbstractShardDataTreeTransaction.class));
274 protected ForwardedReadyTransaction prepareForwardedReadyTransaction(ShardDataTreeCohort cohort,
275 String transactionID, short version, boolean doCommitOnReady) {
276 return new ForwardedReadyTransaction(transactionID, version,
277 new ReadWriteShardDataTreeTransaction(newShardDataTreeTransactionParent(cohort), transactionID,
278 mock(DataTreeModification.class)), true, doCommitOnReady);
281 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
282 String transactionID,
283 MutableCompositeModification modification) {
284 return prepareReadyTransactionMessage(remoteReadWriteTransaction, shard, cohort, transactionID, modification, false);
287 protected void setupCohortDecorator(Shard shard, final ShardDataTreeCohort cohort) {
288 shard.getCommitCoordinator().setCohortDecorator(new ShardCommitCoordinator.CohortDecorator() {
290 public ShardDataTreeCohort decorate(String transactionID, ShardDataTreeCohort actual) {
296 protected BatchedModifications prepareBatchedModifications(String transactionID,
297 MutableCompositeModification modification) {
298 return prepareBatchedModifications(transactionID, modification, false);
301 private static BatchedModifications prepareBatchedModifications(String transactionID,
302 MutableCompositeModification modification,
303 boolean doCommitOnReady) {
304 final BatchedModifications batchedModifications = new BatchedModifications(transactionID, CURRENT_VERSION, null);
305 batchedModifications.addModification(modification);
306 batchedModifications.setReady(true);
307 batchedModifications.setDoCommitOnReady(doCommitOnReady);
308 batchedModifications.setTotalMessagesSent(1);
309 return batchedModifications;
313 public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard, final YangInstanceIdentifier id)
314 throws ExecutionException, InterruptedException {
315 return shard.underlyingActor().getDataStore().readNode(id).orNull();
318 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
319 return store.takeSnapshot().readNode(id).orNull();
322 public static void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
323 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
324 writeToStore(shard.underlyingActor().getDataStore(), id, node);
327 public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
328 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
329 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
331 transaction.getSnapshot().write(id, node);
332 final ShardDataTreeCohort cohort = transaction.ready();
333 cohort.canCommit().get();
334 cohort.preCommit().get();
338 public static void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
339 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
340 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
342 transaction.getSnapshot().merge(id, node);
343 final ShardDataTreeCohort cohort = transaction.ready();
344 cohort.canCommit().get();
345 cohort.preCommit().get();
349 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
350 final NormalizedNode<?,?> node) throws DataValidationFailedException {
351 final DataTreeModification transaction = store.takeSnapshot().newModification();
353 transaction.write(id, node);
355 store.validate(transaction);
356 final DataTreeCandidate candidate = store.prepare(transaction);
357 store.commit(candidate);
360 @SuppressWarnings("serial")
361 public static final class DelegatingShardCreator implements Creator<Shard> {
362 private final Creator<Shard> delegate;
364 DelegatingShardCreator(final Creator<Shard> delegate) {
365 this.delegate = delegate;
369 public Shard create() throws Exception {
370 return delegate.create();