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.PreBoronShardDataTreeSnapshot;
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()).schemaContext(SCHEMA_CONTEXT);
131 protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
132 // Create the actor and wait for recovery complete.
134 final int nListEntries = listEntryKeys.size();
136 final CountDownLatch recoveryComplete = new CountDownLatch(1);
138 final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
140 protected void onRecoveryComplete() {
142 super.onRecoveryComplete();
144 recoveryComplete.countDown();
149 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
150 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
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: " + listEntryKeys);
177 assertEquals("Last log index", nListEntries,
178 shard.underlyingActor().getShardMBean().getLastLogIndex());
179 assertEquals("Commit index", nListEntries,
180 shard.underlyingActor().getShardMBean().getCommitIndex());
181 assertEquals("Last applied", nListEntries,
182 shard.underlyingActor().getShardMBean().getLastApplied());
184 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
187 protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
188 long lastApplied = -1;
189 for (int i = 0; i < 20 * 5; i++) {
190 lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
191 if (lastApplied == expectedValue) {
194 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
197 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
200 protected TipProducingDataTree createDelegatingMockDataTree() throws Exception {
201 TipProducingDataTree actual = InMemoryDataTreeFactory.getInstance().create(TreeType.CONFIGURATION);
202 final TipProducingDataTree mock = mock(TipProducingDataTree.class);
204 doAnswer(invocation -> {
205 actual.validate(invocation.getArgumentAt(0, DataTreeModification.class));
207 }).when(mock).validate(any(DataTreeModification.class));
209 doAnswer(invocation -> {
210 return actual.prepare(invocation.getArgumentAt(0, DataTreeModification.class));
211 }).when(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 -> {
224 return actual.takeSnapshot();
225 }).when(mock).takeSnapshot();
227 doAnswer(invocation -> {
228 return actual.getRootPath();
229 }).when(mock).getRootPath();
234 protected ShardDataTreeCohort mockShardDataTreeCohort() {
235 ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class);
236 DataTreeCandidate candidate = mockCandidate("candidate");
237 successfulCanCommit(cohort);
238 successfulPreCommit(cohort, candidate);
239 successfulCommit(cohort);
240 doReturn(candidate).when(cohort).getCandidate();
244 protected Map<TransactionIdentifier, CapturingShardDataTreeCohort> setupCohortDecorator(final Shard shard,
245 final TransactionIdentifier... transactionIDs) {
246 final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = new HashMap<>();
247 for (TransactionIdentifier id: transactionIDs) {
248 cohortMap.put(id, new CapturingShardDataTreeCohort());
251 shard.getCommitCoordinator().setCohortDecorator((transactionID, actual) -> {
252 CapturingShardDataTreeCohort cohort = cohortMap.get(transactionID);
253 cohort.setDelegate(actual);
260 protected BatchedModifications prepareBatchedModifications(final TransactionIdentifier transactionID,
261 final MutableCompositeModification modification) {
262 return prepareBatchedModifications(transactionID, modification, false);
265 protected static BatchedModifications prepareBatchedModifications(final TransactionIdentifier transactionID,
266 final MutableCompositeModification modification,
267 final boolean doCommitOnReady) {
268 final BatchedModifications batchedModifications = new BatchedModifications(transactionID, CURRENT_VERSION);
269 batchedModifications.addModification(modification);
270 batchedModifications.setReady(true);
271 batchedModifications.setDoCommitOnReady(doCommitOnReady);
272 batchedModifications.setTotalMessagesSent(1);
273 return batchedModifications;
276 protected static BatchedModifications prepareBatchedModifications(final TransactionIdentifier transactionID,
277 final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean doCommitOnReady) {
278 final MutableCompositeModification modification = new MutableCompositeModification();
279 modification.addModification(new WriteModification(path, data));
280 return prepareBatchedModifications(transactionID, modification, doCommitOnReady);
283 protected static ForwardedReadyTransaction prepareForwardedReadyTransaction(final TestActorRef<Shard> shard,
284 final TransactionIdentifier transactionID, final YangInstanceIdentifier path,
285 final NormalizedNode<?, ?> data, final boolean doCommitOnReady) {
286 ReadWriteShardDataTreeTransaction rwTx = shard.underlyingActor().getDataStore()
287 .newReadWriteTransaction(transactionID);
288 rwTx.getSnapshot().write(path, data);
289 return new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, rwTx, doCommitOnReady);
292 public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard,
293 final YangInstanceIdentifier id) throws ExecutionException, InterruptedException {
294 return shard.underlyingActor().getDataStore().readNode(id).orNull();
297 public static NormalizedNode<?,?> readStore(final DataTree store, final YangInstanceIdentifier id) {
298 return store.takeSnapshot().readNode(id).orNull();
301 public void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
302 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
303 Future<Object> future = Patterns.ask(shard, newBatchedModifications(nextTransactionId(),
304 id, node, true, true, 1), new Timeout(5, TimeUnit.SECONDS));
306 Await.ready(future, Duration.create(5, TimeUnit.SECONDS));
307 } catch (TimeoutException e) {
308 throw new ExecutionException(e);
312 public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
313 final NormalizedNode<?,?> node) throws Exception {
314 BatchedModifications batched = newBatchedModifications(nextTransactionId(), id, node, true, true, 1);
315 DataTreeModification modification = store.getDataTree().takeSnapshot().newModification();
316 batched.apply(modification);
317 store.notifyListeners(store.commit(modification));
320 public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
321 final NormalizedNode<?,?> node) throws DataValidationFailedException {
322 final DataTreeModification transaction = store.takeSnapshot().newModification();
324 transaction.write(id, node);
326 store.validate(transaction);
327 final DataTreeCandidate candidate = store.prepare(transaction);
328 store.commit(candidate);
331 public void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
332 final NormalizedNode<?,?> node) throws Exception {
333 final BatchedModifications batched = new BatchedModifications(nextTransactionId(), CURRENT_VERSION);
334 batched.addModification(new MergeModification(id, node));
335 batched.setReady(true);
336 batched.setDoCommitOnReady(true);
337 batched.setTotalMessagesSent(1);
339 DataTreeModification modification = store.getDataTree().takeSnapshot().newModification();
340 batched.apply(modification);
341 store.notifyListeners(store.commit(modification));
344 DataTree setupInMemorySnapshotStore() throws DataValidationFailedException {
345 final DataTree testStore = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
346 testStore.setSchemaContext(SCHEMA_CONTEXT);
348 writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
350 final NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.EMPTY);
352 InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
353 new ShardSnapshotState(new PreBoronShardDataTreeSnapshot(root)),
354 Collections.<ReplicatedLogEntry>emptyList(), 0, 1, -1, -1, 1, null, null));
358 static CommitTransactionPayload payloadForModification(final DataTree source, final DataTreeModification mod,
359 final TransactionIdentifier transactionId) throws DataValidationFailedException, IOException {
360 source.validate(mod);
361 final DataTreeCandidate candidate = source.prepare(mod);
362 source.commit(candidate);
363 return CommitTransactionPayload.create(transactionId, candidate);
366 static BatchedModifications newBatchedModifications(final TransactionIdentifier transactionID,
367 final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean ready,
368 final boolean doCommitOnReady, final int messagesSent) {
369 final BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
370 batched.addModification(new WriteModification(path, data));
371 batched.setReady(ready);
372 batched.setDoCommitOnReady(doCommitOnReady);
373 batched.setTotalMessagesSent(messagesSent);
377 @SuppressWarnings("unchecked")
378 static void verifyOuterListEntry(final TestActorRef<Shard> shard, final Object expIDValue) throws Exception {
379 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
380 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
381 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
382 outerList.getValue() instanceof Iterable);
383 final Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
384 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
385 entry instanceof MapEntryNode);
386 final MapEntryNode mapEntry = (MapEntryNode)entry;
387 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
388 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
389 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
390 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", expIDValue, idLeaf.get().getValue());
393 public static DataTreeCandidateTip mockCandidate(final String name) {
394 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
395 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
396 doReturn(ModificationType.WRITE).when(mockCandidateNode).getModificationType();
397 doReturn(Optional.of(ImmutableNodes.containerNode(CarsModel.CARS_QNAME)))
398 .when(mockCandidateNode).getDataAfter();
399 doReturn(CarsModel.BASE_PATH).when(mockCandidate).getRootPath();
400 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
401 return mockCandidate;
404 static DataTreeCandidateTip mockUnmodifiedCandidate(final String name) {
405 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
406 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
407 doReturn(ModificationType.UNMODIFIED).when(mockCandidateNode).getModificationType();
408 doReturn(YangInstanceIdentifier.EMPTY).when(mockCandidate).getRootPath();
409 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
410 return mockCandidate;
413 static void commitTransaction(final DataTree store, final DataTreeModification modification)
414 throws DataValidationFailedException {
415 modification.ready();
416 store.validate(modification);
417 store.commit(store.prepare(modification));
420 @SuppressWarnings("serial")
421 public static final class DelegatingShardCreator implements Creator<Shard> {
422 private final Creator<Shard> delegate;
424 DelegatingShardCreator(final Creator<Shard> delegate) {
425 this.delegate = delegate;
429 public Shard create() throws Exception {
430 return delegate.create();
434 public static class CapturingShardDataTreeCohort extends ShardDataTreeCohort {
435 private volatile ShardDataTreeCohort delegate;
436 private FutureCallback<Void> canCommit;
437 private FutureCallback<DataTreeCandidate> preCommit;
438 private FutureCallback<UnsignedLong> commit;
440 public void setDelegate(final ShardDataTreeCohort delegate) {
441 this.delegate = delegate;
444 public FutureCallback<Void> getCanCommit() {
445 assertNotNull("canCommit was not invoked", canCommit);
449 public FutureCallback<DataTreeCandidate> getPreCommit() {
450 assertNotNull("preCommit was not invoked", preCommit);
454 public FutureCallback<UnsignedLong> getCommit() {
455 assertNotNull("commit was not invoked", commit);
460 public TransactionIdentifier getIdentifier() {
461 return delegate.getIdentifier();
465 DataTreeCandidateTip getCandidate() {
466 return delegate.getCandidate();
470 DataTreeModification getDataTreeModification() {
471 return delegate.getDataTreeModification();
475 public void canCommit(final FutureCallback<Void> callback) {
476 canCommit = mockFutureCallback(callback);
477 delegate.canCommit(canCommit);
481 public void preCommit(final FutureCallback<DataTreeCandidate> callback) {
482 preCommit = mockFutureCallback(callback);
483 delegate.preCommit(preCommit);
487 public void commit(final FutureCallback<UnsignedLong> callback) {
488 commit = mockFutureCallback(callback);
489 delegate.commit(commit);
492 @SuppressWarnings("unchecked")
493 private static <T> FutureCallback<T> mockFutureCallback(final FutureCallback<T> actual) {
494 FutureCallback<T> mock = mock(FutureCallback.class);
495 doAnswer(invocation -> {
496 actual.onFailure(invocation.getArgumentAt(0, Throwable.class));
498 }).when(mock).onFailure(any(Throwable.class));
500 doAnswer(invocation -> {
501 actual.onSuccess((T) invocation.getArgumentAt(0, Throwable.class));
503 }).when(mock).onSuccess((T) any(Object.class));
509 public void abort(final FutureCallback<Void> callback) {
510 delegate.abort(callback);
514 public boolean isFailed() {
515 return delegate.isFailed();
519 public State getState() {
520 return delegate.getState();