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.Futures;
31 import com.google.common.util.concurrent.ListenableFuture;
32 import com.google.common.util.concurrent.Uninterruptibles;
33 import java.util.Collections;
35 import java.util.concurrent.CountDownLatch;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.TimeUnit;
38 import java.util.concurrent.TimeoutException;
39 import java.util.concurrent.atomic.AtomicInteger;
40 import org.junit.After;
41 import org.junit.Assert;
42 import org.junit.Before;
43 import org.mockito.invocation.InvocationOnMock;
44 import org.mockito.stubbing.Answer;
45 import org.opendaylight.controller.cluster.access.concepts.MemberName;
46 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
47 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
48 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
49 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
50 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
51 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
52 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
53 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
54 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
55 import org.opendaylight.controller.cluster.raft.Snapshot;
56 import org.opendaylight.controller.cluster.raft.TestActorFactory;
57 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
58 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
59 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
60 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
61 import org.opendaylight.yangtools.concepts.Identifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
64 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
65 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
75 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
76 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
77 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
78 import scala.concurrent.Await;
79 import scala.concurrent.Future;
80 import scala.concurrent.duration.Duration;
83 * Abstract base for shard unit tests.
85 * @author Thomas Pantelis
87 public abstract class AbstractShardTest extends AbstractActorTest{
88 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
90 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
92 protected final ShardIdentifier shardID = ShardIdentifier.create("inventory", MemberName.forName("member-1"),
93 "config" + NEXT_SHARD_NUM.getAndIncrement());
95 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
96 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
97 shardHeartbeatIntervalInMillis(100);
99 protected final TestActorFactory actorFactory = new TestActorFactory(getSystem());
102 public void setUp() {
103 InMemorySnapshotStore.clear();
104 InMemoryJournal.clear();
108 public void tearDown() {
109 InMemorySnapshotStore.clear();
110 InMemoryJournal.clear();
111 actorFactory.close();
114 protected DatastoreContext newDatastoreContext() {
115 return dataStoreContextBuilder.build();
118 protected Props newShardProps() {
119 return newShardBuilder().props();
122 protected Shard.Builder newShardBuilder() {
123 return Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).schemaContext(SCHEMA_CONTEXT);
126 protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
127 // Create the actor and wait for recovery complete.
129 final int nListEntries = listEntryKeys.size();
131 final CountDownLatch recoveryComplete = new CountDownLatch(1);
133 @SuppressWarnings("serial")
134 final Creator<Shard> creator = new Creator<Shard>() {
136 public Shard create() throws Exception {
137 return new Shard(newShardBuilder()) {
139 protected void onRecoveryComplete() {
141 super.onRecoveryComplete();
143 recoveryComplete.countDown();
150 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
151 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
153 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
155 // Verify data in the data store.
157 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
158 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
159 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
160 outerList.getValue() instanceof Iterable);
161 for(final Object entry: (Iterable<?>) outerList.getValue()) {
162 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
163 entry instanceof MapEntryNode);
164 final MapEntryNode mapEntry = (MapEntryNode)entry;
165 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
166 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
167 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
168 final Object value = idLeaf.get().getValue();
169 assertTrue("Unexpected value for leaf "+ TestModel.ID_QNAME.getLocalName() + ": " + value,
170 listEntryKeys.remove(value));
173 if(!listEntryKeys.isEmpty()) {
174 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
178 assertEquals("Last log index", nListEntries,
179 shard.underlyingActor().getShardMBean().getLastLogIndex());
180 assertEquals("Commit index", nListEntries,
181 shard.underlyingActor().getShardMBean().getCommitIndex());
182 assertEquals("Last applied", nListEntries,
183 shard.underlyingActor().getShardMBean().getLastApplied());
185 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
188 protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
189 long lastApplied = -1;
190 for(int i = 0; i < 20 * 5; i++) {
191 lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
192 if(lastApplied == expectedValue) {
195 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
198 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
201 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
202 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
203 final MutableCompositeModification modification) {
204 return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null);
207 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
208 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
209 final MutableCompositeModification modification,
210 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
212 final ReadWriteShardDataTreeTransaction tx = dataStore.newReadWriteTransaction(nextTransactionId());
213 tx.getSnapshot().write(path, data);
214 final ShardDataTreeCohort cohort = createDelegatingMockCohort(cohortName, dataStore.finishTransaction(tx), preCommit);
216 modification.addModification(new WriteModification(path, data));
221 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
222 final ShardDataTreeCohort actual) {
223 return createDelegatingMockCohort(cohortName, actual, null);
226 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
227 final ShardDataTreeCohort actual,
228 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
229 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, cohortName);
231 doAnswer(new Answer<ListenableFuture<Boolean>>() {
233 public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
234 return actual.canCommit();
236 }).when(cohort).canCommit();
238 doAnswer(new Answer<ListenableFuture<Void>>() {
240 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
241 if(preCommit != null) {
242 return preCommit.apply(actual);
244 return actual.preCommit();
247 }).when(cohort).preCommit();
249 doAnswer(new Answer<ListenableFuture<Void>>() {
251 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
252 return actual.commit();
254 }).when(cohort).commit();
256 doAnswer(new Answer<ListenableFuture<Void>>() {
258 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
259 return actual.abort();
261 }).when(cohort).abort();
263 doAnswer(new Answer<DataTreeCandidateTip>() {
265 public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
266 return actual.getCandidate();
268 }).when(cohort).getCandidate();
273 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
274 TransactionIdentifier transactionID, MutableCompositeModification modification,
275 boolean doCommitOnReady) {
276 if(remoteReadWriteTransaction){
277 return prepareForwardedReadyTransaction(cohort, transactionID, CURRENT_VERSION,
280 setupCohortDecorator(shard, cohort);
281 return prepareBatchedModifications(transactionID, modification, doCommitOnReady);
285 protected ShardDataTreeCohort mockShardDataTreeCohort() {
286 ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class);
287 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
288 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
289 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
290 doReturn(mockCandidate("candidate")).when(cohort).getCandidate();
294 static ShardDataTreeTransactionParent newShardDataTreeTransactionParent(ShardDataTreeCohort cohort) {
295 ShardDataTreeTransactionParent mockParent = mock(ShardDataTreeTransactionParent.class);
296 doReturn(cohort).when(mockParent).finishTransaction(any(ReadWriteShardDataTreeTransaction.class));
297 doNothing().when(mockParent).abortTransaction(any(AbstractShardDataTreeTransaction.class));
301 protected ForwardedReadyTransaction prepareForwardedReadyTransaction(ShardDataTreeCohort cohort,
302 TransactionIdentifier transactionID, short version, boolean doCommitOnReady) {
303 return new ForwardedReadyTransaction(transactionID, version,
304 new ReadWriteShardDataTreeTransaction(newShardDataTreeTransactionParent(cohort), transactionID,
305 mock(DataTreeModification.class)), doCommitOnReady);
308 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
309 TransactionIdentifier transactionID, MutableCompositeModification modification) {
310 return prepareReadyTransactionMessage(remoteReadWriteTransaction, shard, cohort, transactionID, modification, false);
313 protected void setupCohortDecorator(Shard shard, final ShardDataTreeCohort cohort) {
314 shard.getCommitCoordinator().setCohortDecorator(new ShardCommitCoordinator.CohortDecorator() {
316 public ShardDataTreeCohort decorate(Identifier transactionID, ShardDataTreeCohort actual) {
322 protected BatchedModifications prepareBatchedModifications(TransactionIdentifier transactionID,
323 MutableCompositeModification modification) {
324 return prepareBatchedModifications(transactionID, modification, false);
327 private static BatchedModifications prepareBatchedModifications(TransactionIdentifier transactionID,
328 MutableCompositeModification modification,
329 boolean doCommitOnReady) {
330 final BatchedModifications batchedModifications = new BatchedModifications(transactionID, CURRENT_VERSION);
331 batchedModifications.addModification(modification);
332 batchedModifications.setReady(true);
333 batchedModifications.setDoCommitOnReady(doCommitOnReady);
334 batchedModifications.setTotalMessagesSent(1);
335 return batchedModifications;
339 public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard, final YangInstanceIdentifier id)
340 throws ExecutionException, InterruptedException {
341 return shard.underlyingActor().getDataStore().readNode(id).orNull();
344 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
345 return store.takeSnapshot().readNode(id).orNull();
348 public void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
349 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
350 Future<Object> future = Patterns.ask(shard, newBatchedModifications(nextTransactionId(), id, node, true, true, 1),
351 new Timeout(5, TimeUnit.SECONDS));
353 Await.ready(future, Duration.create(5, TimeUnit.SECONDS));
354 } catch(TimeoutException e) {
355 throw new ExecutionException(e);
359 public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
360 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
361 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction(nextTransactionId());
363 transaction.getSnapshot().write(id, node);
364 final ShardDataTreeCohort cohort = transaction.ready();
365 cohort.canCommit().get();
366 cohort.preCommit().get();
370 public void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
371 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
372 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction(nextTransactionId());
374 transaction.getSnapshot().merge(id, node);
375 final ShardDataTreeCohort cohort = transaction.ready();
376 cohort.canCommit().get();
377 cohort.preCommit().get();
381 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
382 final NormalizedNode<?,?> node) throws DataValidationFailedException {
383 final DataTreeModification transaction = store.takeSnapshot().newModification();
385 transaction.write(id, node);
387 store.validate(transaction);
388 final DataTreeCandidate candidate = store.prepare(transaction);
389 store.commit(candidate);
392 DataTree setupInMemorySnapshotStore() throws DataValidationFailedException {
393 final DataTree testStore = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
394 testStore.setSchemaContext(SCHEMA_CONTEXT);
396 writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
398 final NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.EMPTY);
400 InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
401 SerializationUtils.serializeNormalizedNode(root),
402 Collections.<ReplicatedLogEntry>emptyList(), 0, 1, -1, -1));
406 static DataTreeCandidatePayload payloadForModification(final DataTree source, final DataTreeModification mod) throws DataValidationFailedException {
407 source.validate(mod);
408 final DataTreeCandidate candidate = source.prepare(mod);
409 source.commit(candidate);
410 return DataTreeCandidatePayload.create(candidate);
413 static BatchedModifications newBatchedModifications(final TransactionIdentifier transactionID,
414 final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady,
415 final int messagesSent) {
416 final BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
417 batched.addModification(new WriteModification(path, data));
418 batched.setReady(ready);
419 batched.setDoCommitOnReady(doCommitOnReady);
420 batched.setTotalMessagesSent(messagesSent);
424 @SuppressWarnings("unchecked")
425 static void verifyOuterListEntry(final TestActorRef<Shard> shard, final Object expIDValue) throws Exception {
426 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
427 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
428 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
429 outerList.getValue() instanceof Iterable);
430 final Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
431 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
432 entry instanceof MapEntryNode);
433 final MapEntryNode mapEntry = (MapEntryNode)entry;
434 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
435 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
436 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
437 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", expIDValue, idLeaf.get().getValue());
440 public static DataTreeCandidateTip mockCandidate(final String name) {
441 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
442 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
443 doReturn(ModificationType.WRITE).when(mockCandidateNode).getModificationType();
444 doReturn(Optional.of(ImmutableNodes.containerNode(CarsModel.CARS_QNAME))).when(mockCandidateNode).getDataAfter();
445 doReturn(CarsModel.BASE_PATH).when(mockCandidate).getRootPath();
446 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
447 return mockCandidate;
450 static DataTreeCandidateTip mockUnmodifiedCandidate(final String name) {
451 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
452 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
453 doReturn(ModificationType.UNMODIFIED).when(mockCandidateNode).getModificationType();
454 doReturn(YangInstanceIdentifier.EMPTY).when(mockCandidate).getRootPath();
455 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
456 return mockCandidate;
459 static void commitTransaction(final DataTree store, final DataTreeModification modification) throws DataValidationFailedException {
460 modification.ready();
461 store.validate(modification);
462 store.commit(store.prepare(modification));
465 @SuppressWarnings("serial")
466 public static final class DelegatingShardCreator implements Creator<Shard> {
467 private final Creator<Shard> delegate;
469 DelegatingShardCreator(final Creator<Shard> delegate) {
470 this.delegate = delegate;
474 public Shard create() throws Exception {
475 return delegate.create();