2 * Copyright (c) 2016 Cisco 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
9 package org.opendaylight.controller.cluster.sharding;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.mockito.Matchers.anyCollection;
14 import static org.mockito.Matchers.anyMap;
15 import static org.mockito.Mockito.doNothing;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.timeout;
19 import static org.mockito.Mockito.verify;
20 import static org.mockito.Mockito.verifyNoMoreInteractions;
21 import static org.opendaylight.controller.cluster.datastore.IntegrationTestKit.findLocalShard;
22 import static org.opendaylight.controller.cluster.datastore.IntegrationTestKit.waitUntilShardIsDown;
24 import akka.actor.ActorRef;
25 import akka.actor.ActorSystem;
26 import akka.actor.Address;
27 import akka.actor.AddressFromURIString;
28 import akka.cluster.Cluster;
29 import akka.testkit.JavaTestKit;
30 import com.google.common.base.Optional;
31 import com.google.common.collect.Lists;
32 import com.google.common.util.concurrent.CheckedFuture;
33 import com.typesafe.config.ConfigFactory;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.List;
40 import java.util.concurrent.CompletionStage;
41 import org.junit.After;
42 import org.junit.Assert;
43 import org.junit.Before;
44 import org.junit.Test;
45 import org.mockito.ArgumentCaptor;
46 import org.mockito.Captor;
47 import org.mockito.Mockito;
48 import org.mockito.MockitoAnnotations;
49 import org.opendaylight.controller.cluster.ActorSystemProvider;
50 import org.opendaylight.controller.cluster.access.concepts.MemberName;
51 import org.opendaylight.controller.cluster.datastore.AbstractTest;
52 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
53 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
54 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
55 import org.opendaylight.controller.cluster.datastore.IntegrationTestKit;
56 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
57 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
58 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
59 import org.opendaylight.controller.cluster.sharding.DistributedShardFactory.DistributedShardRegistration;
60 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
61 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
62 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
63 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
64 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
65 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
66 import org.opendaylight.mdsal.dom.api.DOMDataTreeListener;
67 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer;
68 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor;
69 import org.opendaylight.yangtools.yang.common.QName;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
73 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
79 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
82 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
86 public class DistributedShardedDOMDataTreeTest extends AbstractTest {
88 private static final Logger LOG = LoggerFactory.getLogger(DistributedShardedDOMDataTreeRemotingTest.class);
90 private static final Address MEMBER_1_ADDRESS =
91 AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558");
93 private static final DOMDataTreeIdentifier TEST_ID =
94 new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH);
96 private static final DOMDataTreeIdentifier INNER_LIST_ID =
97 new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION,
98 YangInstanceIdentifier.create(getOuterListIdFor(0).getPathArguments())
99 .node(TestModel.INNER_LIST_QNAME));
100 private static final Set<MemberName> SINGLE_MEMBER = Collections.singleton(AbstractTest.MEMBER_NAME);
102 private static final String MODULE_SHARDS_CONFIG = "module-shards-cars-member-1.conf";
104 private ActorSystem leaderSystem;
106 private final Builder leaderDatastoreContextBuilder =
107 DatastoreContext.newBuilder()
108 .shardHeartbeatIntervalInMillis(100)
109 .shardElectionTimeoutFactor(2)
111 org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION);
113 private DistributedDataStore leaderDistributedDataStore;
114 private DistributedDataStore operDistributedDatastore;
115 private IntegrationTestKit leaderTestKit;
117 private DistributedShardedDOMDataTree leaderShardFactory;
120 private ArgumentCaptor<Collection<DataTreeCandidate>> captorForChanges;
122 private ArgumentCaptor<Map<DOMDataTreeIdentifier, NormalizedNode<?, ?>>> captorForSubtrees;
124 private ActorSystemProvider leaderSystemProvider;
127 public void setUp() {
128 MockitoAnnotations.initMocks(this);
130 InMemoryJournal.clear();
131 InMemorySnapshotStore.clear();
133 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
134 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
136 leaderSystemProvider = Mockito.mock(ActorSystemProvider.class);
137 doReturn(leaderSystem).when(leaderSystemProvider).getActorSystem();
141 public void tearDown() throws Exception {
142 if (leaderDistributedDataStore != null) {
143 leaderDistributedDataStore.close();
146 if (operDistributedDatastore != null) {
147 operDistributedDatastore.close();
150 JavaTestKit.shutdownActorSystem(leaderSystem);
152 InMemoryJournal.clear();
153 InMemorySnapshotStore.clear();
156 private void initEmptyDatastores() throws Exception {
157 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderDatastoreContextBuilder);
159 leaderDistributedDataStore = leaderTestKit.setupDistributedDataStore(
160 "config", MODULE_SHARDS_CONFIG, "empty-modules.conf", true,
161 SchemaContextHelper.distributedShardedDOMDataTreeSchemaContext());
163 operDistributedDatastore = leaderTestKit.setupDistributedDataStore(
164 "operational", MODULE_SHARDS_CONFIG, "empty-modules.conf",true,
165 SchemaContextHelper.distributedShardedDOMDataTreeSchemaContext());
167 leaderShardFactory = new DistributedShardedDOMDataTree(leaderSystemProvider,
168 operDistributedDatastore,
169 leaderDistributedDataStore);
171 leaderShardFactory.init();
176 public void testWritesIntoDefaultShard() throws Exception {
177 initEmptyDatastores();
179 final DOMDataTreeIdentifier configRoot =
180 new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY);
182 final DOMDataTreeProducer producer = leaderShardFactory.createProducer(Collections.singleton(configRoot));
184 final DOMDataTreeCursorAwareTransaction tx = producer.createTransaction(true);
185 final DOMDataTreeWriteCursor cursor =
186 tx.createCursor(new DOMDataTreeIdentifier(
187 LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY));
188 Assert.assertNotNull(cursor);
190 final ContainerNode test =
191 ImmutableContainerNodeBuilder.create()
192 .withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME)).build();
194 cursor.write(test.getIdentifier(), test);
197 tx.submit().checkedGet();
201 public void testSingleNodeWrites() throws Exception {
202 initEmptyDatastores();
204 final DistributedShardRegistration shardRegistration = waitOnAsyncTask(
205 leaderShardFactory.createDistributedShard(TEST_ID, Lists.newArrayList(AbstractTest.MEMBER_NAME)),
206 DistributedShardedDOMDataTree.SHARD_FUTURE_TIMEOUT_DURATION);
208 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(),
209 ClusterUtils.getCleanShardName(TEST_ID.getRootIdentifier()));
211 final DOMDataTreeProducer producer = leaderShardFactory.createProducer(Collections.singleton(TEST_ID));
213 final DOMDataTreeCursorAwareTransaction tx = producer.createTransaction(true);
214 final DOMDataTreeWriteCursor cursor = tx.createCursor(TEST_ID);
215 Assert.assertNotNull(cursor);
216 final YangInstanceIdentifier nameId =
217 YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(TestModel.NAME_QNAME).build();
218 final LeafNode<String> valueToCheck = ImmutableLeafNodeBuilder.<String>create().withNodeIdentifier(
219 new NodeIdentifier(TestModel.NAME_QNAME)).withValue("Test Value").build();
220 LOG.debug("Writing data {} at {}, cursor {}", nameId.getLastPathArgument(), valueToCheck, cursor);
221 cursor.write(nameId.getLastPathArgument(),
225 LOG.debug("Got to pre submit");
227 tx.submit().checkedGet();
229 final DOMDataTreeListener mockedDataTreeListener = mock(DOMDataTreeListener.class);
230 doNothing().when(mockedDataTreeListener).onDataTreeChanged(anyCollection(), anyMap());
232 leaderShardFactory.registerListener(mockedDataTreeListener, Collections.singletonList(TEST_ID),
233 true, Collections.emptyList());
235 verify(mockedDataTreeListener, timeout(1000).times(1)).onDataTreeChanged(captorForChanges.capture(),
236 captorForSubtrees.capture());
237 final List<Collection<DataTreeCandidate>> capturedValue = captorForChanges.getAllValues();
239 final Optional<NormalizedNode<?, ?>> dataAfter =
240 capturedValue.get(0).iterator().next().getRootNode().getDataAfter();
242 final NormalizedNode<?,?> expected = ImmutableContainerNodeBuilder.create()
243 .withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME)).withChild(valueToCheck).build();
244 assertEquals(expected, dataAfter.get());
246 verifyNoMoreInteractions(mockedDataTreeListener);
248 shardRegistration.close().toCompletableFuture().get();
253 public void testMultipleWritesIntoSingleMapEntry() throws Exception {
254 initEmptyDatastores();
256 final DistributedShardRegistration shardRegistration = waitOnAsyncTask(
257 leaderShardFactory.createDistributedShard(TEST_ID, Lists.newArrayList(AbstractTest.MEMBER_NAME)),
258 DistributedShardedDOMDataTree.SHARD_FUTURE_TIMEOUT_DURATION);
260 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(),
261 ClusterUtils.getCleanShardName(TEST_ID.getRootIdentifier()));
263 LOG.warn("Got after waiting for nonleader");
264 final ActorRef leaderShardManager = leaderDistributedDataStore.getActorContext().getShardManager();
266 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(),
267 ClusterUtils.getCleanShardName(TestModel.TEST_PATH));
269 final YangInstanceIdentifier oid1 = getOuterListIdFor(0);
270 final DOMDataTreeIdentifier outerListPath = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, oid1);
272 final DistributedShardRegistration outerListShardReg = waitOnAsyncTask(
273 leaderShardFactory.createDistributedShard(outerListPath, Lists.newArrayList(AbstractTest.MEMBER_NAME)),
274 DistributedShardedDOMDataTree.SHARD_FUTURE_TIMEOUT_DURATION);
276 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(),
277 ClusterUtils.getCleanShardName(outerListPath.getRootIdentifier()));
279 final DOMDataTreeProducer shardProducer = leaderShardFactory.createProducer(
280 Collections.singletonList(outerListPath));
282 final DOMDataTreeCursorAwareTransaction tx = shardProducer.createTransaction(false);
283 final DOMDataTreeWriteCursor cursor =
284 tx.createCursor(new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, oid1));
285 assertNotNull(cursor);
287 MapNode innerList = ImmutableMapNodeBuilder
289 .withNodeIdentifier(new NodeIdentifier(TestModel.INNER_LIST_QNAME))
292 cursor.write(new NodeIdentifier(TestModel.INNER_LIST_QNAME), innerList);
294 tx.submit().checkedGet();
296 final ArrayList<CheckedFuture<Void, TransactionCommitFailedException>> futures = new ArrayList<>();
297 for (int i = 0; i < 1000; i++) {
298 final Collection<MapEntryNode> innerListMapEntries = createInnerListMapEntries(1000, "run-" + i);
299 for (final MapEntryNode innerListMapEntry : innerListMapEntries) {
300 final DOMDataTreeCursorAwareTransaction tx1 = shardProducer.createTransaction(false);
301 final DOMDataTreeWriteCursor cursor1 = tx1.createCursor(
302 new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION,
303 oid1.node(new NodeIdentifier(TestModel.INNER_LIST_QNAME))));
304 cursor1.write(innerListMapEntry.getIdentifier(), innerListMapEntry);
306 futures.add(tx1.submit());
310 futures.get(futures.size() - 1).checkedGet();
312 final DOMDataTreeListener mockedDataTreeListener = mock(DOMDataTreeListener.class);
313 doNothing().when(mockedDataTreeListener).onDataTreeChanged(anyCollection(), anyMap());
315 leaderShardFactory.registerListener(mockedDataTreeListener, Collections.singletonList(INNER_LIST_ID),
316 true, Collections.emptyList());
318 verify(mockedDataTreeListener, timeout(1000).times(1)).onDataTreeChanged(captorForChanges.capture(),
319 captorForSubtrees.capture());
320 verifyNoMoreInteractions(mockedDataTreeListener);
321 final List<Collection<DataTreeCandidate>> capturedValue = captorForChanges.getAllValues();
323 final NormalizedNode<?,?> expected =
324 ImmutableMapNodeBuilder
326 .withNodeIdentifier(new NodeIdentifier(TestModel.INNER_LIST_QNAME))
327 // only the values from the last run should be present
328 .withValue(createInnerListMapEntries(1000, "run-999"))
331 assertEquals("List values dont match the expected values from the last run",
332 expected, capturedValue.get(0).iterator().next().getRootNode().getDataAfter().get());
336 // top level shard at TEST element, with subshards on each outer-list map entry
338 public void testMultipleShardLevels() throws Exception {
339 initEmptyDatastores();
341 final DistributedShardRegistration testShardReg = waitOnAsyncTask(
342 leaderShardFactory.createDistributedShard(TEST_ID, SINGLE_MEMBER),
343 DistributedShardedDOMDataTree.SHARD_FUTURE_TIMEOUT_DURATION);
345 final ArrayList<DistributedShardRegistration> registrations = new ArrayList<>();
346 final int listSize = 5;
347 for (int i = 0; i < listSize; i++) {
348 final YangInstanceIdentifier entryYID = getOuterListIdFor(i);
349 final CompletionStage<DistributedShardRegistration> future = leaderShardFactory.createDistributedShard(
350 new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, entryYID), SINGLE_MEMBER);
352 registrations.add(waitOnAsyncTask(future, DistributedShardedDOMDataTree.SHARD_FUTURE_TIMEOUT_DURATION));
355 final DOMDataTreeIdentifier rootId =
356 new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY);
357 final DOMDataTreeProducer producer = leaderShardFactory.createProducer(Collections.singletonList(
360 DOMDataTreeCursorAwareTransaction transaction = producer.createTransaction(false);
362 DOMDataTreeWriteCursor cursor = transaction.createCursor(rootId);
363 assertNotNull(cursor);
365 final MapNode outerList =
366 ImmutableMapNodeBuilder.create()
367 .withNodeIdentifier(new NodeIdentifier(TestModel.OUTER_LIST_QNAME)).build();
369 final ContainerNode testNode =
370 ImmutableContainerNodeBuilder.create()
371 .withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME))
372 .withChild(outerList)
375 cursor.write(testNode.getIdentifier(), testNode);
378 transaction.submit().checkedGet();
380 final DOMDataTreeListener mockedDataTreeListener = mock(DOMDataTreeListener.class);
381 doNothing().when(mockedDataTreeListener).onDataTreeChanged(anyCollection(), anyMap());
383 final MapNode wholeList = ImmutableMapNodeBuilder.create(outerList)
384 .withValue(createOuterEntries(listSize, "testing-values")).build();
386 transaction = producer.createTransaction(false);
387 cursor = transaction.createCursor(TEST_ID);
388 assertNotNull(cursor);
390 cursor.write(wholeList.getIdentifier(), wholeList);
393 transaction.submit().checkedGet();
395 leaderShardFactory.registerListener(mockedDataTreeListener, Collections.singletonList(TEST_ID),
396 true, Collections.emptyList());
398 verify(mockedDataTreeListener, timeout(35000).atLeast(2)).onDataTreeChanged(captorForChanges.capture(),
399 captorForSubtrees.capture());
400 verifyNoMoreInteractions(mockedDataTreeListener);
401 final List<Map<DOMDataTreeIdentifier, NormalizedNode<?, ?>>> allSubtrees = captorForSubtrees.getAllValues();
403 final Map<DOMDataTreeIdentifier, NormalizedNode<?, ?>> lastSubtree = allSubtrees.get(allSubtrees.size() - 1);
405 final NormalizedNode<?, ?> actual = lastSubtree.get(TEST_ID);
406 assertNotNull(actual);
408 final NormalizedNode<?, ?> expected =
409 ImmutableContainerNodeBuilder.create()
410 .withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME))
411 .withChild(ImmutableMapNodeBuilder.create(outerList)
412 .withValue(createOuterEntries(listSize, "testing-values")).build())
416 for (final DistributedShardRegistration registration : registrations) {
417 waitOnAsyncTask(registration.close(), DistributedShardedDOMDataTree.SHARD_FUTURE_TIMEOUT_DURATION);
420 waitOnAsyncTask(testShardReg.close(), DistributedShardedDOMDataTree.SHARD_FUTURE_TIMEOUT_DURATION);
422 assertEquals(expected, actual);
426 public void testMultipleRegistrationsAtOnePrefix() throws Exception {
427 initEmptyDatastores();
429 for (int i = 0; i < 10; i++) {
430 LOG.debug("Round {}", i);
431 final DistributedShardRegistration reg1 = waitOnAsyncTask(leaderShardFactory.createDistributedShard(
432 TEST_ID, Lists.newArrayList(AbstractTest.MEMBER_NAME)),
433 DistributedShardedDOMDataTree.SHARD_FUTURE_TIMEOUT_DURATION);
435 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(),
436 ClusterUtils.getCleanShardName(TestModel.TEST_PATH));
438 assertNotNull(findLocalShard(leaderDistributedDataStore.getActorContext(),
439 ClusterUtils.getCleanShardName(TestModel.TEST_PATH)));
441 waitOnAsyncTask(reg1.close(), DistributedShardedDOMDataTree.SHARD_FUTURE_TIMEOUT_DURATION);
443 waitUntilShardIsDown(leaderDistributedDataStore.getActorContext(),
444 ClusterUtils.getCleanShardName(TestModel.TEST_PATH));
448 private static Collection<MapEntryNode> createOuterEntries(final int amount, final String valuePrefix) {
449 final Collection<MapEntryNode> ret = new ArrayList<>();
450 for (int i = 0; i < amount; i++) {
451 ret.add(ImmutableNodes.mapEntryBuilder()
452 .withNodeIdentifier(new NodeIdentifierWithPredicates(TestModel.OUTER_LIST_QNAME,
453 QName.create(TestModel.OUTER_LIST_QNAME, "id"), i))
454 .withChild(ImmutableNodes
455 .leafNode(QName.create(TestModel.OUTER_LIST_QNAME, "id"), i))
456 .withChild(createWholeInnerList(amount, "outer id: " + i + " " + valuePrefix))
463 private static MapNode createWholeInnerList(final int amount, final String valuePrefix) {
464 return ImmutableMapNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(TestModel.INNER_LIST_QNAME))
465 .withValue(createInnerListMapEntries(amount, valuePrefix)).build();
468 private static Collection<MapEntryNode> createInnerListMapEntries(final int amount, final String valuePrefix) {
469 final Collection<MapEntryNode> ret = new ArrayList<>();
470 for (int i = 0; i < amount; i++) {
471 ret.add(ImmutableNodes.mapEntryBuilder()
472 .withNodeIdentifier(new NodeIdentifierWithPredicates(TestModel.INNER_LIST_QNAME,
473 QName.create(TestModel.INNER_LIST_QNAME, "name"), Integer.toString(i)))
474 .withChild(ImmutableNodes
475 .leafNode(QName.create(TestModel.INNER_LIST_QNAME, "value"), valuePrefix + "-" + i))
482 private static YangInstanceIdentifier getOuterListIdFor(final int id) {
483 return TestModel.OUTER_LIST_PATH.node(new NodeIdentifierWithPredicates(
484 TestModel.OUTER_LIST_QNAME, QName.create(TestModel.OUTER_LIST_QNAME, "id"), id));