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.doReturn;
17 import static org.mockito.Mockito.mock;
18 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
19 import static org.opendaylight.controller.cluster.datastore.ShardDataTreeMocking.successfulCanCommit;
20 import static org.opendaylight.controller.cluster.datastore.ShardDataTreeMocking.successfulCommit;
21 import static org.opendaylight.controller.cluster.datastore.ShardDataTreeMocking.successfulPreCommit;
23 import akka.actor.ActorRef;
24 import akka.actor.PoisonPill;
25 import akka.actor.Props;
26 import akka.dispatch.Dispatchers;
27 import akka.japi.Creator;
28 import akka.pattern.Patterns;
29 import akka.testkit.TestActorRef;
30 import akka.util.Timeout;
31 import com.google.common.base.Optional;
32 import com.google.common.primitives.UnsignedLong;
33 import com.google.common.util.concurrent.FutureCallback;
34 import com.google.common.util.concurrent.Uninterruptibles;
35 import java.io.IOException;
36 import java.util.Collections;
37 import java.util.HashMap;
40 import java.util.concurrent.CountDownLatch;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.TimeUnit;
43 import java.util.concurrent.TimeoutException;
44 import java.util.concurrent.atomic.AtomicInteger;
45 import org.junit.After;
46 import org.junit.Assert;
47 import org.junit.Before;
48 import org.opendaylight.controller.cluster.access.concepts.MemberName;
49 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
50 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
51 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
52 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
53 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
54 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
55 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
56 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
57 import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
58 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
59 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
60 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
61 import org.opendaylight.controller.cluster.raft.TestActorFactory;
62 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
63 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
64 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
65 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
66 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
69 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
70 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
81 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
82 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
83 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
84 import scala.concurrent.Await;
85 import scala.concurrent.Future;
86 import scala.concurrent.duration.Duration;
89 * Abstract base for shard unit tests.
91 * @author Thomas Pantelis
93 public abstract class AbstractShardTest extends AbstractActorTest {
94 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
96 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
98 protected final ShardIdentifier shardID = ShardIdentifier.create("inventory", MemberName.forName("member-1"),
99 "config" + NEXT_SHARD_NUM.getAndIncrement());
101 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
102 .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).shardHeartbeatIntervalInMillis(100);
104 protected final TestActorFactory actorFactory = new TestActorFactory(getSystem());
107 public void setUp() {
108 InMemorySnapshotStore.clear();
109 InMemoryJournal.clear();
113 public void tearDown() {
114 InMemorySnapshotStore.clear();
115 InMemoryJournal.clear();
116 actorFactory.close();
119 protected DatastoreContext newDatastoreContext() {
120 return dataStoreContextBuilder.build();
123 protected Props newShardProps() {
124 return newShardBuilder().props();
127 protected Shard.Builder newShardBuilder() {
128 return Shard.builder().id(shardID).datastoreContext(newDatastoreContext())
129 .schemaContextProvider(() -> SCHEMA_CONTEXT);
132 protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
133 // Create the actor and wait for recovery complete.
135 final int nListEntries = listEntryKeys.size();
137 final CountDownLatch recoveryComplete = new CountDownLatch(1);
139 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
141 protected void onRecoveryComplete() {
143 super.onRecoveryComplete();
145 recoveryComplete.countDown();
150 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
151 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
154 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
156 // Verify data in the data store.
158 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
159 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
160 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
161 outerList.getValue() instanceof Iterable);
162 for (final Object entry: (Iterable<?>) outerList.getValue()) {
163 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
164 entry instanceof MapEntryNode);
165 final MapEntryNode mapEntry = (MapEntryNode)entry;
166 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
167 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
168 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
169 final Object value = idLeaf.get().getValue();
170 assertTrue("Unexpected value for leaf " + TestModel.ID_QNAME.getLocalName() + ": " + value,
171 listEntryKeys.remove(value));
174 if (!listEntryKeys.isEmpty()) {
175 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " + listEntryKeys);
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 TipProducingDataTree createDelegatingMockDataTree() throws Exception {
202 TipProducingDataTree actual = InMemoryDataTreeFactory.getInstance().create(TreeType.CONFIGURATION);
203 final TipProducingDataTree mock = mock(TipProducingDataTree.class);
205 doAnswer(invocation -> {
206 actual.validate(invocation.getArgumentAt(0, DataTreeModification.class));
208 }).when(mock).validate(any(DataTreeModification.class));
210 doAnswer(invocation -> actual.prepare(invocation.getArgumentAt(0, DataTreeModification.class))).when(
211 mock).prepare(any(DataTreeModification.class));
213 doAnswer(invocation -> {
214 actual.commit(invocation.getArgumentAt(0, DataTreeCandidate.class));
216 }).when(mock).commit(any(DataTreeCandidate.class));
218 doAnswer(invocation -> {
219 actual.setSchemaContext(invocation.getArgumentAt(0, SchemaContext.class));
221 }).when(mock).setSchemaContext(any(SchemaContext.class));
223 doAnswer(invocation -> actual.takeSnapshot()).when(mock).takeSnapshot();
225 doAnswer(invocation -> actual.getRootPath()).when(mock).getRootPath();
230 protected ShardDataTreeCohort mockShardDataTreeCohort() {
231 ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class);
232 DataTreeCandidate candidate = mockCandidate("candidate");
233 successfulCanCommit(cohort);
234 successfulPreCommit(cohort, candidate);
235 successfulCommit(cohort);
236 doReturn(candidate).when(cohort).getCandidate();
240 protected Map<TransactionIdentifier, CapturingShardDataTreeCohort> setupCohortDecorator(final Shard shard,
241 final TransactionIdentifier... transactionIDs) {
242 final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = new HashMap<>();
243 for (TransactionIdentifier id: transactionIDs) {
244 cohortMap.put(id, new CapturingShardDataTreeCohort());
247 shard.getCommitCoordinator().setCohortDecorator((transactionID, actual) -> {
248 CapturingShardDataTreeCohort cohort = cohortMap.get(transactionID);
249 cohort.setDelegate(actual);
256 protected BatchedModifications prepareBatchedModifications(final TransactionIdentifier transactionID,
257 final MutableCompositeModification modification) {
258 return prepareBatchedModifications(transactionID, modification, false);
261 protected static BatchedModifications prepareBatchedModifications(final TransactionIdentifier transactionID,
262 final MutableCompositeModification modification,
263 final boolean doCommitOnReady) {
264 final BatchedModifications batchedModifications = new BatchedModifications(transactionID, CURRENT_VERSION);
265 batchedModifications.addModification(modification);
266 batchedModifications.setReady(true);
267 batchedModifications.setDoCommitOnReady(doCommitOnReady);
268 batchedModifications.setTotalMessagesSent(1);
269 return batchedModifications;
272 protected static BatchedModifications prepareBatchedModifications(final TransactionIdentifier transactionID,
273 final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean doCommitOnReady) {
274 final MutableCompositeModification modification = new MutableCompositeModification();
275 modification.addModification(new WriteModification(path, data));
276 return prepareBatchedModifications(transactionID, modification, doCommitOnReady);
279 protected static ForwardedReadyTransaction prepareForwardedReadyTransaction(final TestActorRef<Shard> shard,
280 final TransactionIdentifier transactionID, final YangInstanceIdentifier path,
281 final NormalizedNode<?, ?> data, final boolean doCommitOnReady) {
282 ReadWriteShardDataTreeTransaction rwTx = shard.underlyingActor().getDataStore()
283 .newReadWriteTransaction(transactionID);
284 rwTx.getSnapshot().write(path, data);
285 return new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, rwTx, doCommitOnReady);
288 public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard,
289 final YangInstanceIdentifier id) throws ExecutionException, InterruptedException {
290 return shard.underlyingActor().getDataStore().readNode(id).orNull();
293 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
294 return store.takeSnapshot().readNode(id).orNull();
297 public void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
298 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
299 Future<Object> future = Patterns.ask(shard, newBatchedModifications(nextTransactionId(),
300 id, node, true, true, 1), new Timeout(5, TimeUnit.SECONDS));
302 Await.ready(future, Duration.create(5, TimeUnit.SECONDS));
303 } catch (TimeoutException e) {
304 throw new ExecutionException(e);
308 public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
309 final NormalizedNode<?,?> node) throws Exception {
310 BatchedModifications batched = newBatchedModifications(nextTransactionId(), id, node, true, true, 1);
311 DataTreeModification modification = store.getDataTree().takeSnapshot().newModification();
312 batched.apply(modification);
313 store.notifyListeners(store.commit(modification));
316 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
317 final NormalizedNode<?,?> node) throws DataValidationFailedException {
318 final DataTreeModification transaction = store.takeSnapshot().newModification();
320 transaction.write(id, node);
322 store.validate(transaction);
323 final DataTreeCandidate candidate = store.prepare(transaction);
324 store.commit(candidate);
327 public void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
328 final NormalizedNode<?,?> node) throws Exception {
329 final BatchedModifications batched = new BatchedModifications(nextTransactionId(), CURRENT_VERSION);
330 batched.addModification(new MergeModification(id, node));
331 batched.setReady(true);
332 batched.setDoCommitOnReady(true);
333 batched.setTotalMessagesSent(1);
335 DataTreeModification modification = store.getDataTree().takeSnapshot().newModification();
336 batched.apply(modification);
337 store.notifyListeners(store.commit(modification));
340 DataTree setupInMemorySnapshotStore() throws DataValidationFailedException {
341 final DataTree testStore = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
342 testStore.setSchemaContext(SCHEMA_CONTEXT);
344 writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
346 final NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.EMPTY);
348 InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
349 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
350 Collections.<ReplicatedLogEntry>emptyList(), 0, 1, -1, -1, 1, null, null));
354 static CommitTransactionPayload payloadForModification(final DataTree source, final DataTreeModification mod,
355 final TransactionIdentifier transactionId) throws DataValidationFailedException, IOException {
356 source.validate(mod);
357 final DataTreeCandidate candidate = source.prepare(mod);
358 source.commit(candidate);
359 return CommitTransactionPayload.create(transactionId, candidate);
362 static BatchedModifications newBatchedModifications(final TransactionIdentifier transactionID,
363 final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean ready,
364 final boolean doCommitOnReady, final int messagesSent) {
365 final BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
366 batched.addModification(new WriteModification(path, data));
367 batched.setReady(ready);
368 batched.setDoCommitOnReady(doCommitOnReady);
369 batched.setTotalMessagesSent(messagesSent);
373 @SuppressWarnings("unchecked")
374 static void verifyOuterListEntry(final TestActorRef<Shard> shard, final Object expIDValue) throws Exception {
375 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
376 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
377 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
378 outerList.getValue() instanceof Iterable);
379 final Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
380 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
381 entry instanceof MapEntryNode);
382 final MapEntryNode mapEntry = (MapEntryNode)entry;
383 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
384 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
385 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
386 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", expIDValue, idLeaf.get().getValue());
389 public static DataTreeCandidateTip mockCandidate(final String name) {
390 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
391 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
392 doReturn(ModificationType.WRITE).when(mockCandidateNode).getModificationType();
393 doReturn(Optional.of(ImmutableNodes.containerNode(CarsModel.CARS_QNAME)))
394 .when(mockCandidateNode).getDataAfter();
395 doReturn(CarsModel.BASE_PATH).when(mockCandidate).getRootPath();
396 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
397 return mockCandidate;
400 static DataTreeCandidateTip mockUnmodifiedCandidate(final String name) {
401 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
402 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
403 doReturn(ModificationType.UNMODIFIED).when(mockCandidateNode).getModificationType();
404 doReturn(YangInstanceIdentifier.EMPTY).when(mockCandidate).getRootPath();
405 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
406 return mockCandidate;
409 static void commitTransaction(final DataTree store, final DataTreeModification modification)
410 throws DataValidationFailedException {
411 modification.ready();
412 store.validate(modification);
413 store.commit(store.prepare(modification));
416 @SuppressWarnings("serial")
417 public static final class DelegatingShardCreator implements Creator<Shard> {
418 private final Creator<Shard> delegate;
420 DelegatingShardCreator(final Creator<Shard> delegate) {
421 this.delegate = delegate;
425 public Shard create() throws Exception {
426 return delegate.create();
430 public static class CapturingShardDataTreeCohort extends ShardDataTreeCohort {
431 private volatile ShardDataTreeCohort delegate;
432 private FutureCallback<Void> canCommit;
433 private FutureCallback<DataTreeCandidate> preCommit;
434 private FutureCallback<UnsignedLong> commit;
436 public void setDelegate(final ShardDataTreeCohort delegate) {
437 this.delegate = delegate;
440 public FutureCallback<Void> getCanCommit() {
441 assertNotNull("canCommit was not invoked", canCommit);
445 public FutureCallback<DataTreeCandidate> getPreCommit() {
446 assertNotNull("preCommit was not invoked", preCommit);
450 public FutureCallback<UnsignedLong> getCommit() {
451 assertNotNull("commit was not invoked", commit);
456 public TransactionIdentifier getIdentifier() {
457 return delegate.getIdentifier();
461 DataTreeCandidateTip getCandidate() {
462 return delegate.getCandidate();
466 DataTreeModification getDataTreeModification() {
467 return delegate.getDataTreeModification();
471 public void canCommit(final FutureCallback<Void> callback) {
472 canCommit = mockFutureCallback(callback);
473 delegate.canCommit(canCommit);
477 public void preCommit(final FutureCallback<DataTreeCandidate> callback) {
478 preCommit = mockFutureCallback(callback);
479 delegate.preCommit(preCommit);
483 public void commit(final FutureCallback<UnsignedLong> callback) {
484 commit = mockFutureCallback(callback);
485 delegate.commit(commit);
488 @SuppressWarnings("unchecked")
489 private static <T> FutureCallback<T> mockFutureCallback(final FutureCallback<T> actual) {
490 FutureCallback<T> mock = mock(FutureCallback.class);
491 doAnswer(invocation -> {
492 actual.onFailure(invocation.getArgumentAt(0, Throwable.class));
494 }).when(mock).onFailure(any(Throwable.class));
496 doAnswer(invocation -> {
497 actual.onSuccess((T) invocation.getArgumentAt(0, Throwable.class));
499 }).when(mock).onSuccess((T) any(Object.class));
505 public void abort(final FutureCallback<Void> callback) {
506 delegate.abort(callback);
510 public boolean isFailed() {
511 return delegate.isFailed();
515 public State getState() {
516 return delegate.getState();