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.datastore.DatastoreContext.Builder;
46 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
47 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
48 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
49 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
50 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
51 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
52 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
53 import org.opendaylight.controller.cluster.raft.Snapshot;
54 import org.opendaylight.controller.cluster.raft.TestActorFactory;
55 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
56 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
57 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
58 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
61 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
62 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
65 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateTip;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
72 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
73 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import scala.concurrent.Await;
76 import scala.concurrent.Future;
77 import scala.concurrent.duration.Duration;
80 * Abstract base for shard unit tests.
82 * @author Thomas Pantelis
84 public abstract class AbstractShardTest extends AbstractActorTest{
85 protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
87 private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
89 protected final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1")
90 .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build();
92 protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
93 shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
94 shardHeartbeatIntervalInMillis(100);
96 protected final TestActorFactory actorFactory = new TestActorFactory(getSystem());
100 InMemorySnapshotStore.clear();
101 InMemoryJournal.clear();
105 public void tearDown() {
106 InMemorySnapshotStore.clear();
107 InMemoryJournal.clear();
108 actorFactory.close();
111 protected DatastoreContext newDatastoreContext() {
112 return dataStoreContextBuilder.build();
115 protected Props newShardProps() {
116 return newShardBuilder().props();
119 protected Shard.Builder newShardBuilder() {
120 return Shard.builder().id(shardID).datastoreContext(newDatastoreContext()).schemaContext(SCHEMA_CONTEXT);
123 protected void testRecovery(final Set<Integer> listEntryKeys) throws Exception {
124 // Create the actor and wait for recovery complete.
126 final int nListEntries = listEntryKeys.size();
128 final CountDownLatch recoveryComplete = new CountDownLatch(1);
130 @SuppressWarnings("serial")
132 Creator<Shard> creator = new Creator<Shard>() {
134 public Shard create() throws Exception {
135 return new Shard(newShardBuilder()) {
137 protected void onRecoveryComplete() {
139 super.onRecoveryComplete();
141 recoveryComplete.countDown();
148 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
149 Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
151 assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
153 // Verify data in the data store.
155 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
156 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
157 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
158 outerList.getValue() instanceof Iterable);
159 for(final Object entry: (Iterable<?>) outerList.getValue()) {
160 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
161 entry instanceof MapEntryNode);
162 final MapEntryNode mapEntry = (MapEntryNode)entry;
163 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
164 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
165 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
166 final Object value = idLeaf.get().getValue();
167 assertTrue("Unexpected value for leaf "+ TestModel.ID_QNAME.getLocalName() + ": " + value,
168 listEntryKeys.remove(value));
171 if(!listEntryKeys.isEmpty()) {
172 fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
176 assertEquals("Last log index", nListEntries,
177 shard.underlyingActor().getShardMBean().getLastLogIndex());
178 assertEquals("Commit index", nListEntries,
179 shard.underlyingActor().getShardMBean().getCommitIndex());
180 assertEquals("Last applied", nListEntries,
181 shard.underlyingActor().getShardMBean().getLastApplied());
183 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
186 protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
187 long lastApplied = -1;
188 for(int i = 0; i < 20 * 5; i++) {
189 lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
190 if(lastApplied == expectedValue) {
193 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
196 Assert.fail(String.format("Expected last applied: %d, Actual: %d", expectedValue, lastApplied));
199 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
200 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
201 final MutableCompositeModification modification) {
202 return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null);
205 protected ShardDataTreeCohort setupMockWriteTransaction(final String cohortName,
206 final ShardDataTree dataStore, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data,
207 final MutableCompositeModification modification,
208 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
210 final ReadWriteShardDataTreeTransaction tx = dataStore.newReadWriteTransaction("setup-mock-" + cohortName, null);
211 tx.getSnapshot().write(path, data);
212 final ShardDataTreeCohort cohort = createDelegatingMockCohort(cohortName, dataStore.finishTransaction(tx), preCommit);
214 modification.addModification(new WriteModification(path, data));
219 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
220 final ShardDataTreeCohort actual) {
221 return createDelegatingMockCohort(cohortName, actual, null);
224 protected ShardDataTreeCohort createDelegatingMockCohort(final String cohortName,
225 final ShardDataTreeCohort actual,
226 final Function<ShardDataTreeCohort, ListenableFuture<Void>> preCommit) {
227 final ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class, cohortName);
229 doAnswer(new Answer<ListenableFuture<Boolean>>() {
231 public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
232 return actual.canCommit();
234 }).when(cohort).canCommit();
236 doAnswer(new Answer<ListenableFuture<Void>>() {
238 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
239 if(preCommit != null) {
240 return preCommit.apply(actual);
242 return actual.preCommit();
245 }).when(cohort).preCommit();
247 doAnswer(new Answer<ListenableFuture<Void>>() {
249 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
250 return actual.commit();
252 }).when(cohort).commit();
254 doAnswer(new Answer<ListenableFuture<Void>>() {
256 public ListenableFuture<Void> answer(final InvocationOnMock invocation) throws Throwable {
257 return actual.abort();
259 }).when(cohort).abort();
261 doAnswer(new Answer<DataTreeCandidateTip>() {
263 public DataTreeCandidateTip answer(final InvocationOnMock invocation) {
264 return actual.getCandidate();
266 }).when(cohort).getCandidate();
271 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
272 String transactionID,
273 MutableCompositeModification modification,
274 boolean doCommitOnReady) {
275 if(remoteReadWriteTransaction){
276 return prepareForwardedReadyTransaction(cohort, transactionID, CURRENT_VERSION,
279 setupCohortDecorator(shard, cohort);
280 return prepareBatchedModifications(transactionID, modification, doCommitOnReady);
284 protected ShardDataTreeCohort mockShardDataTreeCohort() {
285 ShardDataTreeCohort cohort = mock(ShardDataTreeCohort.class);
286 doReturn(Futures.immediateFuture(Boolean.TRUE)).when(cohort).canCommit();
287 doReturn(Futures.immediateFuture(null)).when(cohort).preCommit();
288 doReturn(Futures.immediateFuture(null)).when(cohort).commit();
289 doReturn(mockCandidate("candidate")).when(cohort).getCandidate();
293 static ShardDataTreeTransactionParent newShardDataTreeTransactionParent(ShardDataTreeCohort cohort) {
294 ShardDataTreeTransactionParent mockParent = mock(ShardDataTreeTransactionParent.class);
295 doReturn(cohort).when(mockParent).finishTransaction(any(ReadWriteShardDataTreeTransaction.class));
296 doNothing().when(mockParent).abortTransaction(any(AbstractShardDataTreeTransaction.class));
300 protected ForwardedReadyTransaction prepareForwardedReadyTransaction(ShardDataTreeCohort cohort,
301 String transactionID, short version, boolean doCommitOnReady) {
302 return new ForwardedReadyTransaction(transactionID, version,
303 new ReadWriteShardDataTreeTransaction(newShardDataTreeTransactionParent(cohort), transactionID,
304 mock(DataTreeModification.class)), doCommitOnReady);
307 protected Object prepareReadyTransactionMessage(boolean remoteReadWriteTransaction, Shard shard, ShardDataTreeCohort cohort,
308 String transactionID,
309 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(String transactionID, ShardDataTreeCohort actual) {
322 protected BatchedModifications prepareBatchedModifications(String transactionID,
323 MutableCompositeModification modification) {
324 return prepareBatchedModifications(transactionID, modification, false);
327 private static BatchedModifications prepareBatchedModifications(String transactionID,
328 MutableCompositeModification modification,
329 boolean doCommitOnReady) {
330 final BatchedModifications batchedModifications = new BatchedModifications(transactionID, CURRENT_VERSION, null);
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 static void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
349 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
350 Future<Object> future = Patterns.ask(shard, newBatchedModifications("tx", 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("writeToStore", null);
363 transaction.getSnapshot().write(id, node);
364 final ShardDataTreeCohort cohort = transaction.ready();
365 cohort.canCommit().get();
366 cohort.preCommit().get();
370 public static void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
371 final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
372 final ReadWriteShardDataTreeTransaction transaction = store.newReadWriteTransaction("writeToStore", null);
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.builder().build());
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 String transactionID, final YangInstanceIdentifier path,
414 final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady, final int messagesSent) {
415 return newBatchedModifications(transactionID, null, path, data, ready, doCommitOnReady, messagesSent);
418 static BatchedModifications newBatchedModifications(final String transactionID, final String transactionChainID,
419 final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady,
420 final int messagesSent) {
421 final BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION, transactionChainID);
422 batched.addModification(new WriteModification(path, data));
423 batched.setReady(ready);
424 batched.setDoCommitOnReady(doCommitOnReady);
425 batched.setTotalMessagesSent(messagesSent);
429 @SuppressWarnings("unchecked")
430 static void verifyOuterListEntry(final TestActorRef<Shard> shard, final Object expIDValue) throws Exception {
431 final NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
432 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
433 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
434 outerList.getValue() instanceof Iterable);
435 final Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
436 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
437 entry instanceof MapEntryNode);
438 final MapEntryNode mapEntry = (MapEntryNode)entry;
439 final Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
440 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
441 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
442 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", expIDValue, idLeaf.get().getValue());
445 public static DataTreeCandidateTip mockCandidate(final String name) {
446 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
447 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
448 doReturn(ModificationType.WRITE).when(mockCandidateNode).getModificationType();
449 doReturn(Optional.of(ImmutableNodes.containerNode(CarsModel.CARS_QNAME))).when(mockCandidateNode).getDataAfter();
450 doReturn(CarsModel.BASE_PATH).when(mockCandidate).getRootPath();
451 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
452 return mockCandidate;
455 static DataTreeCandidateTip mockUnmodifiedCandidate(final String name) {
456 final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
457 final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
458 doReturn(ModificationType.UNMODIFIED).when(mockCandidateNode).getModificationType();
459 doReturn(YangInstanceIdentifier.builder().build()).when(mockCandidate).getRootPath();
460 doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
461 return mockCandidate;
464 static void commitTransaction(final DataTree store, final DataTreeModification modification) throws DataValidationFailedException {
465 modification.ready();
466 store.validate(modification);
467 store.commit(store.prepare(modification));
470 @SuppressWarnings("serial")
471 public static final class DelegatingShardCreator implements Creator<Shard> {
472 private final Creator<Shard> delegate;
474 DelegatingShardCreator(final Creator<Shard> delegate) {
475 this.delegate = delegate;
479 public Shard create() throws Exception {
480 return delegate.create();