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;
30 import java.util.Collections;
32 import java.util.concurrent.CountDownLatch;
33 import java.util.concurrent.ExecutionException;
34 import java.util.concurrent.TimeUnit;
35 import java.util.concurrent.atomic.AtomicInteger;
36 import org.junit.After;
37 import org.junit.Assert;
38 import org.junit.Before;
39 import org.mockito.invocation.InvocationOnMock;
40 import org.mockito.stubbing.Answer;
41 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
42 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
43 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
44 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
45 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
46 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
47 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
48 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
49 import org.opendaylight.controller.cluster.raft.Snapshot;
50 import org.opendaylight.controller.cluster.raft.TestActorFactory;
51 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
52 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
53 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
54 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
57 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
58 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
64 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
65 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
68 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
69 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
73 * Abstract base for shard unit tests.
75 * @author Thomas Pantelis
77 public abstract class AbstractShardTest extends AbstractActorTest{
78 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
80 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
82 protected final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1")
83 .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build();
85 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
86 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
87 shardHeartbeatIntervalInMillis(100);
89 protected final TestActorFactory actorFactory = new TestActorFactory(getSystem());
93 InMemorySnapshotStore.clear();
94 InMemoryJournal.clear();
98 public void tearDown() {
99 InMemorySnapshotStore.clear();
100 InMemoryJournal.clear();
101 actorFactory.close();
104 protected DatastoreContext newDatastoreContext() {
105 return dataStoreContextBuilder.build();
108 protected Props newShardProps() {
109 return newShardBuilder().props();
112 protected Shard.Builder newShardBuilder() {
113 return Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).schemaContext(SCHEMA_CONTEXT);
116 protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
117 // Create the actor and wait for recovery complete.
119 final int nListEntries = listEntryKeys.size();
121 final CountDownLatch recoveryComplete = new CountDownLatch(1);
123 @SuppressWarnings("serial")
125 Creator<Shard> creator = new Creator<Shard>() {
127 public Shard create() throws Exception {
128 return new Shard(newShardBuilder()) {
130 protected void onRecoveryComplete() {
132 super.onRecoveryComplete();
134 recoveryComplete.countDown();
141 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
142 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
144 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
146 // Verify data in the data store.
148 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
149 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
150 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
151 outerList.getValue() instanceof Iterable);
152 for(final Object entry: (Iterable<?>) outerList.getValue()) {
153 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
154 entry instanceof MapEntryNode);
155 final MapEntryNode mapEntry = (MapEntryNode)entry;
156 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
157 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
158 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
159 final Object value = idLeaf.get().getValue();
160 assertTrue("Unexpected value for leaf "+ TestModel.ID_QNAME.getLocalName() + ": " + value,
161 listEntryKeys.remove(value));
164 if(!listEntryKeys.isEmpty()) {
165 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
169 assertEquals("Last log index", nListEntries,
170 shard.underlyingActor().getShardMBean().getLastLogIndex());
171 assertEquals("Commit index", nListEntries,
172 shard.underlyingActor().getShardMBean().getCommitIndex());
173 assertEquals("Last applied", nListEntries,
174 shard.underlyingActor().getShardMBean().getLastApplied());
176 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
179 protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
180 long lastApplied = -1;
181 for(int i = 0; i < 20 * 5; i++) {
182 lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
183 if(lastApplied == expectedValue) {
186 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
189 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
192 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
193 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
194 final MutableCompositeModification modification) {
195 return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null);
198 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
199 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
200 final MutableCompositeModification modification,
201 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
203 final ReadWriteShardDataTreeTransaction tx = dataStore.newReadWriteTransaction("setup-mock-" + cohortName, null);
204 tx.getSnapshot().write(path, data);
205 final ShardDataTreeCohort cohort = createDelegatingMockCohort(cohortName, dataStore.finishTransaction(tx), preCommit);
207 modification.addModification(new WriteModification(path, data));
212 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
213 final ShardDataTreeCohort actual) {
214 return createDelegatingMockCohort(cohortName, actual, null);
217 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
218 final ShardDataTreeCohort actual,
219 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
220 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, cohortName);
222 doAnswer(new Answer<ListenableFuture<Boolean>>() {
224 public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
225 return actual.canCommit();
227 }).when(cohort).canCommit();
229 doAnswer(new Answer<ListenableFuture<Void>>() {
231 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
232 if(preCommit != null) {
233 return preCommit.apply(actual);
235 return actual.preCommit();
238 }).when(cohort).preCommit();
240 doAnswer(new Answer<ListenableFuture<Void>>() {
242 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
243 return actual.commit();
245 }).when(cohort).commit();
247 doAnswer(new Answer<ListenableFuture<Void>>() {
249 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
250 return actual.abort();
252 }).when(cohort).abort();
254 doAnswer(new Answer<DataTreeCandidateTip>() {
256 public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
257 return actual.getCandidate();
259 }).when(cohort).getCandidate();
264 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
265 String transactionID,
266 MutableCompositeModification modification,
267 boolean doCommitOnReady) {
268 if(remoteReadWriteTransaction){
269 return prepareForwardedReadyTransaction(cohort, transactionID, CURRENT_VERSION,
272 setupCohortDecorator(shard, cohort);
273 return prepareBatchedModifications(transactionID, modification, doCommitOnReady);
277 static ShardDataTreeTransactionParent newShardDataTreeTransactionParent(ShardDataTreeCohort cohort) {
278 ShardDataTreeTransactionParent mockParent = mock(ShardDataTreeTransactionParent.class);
279 doReturn(cohort).when(mockParent).finishTransaction(any(ReadWriteShardDataTreeTransaction.class));
280 doNothing().when(mockParent).abortTransaction(any(AbstractShardDataTreeTransaction.class));
284 protected ForwardedReadyTransaction prepareForwardedReadyTransaction(ShardDataTreeCohort cohort,
285 String transactionID, short version, boolean doCommitOnReady) {
286 return new ForwardedReadyTransaction(transactionID, version,
287 new ReadWriteShardDataTreeTransaction(newShardDataTreeTransactionParent(cohort), transactionID,
288 mock(DataTreeModification.class)), true, doCommitOnReady);
291 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
292 String transactionID,
293 MutableCompositeModification modification) {
294 return prepareReadyTransactionMessage(remoteReadWriteTransaction, shard, cohort, transactionID, modification, false);
297 protected void setupCohortDecorator(Shard shard, final ShardDataTreeCohort cohort) {
298 shard.getCommitCoordinator().setCohortDecorator(new ShardCommitCoordinator.CohortDecorator() {
300 public ShardDataTreeCohort decorate(String transactionID, ShardDataTreeCohort actual) {
306 protected BatchedModifications prepareBatchedModifications(String transactionID,
307 MutableCompositeModification modification) {
308 return prepareBatchedModifications(transactionID, modification, false);
311 private static BatchedModifications prepareBatchedModifications(String transactionID,
312 MutableCompositeModification modification,
313 boolean doCommitOnReady) {
314 final BatchedModifications batchedModifications = new BatchedModifications(transactionID, CURRENT_VERSION, null);
315 batchedModifications.addModification(modification);
316 batchedModifications.setReady(true);
317 batchedModifications.setDoCommitOnReady(doCommitOnReady);
318 batchedModifications.setTotalMessagesSent(1);
319 return batchedModifications;
323 public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard, final YangInstanceIdentifier id)
324 throws ExecutionException, InterruptedException {
325 return shard.underlyingActor().getDataStore().readNode(id).orNull();
328 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
329 return store.takeSnapshot().readNode(id).orNull();
332 public static void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
333 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
334 writeToStore(shard.underlyingActor().getDataStore(), id, node);
337 public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
338 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
339 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
341 transaction.getSnapshot().write(id, node);
342 final ShardDataTreeCohort cohort = transaction.ready();
343 cohort.canCommit().get();
344 cohort.preCommit().get();
348 public static void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
349 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
350 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
352 transaction.getSnapshot().merge(id, node);
353 final ShardDataTreeCohort cohort = transaction.ready();
354 cohort.canCommit().get();
355 cohort.preCommit().get();
359 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
360 final NormalizedNode<?,?> node) throws DataValidationFailedException {
361 final DataTreeModification transaction = store.takeSnapshot().newModification();
363 transaction.write(id, node);
365 store.validate(transaction);
366 final DataTreeCandidate candidate = store.prepare(transaction);
367 store.commit(candidate);
370 DataTree setupInMemorySnapshotStore() throws DataValidationFailedException {
371 final DataTree testStore = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
372 testStore.setSchemaContext(SCHEMA_CONTEXT);
374 writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
376 final NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.builder().build());
378 InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
379 SerializationUtils.serializeNormalizedNode(root),
380 Collections.<ReplicatedLogEntry>emptyList(), 0, 1, -1, -1));
384 static DataTreeCandidatePayload payloadForModification(final DataTree source, final DataTreeModification mod) throws DataValidationFailedException {
385 source.validate(mod);
386 final DataTreeCandidate candidate = source.prepare(mod);
387 source.commit(candidate);
388 return DataTreeCandidatePayload.create(candidate);
391 static BatchedModifications newBatchedModifications(final String transactionID, final YangInstanceIdentifier path,
392 final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady, final int messagesSent) {
393 return newBatchedModifications(transactionID, null, path, data, ready, doCommitOnReady, messagesSent);
396 static BatchedModifications newBatchedModifications(final String transactionID, final String transactionChainID,
397 final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady,
398 final int messagesSent) {
399 final BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, transactionChainID);
400 batched.addModification(new WriteModification(path, data));
401 batched.setReady(ready);
402 batched.setDoCommitOnReady(doCommitOnReady);
403 batched.setTotalMessagesSent(messagesSent);
407 @SuppressWarnings("unchecked")
408 static void verifyOuterListEntry(final TestActorRef<Shard> shard, final Object expIDValue) throws Exception {
409 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
410 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
411 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
412 outerList.getValue() instanceof Iterable);
413 final Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
414 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
415 entry instanceof MapEntryNode);
416 final MapEntryNode mapEntry = (MapEntryNode)entry;
417 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
418 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
419 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
420 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", expIDValue, idLeaf.get().getValue());
423 static DataTreeCandidateTip mockCandidate(final String name) {
424 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
425 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
426 doReturn(ModificationType.WRITE).when(mockCandidateNode).getModificationType();
427 doReturn(Optional.of(ImmutableNodes.containerNode(CarsModel.CARS_QNAME))).when(mockCandidateNode).getDataAfter();
428 doReturn(YangInstanceIdentifier.builder().build()).when(mockCandidate).getRootPath();
429 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
430 return mockCandidate;
433 static DataTreeCandidateTip mockUnmodifiedCandidate(final String name) {
434 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
435 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
436 doReturn(ModificationType.UNMODIFIED).when(mockCandidateNode).getModificationType();
437 doReturn(YangInstanceIdentifier.builder().build()).when(mockCandidate).getRootPath();
438 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
439 return mockCandidate;
442 static void commitTransaction(final DataTree store, final DataTreeModification modification) throws DataValidationFailedException {
443 modification.ready();
444 store.validate(modification);
445 store.commit(store.prepare(modification));
448 @SuppressWarnings("serial")
449 public static final class DelegatingShardCreator implements Creator<Shard> {
450 private final Creator<Shard> delegate;
452 DelegatingShardCreator(final Creator<Shard> delegate) {
453 this.delegate = delegate;
457 public Shard create() throws Exception {
458 return delegate.create();