6b942515315ef54a9a62a74253008fd9f6d9f8cd
[controller.git] / opendaylight / netconf / mdsal-netconf-connector / src / test / java / org / opendaylight / controller / netconf / mdsal / connector / ops / NetconfMDSalMappingTest.java
1 /*
2  * Copyright (c) 2015 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
9 package org.opendaylight.controller.netconf.mdsal.connector.ops;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15
16 import com.google.common.base.Preconditions;
17 import com.google.common.io.ByteSource;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Collection;
23 import java.util.EnumMap;
24 import java.util.List;
25 import java.util.concurrent.ExecutorService;
26 import javax.xml.parsers.ParserConfigurationException;
27 import org.custommonkey.xmlunit.DetailedDiff;
28 import org.custommonkey.xmlunit.Diff;
29 import org.custommonkey.xmlunit.XMLUnit;
30 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.opendaylight.controller.cluster.datastore.ConcurrentDOMDataBroker;
34 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
35 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
36 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
37 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
38 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
39 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
40 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
41 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
42 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
43 import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
44 import org.opendaylight.controller.netconf.mdsal.connector.TransactionProvider;
45 import org.opendaylight.controller.netconf.mdsal.connector.ops.get.Get;
46 import org.opendaylight.controller.netconf.mdsal.connector.ops.get.GetConfig;
47 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
48 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
49 import org.opendaylight.controller.sal.core.api.model.SchemaService;
50 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
51 import org.opendaylight.yangtools.concepts.ListenerRegistration;
52 import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
53 import org.opendaylight.yangtools.yang.model.api.Module;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
56 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
57 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
58 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.w3c.dom.Document;
62 import org.w3c.dom.Node;
63 import org.w3c.dom.NodeList;
64 import org.xml.sax.SAXException;
65
66 public class NetconfMDSalMappingTest {
67
68     private static final Logger LOG = LoggerFactory.getLogger(NetconfMDSalMappingTest.class);
69
70     private static final String RPC_REPLY_ELEMENT = "rpc-reply";
71     private static final String DATA_ELEMENT = "data";
72
73     private static Document RPC_REPLY_OK = null;
74
75     static {
76         try {
77             RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpc-reply_ok.xml");
78         } catch (Exception e) {
79             LOG.debug("unable to load rpc reply ok.", e);
80             RPC_REPLY_OK = XmlUtil.newDocument();
81         }
82     }
83
84     private CurrentSchemaContext currentSchemaContext = null;
85     private SchemaContext schemaContext = null;
86     private String sessionIdForReporting = "netconf-test-session1";
87
88     private TransactionProvider transactionProvider = null;
89
90
91     @Before
92     public void setUp() throws Exception {
93
94         XMLUnit.setIgnoreWhitespace(true);
95         XMLUnit.setIgnoreAttributeOrder(true);
96
97         this.schemaContext = parseSchemas(getYangSchemas());
98         schemaContext.getModules();
99         SchemaService schemaService = createSchemaService();
100
101         final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
102         final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
103
104         final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
105         datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
106         datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
107
108         ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
109                 16, 16, "CommitFutures");
110
111         ConcurrentDOMDataBroker cdb = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
112         this.transactionProvider = new TransactionProvider(cdb, sessionIdForReporting);
113         this.currentSchemaContext = new CurrentSchemaContext(schemaService);
114
115     }
116
117     @Test
118     public void testEmptyDatastore() throws Exception {
119
120         Document response = getConfigRunning();
121         assertEmptyDatastore(response);
122
123         response = getConfigCandidate();
124         assertEmptyDatastore(response);
125
126         response = get();
127         assertEmptyDatastore(response);
128
129     }
130
131     @Test
132     public void testEditRunning() throws Exception {
133
134         try {
135             edit("messages/mapping/editConfig_running.xml");
136             fail("Should have failed - edit config on running datastore is not supported");
137         } catch (NetconfDocumentedException e) {
138             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
139             assertTrue(e.getErrorTag() == ErrorTag.operation_not_supported);
140             assertTrue(e.getErrorType() == ErrorType.protocol);
141         }
142
143     }
144
145     @Test
146     public void testCandidateTransaction() throws Exception {
147
148         verifyResponse(edit("messages/mapping/editConfig_merge_n1.xml"), RPC_REPLY_OK);
149         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_n1_control.xml"));
150         assertEmptyDatastore(getConfigRunning());
151
152         verifyResponse(discardChanges(), RPC_REPLY_OK);
153         assertEmptyDatastore(getConfigCandidate());
154
155     }
156
157     @Test
158     public void testEditWithCommit() throws Exception {
159
160         verifyResponse(edit("messages/mapping/editConfig_merge_n1.xml"), RPC_REPLY_OK);
161         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_n1_control.xml"));
162
163         verifyResponse(commit(), RPC_REPLY_OK);
164         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_n1_control.xml"));
165
166         deleteDatastore();
167
168     }
169
170     @Test
171     public void testMultipleEditsWithMerge() throws Exception {
172
173         verifyResponse(edit("messages/mapping/editConfig_merge_multiple_1.xml"), RPC_REPLY_OK);
174         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_control_1.xml"));
175         verifyResponse(edit("messages/mapping/editConfig_merge_single_1.xml"), RPC_REPLY_OK);
176         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_control_2.xml"));
177         assertEmptyDatastore(getConfigRunning());
178
179         verifyResponse(commit(), RPC_REPLY_OK);
180         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_control_2.xml"));
181
182         deleteDatastore();
183
184     }
185
186     @Test
187     public void testMoreComplexEditConfigs() throws Exception {
188
189         verifyResponse(edit("messages/mapping/editConfig_merge_multiple_1.xml"), RPC_REPLY_OK);
190         verifyResponse(edit("messages/mapping/editConfig_merge_single_1.xml"), RPC_REPLY_OK);
191
192         verifyResponse(edit("messages/mapping/editConfig_merge_multiple_2.xml"), RPC_REPLY_OK);
193         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_after_more_complex_merge.xml"));
194
195         verifyResponse(edit("messages/mapping/editConfig_merge_multiple_3.xml"), RPC_REPLY_OK);
196         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_after_more_complex_merge_2.xml"));
197
198         verifyResponse(edit("messages/mapping/editConfig_merge_multiple_4_replace.xml"), RPC_REPLY_OK);
199         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_after_replace.xml"));
200         verifyResponse(commit(), RPC_REPLY_OK);
201
202         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_multiple_after_replace.xml"));
203
204         verifyResponse(edit("messages/mapping/editConfig_replace_default.xml"), RPC_REPLY_OK);
205         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_replace_default_control.xml"));
206         verifyResponse(commit(), RPC_REPLY_OK);
207
208         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_replace_default_control.xml"));
209
210         deleteDatastore();
211
212     }
213
214     @Test
215     public void testLock() throws Exception {
216
217         verifyResponse(lockCandidate(), RPC_REPLY_OK);
218
219         try {
220             lock();
221             fail("Should have failed - locking of running datastore is not supported");
222         } catch (NetconfDocumentedException e) {
223             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
224             assertTrue(e.getErrorTag() == ErrorTag.operation_not_supported);
225             assertTrue(e.getErrorType() == ErrorType.application);
226         }
227     }
228
229     @Test
230     public void testUnlock() throws Exception {
231
232         verifyResponse(unlockCandidate(), RPC_REPLY_OK);
233
234         try {
235             unlock();
236             fail("Should have failed - unlocking of running datastore is not supported");
237         } catch (NetconfDocumentedException e) {
238             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
239             assertTrue(e.getErrorTag() == ErrorTag.operation_not_supported);
240             assertTrue(e.getErrorType() == ErrorType.application);
241         }
242     }
243
244     @Test
245     public void testEditWithCreate() throws Exception {
246
247         verifyResponse(edit("messages/mapping/editConfig_create.xml"), RPC_REPLY_OK);
248         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_create_n1_control.xml"));
249
250
251         try {
252             edit("messages/mapping/editConfig_create.xml");
253             fail("Create should have failed - data already exists");
254         } catch (NetconfDocumentedException e) {
255             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
256             assertTrue(e.getErrorTag() == ErrorTag.data_exists);
257             assertTrue(e.getErrorType() == ErrorType.protocol);
258         }
259
260         verifyResponse(discardChanges(), RPC_REPLY_OK);
261
262     }
263
264     @Test
265     public void testDeleteNonExisting() throws Exception {
266
267         assertEmptyDatastore(getConfigCandidate());
268         assertEmptyDatastore(getConfigRunning());
269
270         try {
271             edit("messages/mapping/editConfig_delete-root.xml");
272             fail("Delete should have failed - data is missing");
273         } catch (NetconfDocumentedException e) {
274             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
275             assertTrue(e.getErrorTag() == ErrorTag.data_missing);
276             assertTrue(e.getErrorType() == ErrorType.protocol);
277         }
278
279     }
280
281     @Test
282     public void testEditMissingDefaultOperation() throws Exception {
283
284         verifyResponse(edit("messages/mapping/editConfig_merge_missing_default-operation_1.xml"), RPC_REPLY_OK);
285         verifyResponse(edit("messages/mapping/editConfig_merge_missing_default-operation_2.xml"), RPC_REPLY_OK);
286         verifyResponse(getConfigCandidate(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_missing_default-operation_control.xml"));
287
288         verifyResponse(commit(), RPC_REPLY_OK);
289         verifyResponse(getConfigRunning(), XmlFileLoader.xmlFileToDocument("messages/mapping/editConfig_merge_missing_default-operation_control.xml"));
290
291         deleteDatastore();
292     }
293
294     private void deleteDatastore() throws Exception{
295         verifyResponse(edit("messages/mapping/editConfig_delete-root.xml"), RPC_REPLY_OK);
296         assertEmptyDatastore(getConfigCandidate());
297
298         verifyResponse(commit(), RPC_REPLY_OK);
299         assertEmptyDatastore(getConfigRunning());
300     }
301
302     private void verifyResponse(Document response, Document template){
303         DetailedDiff dd = new DetailedDiff(new Diff(response, template));
304         dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
305         assertTrue(dd.similar());
306     }
307
308     private void assertEmptyDatastore(Document response) {
309
310         NodeList nodes = response.getChildNodes();
311         assertTrue(nodes.getLength() == 1);
312
313         assertEquals(nodes.item(0).getLocalName(),RPC_REPLY_ELEMENT);
314
315         NodeList replyNodes = nodes.item(0).getChildNodes();
316         assertTrue(replyNodes.getLength() == 1);
317
318         Node dataNode = replyNodes.item(0);
319         assertEquals(dataNode.getLocalName(), DATA_ELEMENT);
320         assertFalse(dataNode.hasChildNodes());
321
322     }
323
324     private Document commit() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
325         Commit commit = new Commit(sessionIdForReporting, transactionProvider);
326         return executeOperation(commit, "messages/mapping/commit.xml");
327     }
328
329     private Document discardChanges() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
330         DiscardChanges discardOp = new DiscardChanges(sessionIdForReporting, transactionProvider);
331         return executeOperation(discardOp, "messages/mapping/discardChanges.xml");
332     }
333
334     private Document edit(String resource) throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
335         EditConfig editConfig = new EditConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
336         return executeOperation(editConfig, resource);
337     }
338
339     private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
340         Get get = new Get(sessionIdForReporting, currentSchemaContext, transactionProvider);
341         return executeOperation(get, "messages/mapping/get.xml");
342     }
343
344     private Document getConfigRunning() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
345         GetConfig getConfig = new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
346         return executeOperation(getConfig, "messages/mapping/getConfig.xml");
347     }
348
349     private Document getConfigCandidate() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
350         GetConfig getConfig = new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
351         return executeOperation(getConfig, "messages/mapping/getConfig_candidate.xml");
352     }
353
354     private Document lock() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
355         Lock lock = new Lock(sessionIdForReporting);
356         return executeOperation(lock, "messages/mapping/lock.xml");
357     }
358
359     private Document unlock() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
360         Unlock unlock = new Unlock(sessionIdForReporting);
361         return executeOperation(unlock, "messages/mapping/unlock.xml");
362     }
363
364     private Document lockCandidate() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
365         Lock lock = new Lock(sessionIdForReporting);
366         return executeOperation(lock, "messages/mapping/lock_candidate.xml");
367     }
368
369     private Document unlockCandidate() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
370         Unlock unlock = new Unlock(sessionIdForReporting);
371         return executeOperation(unlock, "messages/mapping/unlock_candidate.xml");
372     }
373
374     private Document executeOperation(NetconfOperation op, String filename) throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
375         final Document request = XmlFileLoader.xmlFileToDocument(filename);
376
377         HandlingPriority priority = op.canHandle(request);
378         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
379
380         final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
381
382         LOG.debug("Got response {}" , response);
383
384         return response;
385     }
386
387     private Collection<InputStream> getYangSchemas() {
388         final List<String> schemaPaths = Arrays.asList("/META-INF/yang/config.yang", "/yang/mdsal-netconf-mapping-test.yang");
389         final List<InputStream> schemas = new ArrayList<>();
390
391         for (String schemaPath : schemaPaths) {
392             InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
393             schemas.add(resourceAsStream);
394         }
395
396         return schemas;
397     }
398
399     private SchemaContext parseSchemas(Collection<InputStream> schemas) throws IOException, YangSyntaxErrorException {
400         final YangParserImpl parser = new YangParserImpl();
401         Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(schemas);
402         return parser.parseSources(sources);
403     }
404
405     private SchemaService createSchemaService() {
406         return new SchemaService() {
407
408             @Override
409             public void addModule(Module module) {
410             }
411
412             @Override
413             public void removeModule(Module module) {
414
415             }
416
417             @Override
418             public SchemaContext getSessionContext() {
419                 return schemaContext;
420             }
421
422             @Override
423             public SchemaContext getGlobalContext() {
424                 return schemaContext;
425             }
426
427             @Override
428             public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
429                 listener.onGlobalContextUpdated(getGlobalContext());
430                 return new ListenerRegistration<SchemaContextListener>() {
431                     @Override
432                     public void close() {
433
434                     }
435
436                     @Override
437                     public SchemaContextListener getInstance() {
438                         return listener;
439                     }
440                 };
441             }
442         };
443     }
444 }