058769544c0c0ed951192f904973af188ddbf4ed
[mdsal.git] / dom / mdsal-dom-broker / src / test / java / org / opendaylight / mdsal / dom / broker / ShardedDOMDataTreeTest.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.dom.broker;
9
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.anyCollection;
15 import static org.mockito.Matchers.anyMap;
16 import static org.mockito.Mockito.doNothing;
17 import static org.mockito.Mockito.timeout;
18 import static org.mockito.Mockito.verify;
19 import static org.mockito.Mockito.verifyNoMoreInteractions;
20
21 import com.google.common.util.concurrent.CheckedFuture;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
29 import org.junit.Before;
30 import org.junit.Test;
31 import org.mockito.ArgumentCaptor;
32 import org.mockito.Captor;
33 import org.mockito.Mockito;
34 import org.mockito.MockitoAnnotations;
35 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
36 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
37 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
38 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
39 import org.opendaylight.mdsal.dom.api.DOMDataTreeListener;
40 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor;
42 import org.opendaylight.mdsal.dom.broker.util.TestModel;
43 import org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataTreeShard;
44 import org.opendaylight.yangtools.concepts.ListenerRegistration;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
49 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
55 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
56 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
57 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
58 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 public class ShardedDOMDataTreeTest {
65
66     private static final Logger LOG = LoggerFactory.getLogger(ShardedDOMDataTreeProducerMultiShardTest.class);
67
68     private static SchemaContext schemaContext = null;
69
70     static {
71         try {
72             schemaContext = TestModel.createTestContext();
73         } catch (final ReactorException e) {
74             LOG.error("Unable to create schema context for TestModel", e);
75         }
76     }
77
78     private static final DOMDataTreeIdentifier ROOT_ID =
79             new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.EMPTY);
80     private static final DOMDataTreeIdentifier TEST_ID =
81             new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH);
82
83     private static final DOMDataTreeIdentifier INNER_CONTAINER_ID =
84             new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, TestModel.INNER_CONTAINER_PATH);
85
86     private InMemoryDOMDataTreeShard rootShard;
87
88     private ShardedDOMDataTree dataTreeService;
89     private ListenerRegistration<InMemoryDOMDataTreeShard> rootShardReg;
90
91     private final ExecutorService executor = Executors.newSingleThreadExecutor();
92
93     @Captor
94     private ArgumentCaptor<Collection<DataTreeCandidate>> captorForChanges;
95     @Captor
96     private ArgumentCaptor<Map<DOMDataTreeIdentifier, NormalizedNode<?, ?>>> captorForSubtrees;
97
98     private final ContainerNode crossShardContainer = createCrossShardContainer();
99
100     @Before
101     public void setUp() throws Exception {
102         MockitoAnnotations.initMocks(this);
103
104         rootShard = InMemoryDOMDataTreeShard.create(ROOT_ID, executor, 1);
105         rootShard.onGlobalContextUpdated(schemaContext);
106
107         final ShardedDOMDataTree dataTree = new ShardedDOMDataTree();
108         final DOMDataTreeProducer shardRegProducer = dataTree.createProducer(Collections.singletonList(ROOT_ID));
109         rootShardReg = dataTree.registerDataTreeShard(ROOT_ID, rootShard, shardRegProducer);
110         shardRegProducer.close();
111
112         dataTreeService = dataTree;
113     }
114
115     @Test(expected = IllegalArgumentException.class)
116     public void testProducerPathContention() throws Exception {
117         dataTreeService.createProducer(Collections.singletonList(ROOT_ID));
118         dataTreeService.createProducer(Collections.singletonList(TEST_ID));
119     }
120
121     @Test
122     public void testShardRegistrationClose() throws Exception {
123         rootShardReg.close();
124
125         final InMemoryDOMDataTreeShard newRootShard = InMemoryDOMDataTreeShard.create(ROOT_ID, executor, 1);
126         newRootShard.onGlobalContextUpdated(schemaContext);
127         final DOMDataTreeProducer shardRegProducer = dataTreeService.createProducer(Collections.singletonList(ROOT_ID));
128
129         final ListenerRegistration<InMemoryDOMDataTreeShard> newRootShardReg =
130                 dataTreeService.registerDataTreeShard(ROOT_ID, rootShard, shardRegProducer);
131         shardRegProducer.close();
132
133         final InMemoryDOMDataTreeShard innerShard = InMemoryDOMDataTreeShard.create(INNER_CONTAINER_ID, executor, 1);
134         innerShard.onGlobalContextUpdated(schemaContext);
135         final DOMDataTreeProducer shardRegProducer2 =
136                 dataTreeService.createProducer(Collections.singletonList(INNER_CONTAINER_ID));
137         ListenerRegistration<InMemoryDOMDataTreeShard> innerShardReg =
138                 dataTreeService.registerDataTreeShard(INNER_CONTAINER_ID, innerShard, shardRegProducer2);
139
140         innerShardReg.close();
141         // try to register the shard again
142         innerShardReg = dataTreeService.registerDataTreeShard(INNER_CONTAINER_ID, innerShard, shardRegProducer2);
143         final DOMDataTreeCursorAwareTransaction tx = shardRegProducer2.createTransaction(false);
144         final DOMDataTreeWriteCursor cursor = tx.createCursor(INNER_CONTAINER_ID);
145         assertNotNull(cursor);
146
147         cursor.close();
148         tx.cancel();
149         shardRegProducer2.close();
150
151         innerShardReg.close();
152         newRootShardReg.close();
153     }
154
155     @Test
156     public void testSingleShardWrite() throws Exception {
157         final DOMDataTreeListener mockedDataTreeListener = Mockito.mock(DOMDataTreeListener.class);
158         doNothing().when(mockedDataTreeListener).onDataTreeChanged(anyCollection(), anyMap());
159
160         dataTreeService.registerListener(mockedDataTreeListener, Collections.singletonList(INNER_CONTAINER_ID),
161                 true, Collections.emptyList());
162
163         final DOMDataTreeProducer producer = dataTreeService.createProducer(Collections.singletonList(ROOT_ID));
164         DOMDataTreeCursorAwareTransaction tx = producer.createTransaction(false);
165         DOMDataTreeWriteCursor cursor = tx.createCursor(ROOT_ID);
166         assertNotNull(cursor);
167
168         cursor.write(TEST_ID.getRootIdentifier().getLastPathArgument(), crossShardContainer);
169
170         try {
171             tx.submit().checkedGet();
172             fail("There's still an open cursor");
173         } catch (final IllegalStateException e) {
174             assertTrue(e.getMessage().contains("cursor open"));
175         }
176
177         cursor.close();
178         tx.submit().checkedGet();
179
180         tx = producer.createTransaction(false);
181         cursor = tx.createCursor(TEST_ID);
182         assertNotNull(cursor);
183
184         cursor.delete(TestModel.INNER_CONTAINER_PATH.getLastPathArgument());
185         cursor.close();
186         tx.submit().checkedGet();
187
188         verify(mockedDataTreeListener, timeout(1000).times(3)).onDataTreeChanged(captorForChanges.capture(),
189                 captorForSubtrees.capture());
190         final List<Collection<DataTreeCandidate>> capturedValue = captorForChanges.getAllValues();
191         assertTrue(capturedValue.size() == 3);
192
193         final ContainerNode capturedChange =
194                 (ContainerNode) capturedValue.get(1).iterator().next().getRootNode().getDataAfter().get();
195         final ContainerNode innerContainerVerify = (ContainerNode) crossShardContainer.getChild(
196                 TestModel.INNER_CONTAINER_PATH.getLastPathArgument()).get();
197         assertEquals(innerContainerVerify, capturedChange);
198
199         verifyNoMoreInteractions(mockedDataTreeListener);
200     }
201
202     @Test
203     public void testMultipleWritesIntoSingleMapEntry() throws Exception {
204
205         final YangInstanceIdentifier oid1 = TestModel.OUTER_LIST_PATH.node(new NodeIdentifierWithPredicates(
206                 TestModel.OUTER_LIST_QNAME, QName.create(TestModel.OUTER_LIST_QNAME, "id"), 0));
207         final DOMDataTreeIdentifier outerListPath = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, oid1);
208
209         final DOMDataTreeProducer shardProducer = dataTreeService.createProducer(
210                 Collections.singletonList(outerListPath));
211         final InMemoryDOMDataTreeShard outerListShard = InMemoryDOMDataTreeShard.create(outerListPath, executor, 1000);
212         outerListShard.onGlobalContextUpdated(schemaContext);
213
214         final ListenerRegistration<InMemoryDOMDataTreeShard> oid1ShardRegistration =
215                 dataTreeService.registerDataTreeShard(outerListPath, outerListShard, shardProducer);
216
217         final DOMDataTreeCursorAwareTransaction tx = shardProducer.createTransaction(false);
218         final DOMDataTreeWriteCursor cursor =
219                 tx.createCursor(new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, oid1));
220         assertNotNull(cursor);
221
222         MapNode innerList = ImmutableMapNodeBuilder
223                 .create()
224                 .withNodeIdentifier(new NodeIdentifier(TestModel.INNER_LIST_QNAME))
225                 .build();
226
227         cursor.write(new NodeIdentifier(TestModel.INNER_LIST_QNAME), innerList);
228         cursor.close();
229         tx.submit().checkedGet();
230
231         final ArrayList<CheckedFuture<Void, TransactionCommitFailedException>> futures = new ArrayList<>();
232         final Collection<MapEntryNode> innerListMapEntries = createInnerListMapEntries(1000, "run-1");
233         for (final MapEntryNode innerListMapEntry : innerListMapEntries) {
234             final DOMDataTreeCursorAwareTransaction tx1 = shardProducer.createTransaction(false);
235             final DOMDataTreeWriteCursor cursor1 = tx1.createCursor(
236                     new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION,
237                             oid1.node(new NodeIdentifier(TestModel.INNER_LIST_QNAME))));
238             cursor1.write(innerListMapEntry.getIdentifier(), innerListMapEntry);
239             cursor1.close();
240             futures.add(tx1.submit());
241         }
242
243         futures.get(futures.size() - 1).checkedGet();
244
245     }
246
247     private Collection<MapEntryNode> createInnerListMapEntries(int amount, String valuePrefix) {
248         final Collection<MapEntryNode> ret = new ArrayList<>();
249         for (int i = 0; i < amount; i++) {
250             ret.add(ImmutableNodes.mapEntryBuilder()
251                     .withNodeIdentifier(new NodeIdentifierWithPredicates(TestModel.INNER_LIST_QNAME,
252                             QName.create(TestModel.OUTER_LIST_QNAME, "name"), Integer.toString(i)))
253                     .withChild(ImmutableNodes
254                             .leafNode(QName.create(TestModel.INNER_LIST_QNAME, "name"), Integer.toString(i)))
255                     .withChild(ImmutableNodes
256                             .leafNode(QName.create(TestModel.INNER_LIST_QNAME, "value"), valuePrefix + "-" + i))
257                     .build());
258         }
259
260         return ret;
261     }
262
263     @Test
264     public void testMultipleProducerCursorCreation() throws Exception {
265
266         final DOMDataTreeProducer rootProducer = dataTreeService.createProducer(Collections.singletonList(ROOT_ID));
267         DOMDataTreeCursorAwareTransaction rootTx = rootProducer.createTransaction(false);
268         //check if we can create cursor where the new producer will be
269         DOMDataTreeWriteCursor rootTxCursor = rootTx.createCursor(INNER_CONTAINER_ID);
270         assertNotNull(rootTxCursor);
271         rootTxCursor.close();
272
273         try {
274             rootProducer.createProducer(Collections.singletonList(INNER_CONTAINER_ID));
275             fail("Should've failed there is still a tx open");
276         } catch (final IllegalStateException e) {
277             assertTrue(e.getMessage().contains("open"));
278         }
279
280         assertTrue(rootTx.cancel());
281
282         final DOMDataTreeProducer innerContainerProducer = rootProducer.createProducer(
283                 Collections.singletonList(INNER_CONTAINER_ID));
284
285         rootTx = rootProducer.createTransaction(false);
286         try {
287             rootTx.createCursor(INNER_CONTAINER_ID);
288             fail("Subtree should not be available to this producer");
289         } catch (final IllegalArgumentException e) {
290             assertTrue(e.getMessage().contains("delegated to child producer"));
291         }
292
293         rootTxCursor = rootTx.createCursor(TEST_ID);
294         assertNotNull(rootTxCursor);
295         try {
296             rootTxCursor.enter(INNER_CONTAINER_ID.getRootIdentifier().getLastPathArgument());
297             fail("Cursor should not have this subtree available");
298         } catch (final IllegalArgumentException e) {
299             assertTrue(e.getMessage().contains("not available to this cursor"));
300         }
301
302         try {
303             rootTxCursor.write(TestModel.INNER_CONTAINER_PATH.getLastPathArgument(),
304                     ImmutableContainerNodeBuilder.create()
305                             .withNodeIdentifier(new NodeIdentifier(TestModel.INNER_CONTAINER))
306                             .build());
307             fail("Cursor should not have this subtree available");
308         } catch (final IllegalArgumentException e) {
309             assertTrue(e.getMessage().contains("not available to this cursor"));
310         }
311
312         final DOMDataTreeCursorAwareTransaction innerShardTx = innerContainerProducer.createTransaction(false);
313         final DOMDataTreeWriteCursor innerShardCursor = innerShardTx.createCursor(INNER_CONTAINER_ID);
314         assertNotNull(innerShardCursor);
315     }
316
317     private ContainerNode createCrossShardContainer() {
318         final LeafNode<String> shardedValue1 =
319                 ImmutableLeafNodeBuilder.<String>create().withNodeIdentifier(new NodeIdentifier(
320                         TestModel.SHARDED_VALUE_1)).withValue("sharded value 1").build();
321         final LeafNode<String> shardedValue2 =
322                 ImmutableLeafNodeBuilder.<String>create().withNodeIdentifier(new NodeIdentifier(
323                         TestModel.SHARDED_VALUE_2)).withValue("sharded value 2").build();
324
325
326         final ContainerNode lowerShardContainer = ImmutableContainerNodeBuilder.create()
327                 .withNodeIdentifier(new NodeIdentifier(TestModel.ANOTHER_SHARD_CONTAINER))
328                 .withChild(ImmutableLeafNodeBuilder.create()
329                         .withNodeIdentifier(new NodeIdentifier(TestModel.ANOTHER_SHARD_VALUE))
330                         .withValue("testing-value")
331                         .build())
332                 .build();
333
334         final ContainerNode containerNode =
335                 ImmutableContainerNodeBuilder.create()
336                         .withNodeIdentifier(new NodeIdentifier(TestModel.INNER_CONTAINER))
337                         .withChild(shardedValue1)
338                         .withChild(shardedValue2)
339                         .withChild(lowerShardContainer)
340                         .build();
341
342         final ContainerNode testContainer = ImmutableContainerNodeBuilder.create()
343                 .withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME))
344                 .withChild(containerNode)
345                 .build();
346
347         return testContainer;
348     }
349 }