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.Futures;
29 import com.google.common.util.concurrent.ListenableFuture;
30 import com.google.common.util.concurrent.Uninterruptibles;
31 import java.util.Collections;
33 import java.util.concurrent.CountDownLatch;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.atomic.AtomicInteger;
37 import org.junit.After;
38 import org.junit.Assert;
39 import org.junit.Before;
40 import org.mockito.invocation.InvocationOnMock;
41 import org.mockito.stubbing.Answer;
42 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
43 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
44 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
45 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
46 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
47 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
48 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
49 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
50 import org.opendaylight.controller.cluster.raft.Snapshot;
51 import org.opendaylight.controller.cluster.raft.TestActorFactory;
52 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
53 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
54 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
55 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
58 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
59 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
65 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
69 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
70 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
74 * Abstract base for shard unit tests.
76 * @author Thomas Pantelis
78 public abstract class AbstractShardTest extends AbstractActorTest{
79 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
81 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
83 protected final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1")
84 .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build();
86 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
87 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
88 shardHeartbeatIntervalInMillis(100);
90 protected final TestActorFactory actorFactory = new TestActorFactory(getSystem());
94 InMemorySnapshotStore.clear();
95 InMemoryJournal.clear();
99 public void tearDown() {
100 InMemorySnapshotStore.clear();
101 InMemoryJournal.clear();
102 actorFactory.close();
105 protected DatastoreContext newDatastoreContext() {
106 return dataStoreContextBuilder.build();
109 protected Props newShardProps() {
110 return newShardBuilder().props();
113 protected Shard.Builder newShardBuilder() {
114 return Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).schemaContext(SCHEMA_CONTEXT);
117 protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
118 // Create the actor and wait for recovery complete.
120 final int nListEntries = listEntryKeys.size();
122 final CountDownLatch recoveryComplete = new CountDownLatch(1);
124 @SuppressWarnings("serial")
126 Creator<Shard> creator = new Creator<Shard>() {
128 public Shard create() throws Exception {
129 return new Shard(newShardBuilder()) {
131 protected void onRecoveryComplete() {
133 super.onRecoveryComplete();
135 recoveryComplete.countDown();
142 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
143 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
145 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
147 // Verify data in the data store.
149 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
150 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
151 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
152 outerList.getValue() instanceof Iterable);
153 for(final Object entry: (Iterable<?>) outerList.getValue()) {
154 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
155 entry instanceof MapEntryNode);
156 final MapEntryNode mapEntry = (MapEntryNode)entry;
157 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
158 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
159 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
160 final Object value = idLeaf.get().getValue();
161 assertTrue("Unexpected value for leaf "+ TestModel.ID_QNAME.getLocalName() + ": " + value,
162 listEntryKeys.remove(value));
165 if(!listEntryKeys.isEmpty()) {
166 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
170 assertEquals("Last log index", nListEntries,
171 shard.underlyingActor().getShardMBean().getLastLogIndex());
172 assertEquals("Commit index", nListEntries,
173 shard.underlyingActor().getShardMBean().getCommitIndex());
174 assertEquals("Last applied", nListEntries,
175 shard.underlyingActor().getShardMBean().getLastApplied());
177 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
180 protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
181 long lastApplied = -1;
182 for(int i = 0; i < 20 * 5; i++) {
183 lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
184 if(lastApplied == expectedValue) {
187 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
190 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
193 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
194 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
195 final MutableCompositeModification modification) {
196 return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null);
199 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
200 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
201 final MutableCompositeModification modification,
202 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
204 final ReadWriteShardDataTreeTransaction tx = dataStore.newReadWriteTransaction("setup-mock-" + cohortName, null);
205 tx.getSnapshot().write(path, data);
206 final ShardDataTreeCohort cohort = createDelegatingMockCohort(cohortName, dataStore.finishTransaction(tx), preCommit);
208 modification.addModification(new WriteModification(path, data));
213 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
214 final ShardDataTreeCohort actual) {
215 return createDelegatingMockCohort(cohortName, actual, null);
218 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
219 final ShardDataTreeCohort actual,
220 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
221 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, cohortName);
223 doAnswer(new Answer<ListenableFuture<Boolean>>() {
225 public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
226 return actual.canCommit();
228 }).when(cohort).canCommit();
230 doAnswer(new Answer<ListenableFuture<Void>>() {
232 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
233 if(preCommit != null) {
234 return preCommit.apply(actual);
236 return actual.preCommit();
239 }).when(cohort).preCommit();
241 doAnswer(new Answer<ListenableFuture<Void>>() {
243 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
244 return actual.commit();
246 }).when(cohort).commit();
248 doAnswer(new Answer<ListenableFuture<Void>>() {
250 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
251 return actual.abort();
253 }).when(cohort).abort();
255 doAnswer(new Answer<DataTreeCandidateTip>() {
257 public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
258 return actual.getCandidate();
260 }).when(cohort).getCandidate();
265 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
266 String transactionID,
267 MutableCompositeModification modification,
268 boolean doCommitOnReady) {
269 if(remoteReadWriteTransaction){
270 return prepareForwardedReadyTransaction(cohort, transactionID, CURRENT_VERSION,
273 setupCohortDecorator(shard, cohort);
274 return prepareBatchedModifications(transactionID, modification, doCommitOnReady);
278 protected ShardDataTreeCohort mockShardDataTreeCohort() {
279 ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class);
280 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
281 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
282 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
283 doReturn(mockCandidate("candidate")).when(cohort).getCandidate();
287 static ShardDataTreeTransactionParent newShardDataTreeTransactionParent(ShardDataTreeCohort cohort) {
288 ShardDataTreeTransactionParent mockParent = mock(ShardDataTreeTransactionParent.class);
289 doReturn(cohort).when(mockParent).finishTransaction(any(ReadWriteShardDataTreeTransaction.class));
290 doNothing().when(mockParent).abortTransaction(any(AbstractShardDataTreeTransaction.class));
294 protected ForwardedReadyTransaction prepareForwardedReadyTransaction(ShardDataTreeCohort cohort,
295 String transactionID, short version, boolean doCommitOnReady) {
296 return new ForwardedReadyTransaction(transactionID, version,
297 new ReadWriteShardDataTreeTransaction(newShardDataTreeTransactionParent(cohort), transactionID,
298 mock(DataTreeModification.class)), true, doCommitOnReady);
301 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
302 String transactionID,
303 MutableCompositeModification modification) {
304 return prepareReadyTransactionMessage(remoteReadWriteTransaction, shard, cohort, transactionID, modification, false);
307 protected void setupCohortDecorator(Shard shard, final ShardDataTreeCohort cohort) {
308 shard.getCommitCoordinator().setCohortDecorator(new ShardCommitCoordinator.CohortDecorator() {
310 public ShardDataTreeCohort decorate(String transactionID, ShardDataTreeCohort actual) {
316 protected BatchedModifications prepareBatchedModifications(String transactionID,
317 MutableCompositeModification modification) {
318 return prepareBatchedModifications(transactionID, modification, false);
321 private static BatchedModifications prepareBatchedModifications(String transactionID,
322 MutableCompositeModification modification,
323 boolean doCommitOnReady) {
324 final BatchedModifications batchedModifications = new BatchedModifications(transactionID, CURRENT_VERSION, null);
325 batchedModifications.addModification(modification);
326 batchedModifications.setReady(true);
327 batchedModifications.setDoCommitOnReady(doCommitOnReady);
328 batchedModifications.setTotalMessagesSent(1);
329 return batchedModifications;
333 public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard, final YangInstanceIdentifier id)
334 throws ExecutionException, InterruptedException {
335 return shard.underlyingActor().getDataStore().readNode(id).orNull();
338 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
339 return store.takeSnapshot().readNode(id).orNull();
342 public static void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
343 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
344 writeToStore(shard.underlyingActor().getDataStore(), id, node);
347 public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
348 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
349 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
351 transaction.getSnapshot().write(id, node);
352 final ShardDataTreeCohort cohort = transaction.ready();
353 cohort.canCommit().get();
354 cohort.preCommit().get();
358 public static void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
359 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
360 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
362 transaction.getSnapshot().merge(id, node);
363 final ShardDataTreeCohort cohort = transaction.ready();
364 cohort.canCommit().get();
365 cohort.preCommit().get();
369 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
370 final NormalizedNode<?,?> node) throws DataValidationFailedException {
371 final DataTreeModification transaction = store.takeSnapshot().newModification();
373 transaction.write(id, node);
375 store.validate(transaction);
376 final DataTreeCandidate candidate = store.prepare(transaction);
377 store.commit(candidate);
380 DataTree setupInMemorySnapshotStore() throws DataValidationFailedException {
381 final DataTree testStore = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
382 testStore.setSchemaContext(SCHEMA_CONTEXT);
384 writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
386 final NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.builder().build());
388 InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
389 SerializationUtils.serializeNormalizedNode(root),
390 Collections.<ReplicatedLogEntry>emptyList(), 0, 1, -1, -1));
394 static DataTreeCandidatePayload payloadForModification(final DataTree source, final DataTreeModification mod) throws DataValidationFailedException {
395 source.validate(mod);
396 final DataTreeCandidate candidate = source.prepare(mod);
397 source.commit(candidate);
398 return DataTreeCandidatePayload.create(candidate);
401 static BatchedModifications newBatchedModifications(final String transactionID, final YangInstanceIdentifier path,
402 final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady, final int messagesSent) {
403 return newBatchedModifications(transactionID, null, path, data, ready, doCommitOnReady, messagesSent);
406 static BatchedModifications newBatchedModifications(final String transactionID, final String transactionChainID,
407 final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady,
408 final int messagesSent) {
409 final BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, transactionChainID);
410 batched.addModification(new WriteModification(path, data));
411 batched.setReady(ready);
412 batched.setDoCommitOnReady(doCommitOnReady);
413 batched.setTotalMessagesSent(messagesSent);
417 @SuppressWarnings("unchecked")
418 static void verifyOuterListEntry(final TestActorRef<Shard> shard, final Object expIDValue) throws Exception {
419 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
420 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
421 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
422 outerList.getValue() instanceof Iterable);
423 final Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
424 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
425 entry instanceof MapEntryNode);
426 final MapEntryNode mapEntry = (MapEntryNode)entry;
427 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
428 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
429 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
430 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", expIDValue, idLeaf.get().getValue());
433 public static DataTreeCandidateTip mockCandidate(final String name) {
434 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
435 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
436 doReturn(ModificationType.WRITE).when(mockCandidateNode).getModificationType();
437 doReturn(Optional.of(ImmutableNodes.containerNode(CarsModel.CARS_QNAME))).when(mockCandidateNode).getDataAfter();
438 doReturn(YangInstanceIdentifier.builder().build()).when(mockCandidate).getRootPath();
439 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
440 return mockCandidate;
443 static DataTreeCandidateTip mockUnmodifiedCandidate(final String name) {
444 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
445 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
446 doReturn(ModificationType.UNMODIFIED).when(mockCandidateNode).getModificationType();
447 doReturn(YangInstanceIdentifier.builder().build()).when(mockCandidate).getRootPath();
448 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
449 return mockCandidate;
452 static void commitTransaction(final DataTree store, final DataTreeModification modification) throws DataValidationFailedException {
453 modification.ready();
454 store.validate(modification);
455 store.commit(store.prepare(modification));
458 @SuppressWarnings("serial")
459 public static final class DelegatingShardCreator implements Creator<Shard> {
460 private final Creator<Shard> delegate;
462 DelegatingShardCreator(final Creator<Shard> delegate) {
463 this.delegate = delegate;
467 public Shard create() throws Exception {
468 return delegate.create();