2 * Copyright (c) 2013 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.netconf.confignetconfconnector;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Lists;
14 import com.google.common.collect.Maps;
15 import org.junit.Before;
16 import org.junit.Ignore;
17 import org.junit.Test;
18 import org.junit.matchers.JUnitMatchers;
19 import org.mockito.Mock;
20 import org.mockito.MockitoAnnotations;
21 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
22 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
23 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
24 import org.opendaylight.controller.config.yang.store.api.YangStoreSnapshot;
25 import org.opendaylight.controller.config.yang.store.impl.MbeParser;
26 import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
27 import org.opendaylight.controller.config.yang.test.impl.ComplexList;
28 import org.opendaylight.controller.config.yang.test.impl.Deep;
29 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
30 import org.opendaylight.controller.config.yang.test.impl.DtoAInner;
31 import org.opendaylight.controller.config.yang.test.impl.DtoAInnerInner;
32 import org.opendaylight.controller.config.yang.test.impl.DtoC;
33 import org.opendaylight.controller.config.yang.test.impl.DtoD;
34 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
35 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
36 import org.opendaylight.controller.config.yang.test.impl.Peers;
37 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
38 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
39 import org.opendaylight.controller.netconf.api.NetconfOperationRouter;
40 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
41 import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
42 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
43 import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
44 import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
45 import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
46 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
47 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
48 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
49 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
50 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
51 import org.opendaylight.controller.netconf.util.xml.XmlElement;
52 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
53 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.w3c.dom.NodeList;
59 import org.xml.sax.SAXException;
61 import javax.management.InstanceAlreadyExistsException;
62 import javax.management.ObjectName;
63 import javax.xml.parsers.ParserConfigurationException;
64 import java.io.FileNotFoundException;
65 import java.io.IOException;
66 import java.io.InputStream;
67 import java.math.BigInteger;
68 import java.util.ArrayList;
69 import java.util.Arrays;
70 import java.util.Collection;
71 import java.util.List;
74 import static org.junit.Assert.assertEquals;
75 import static org.junit.Assert.assertThat;
76 import static org.junit.Assert.fail;
77 import static org.mockito.Mockito.doNothing;
78 import static org.mockito.Mockito.doReturn;
79 import static org.mockito.Mockito.verify;
80 import static org.mockito.Mockito.verifyNoMoreInteractions;
83 public class NetconfMappingTest extends AbstractConfigTest {
84 private static final Logger logger = LoggerFactory.getLogger(NetconfMappingTest.class);
86 private static final String INSTANCE_NAME = "test1";
87 private static final String NETCONF_SESSION_ID = "foo";
88 private NetconfTestImplModuleFactory factory;
89 private DepTestImplModuleFactory factory2;
92 YangStoreSnapshot yangStoreSnapshot;
94 NetconfOperationRouter netconfOperationRouter;
96 private TransactionProvider transactionProvider;
99 public void setUp() throws Exception {
100 MockitoAnnotations.initMocks(this);
101 doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
102 this.factory = new NetconfTestImplModuleFactory();
103 this.factory2 = new DepTestImplModuleFactory();
104 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(this.factory, this.factory2));
106 transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
109 private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException {
110 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
112 final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
113 final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
114 setModule(mxBean, transaction);
116 transaction.commit();
121 public void testConfigNetconf() throws Exception {
123 createModule(INSTANCE_NAME);
125 edit("netconfMessages/editConfig.xml");
126 checkBinaryLeafEdited(getConfigCandidate());
128 // default-operation:none, should not affect binary leaf
129 edit("netconfMessages/editConfig_none.xml");
130 checkBinaryLeafEdited(getConfigCandidate());
134 Element response = getConfigRunning();
135 System.err.println(XmlUtil.toString(response));
136 checkBinaryLeafEdited(response);
137 checkTypeConfigAttribute(response);
138 checkTypedefs(response);
140 edit("netconfMessages/editConfig_remove.xml");
143 response = getConfigCandidate();
144 final String responseFromCandidate = XmlUtil.toString(response).replaceAll("\\s+", "");
145 // System.out.println(responseFromCandidate);
146 response = getConfigRunning();
147 final String responseFromRunning = XmlUtil.toString(response).replaceAll("\\s+", "");
148 // System.out.println(responseFromRunning);
149 assertEquals(responseFromCandidate, responseFromRunning);
151 final String expectedResult = XmlFileLoader.fileToString("netconfMessages/editConfig_expectedResult.xml")
152 .replaceAll("\\s+", "");
154 assertEquals(expectedResult, responseFromRunning);
155 assertEquals(expectedResult, responseFromCandidate);
157 edit("netconfMessages/editConfig_none.xml");
158 doNothing().when(netconfOperationRouter).close();
160 verify(netconfOperationRouter).close();
161 verifyNoMoreInteractions(netconfOperationRouter);
164 private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
166 DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID);
167 executeOp(closeOp, "netconfMessages/closeSession.xml");
170 private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
171 NetconfDocumentedException {
172 EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
174 executeOp(editOp, resource);
177 private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
178 Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
179 executeOp(commitOp, "netconfMessages/commit.xml");
182 private Element getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
183 NetconfDocumentedException {
184 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
185 configRegistryClient, NETCONF_SESSION_ID);
186 return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
189 private Element getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
190 NetconfDocumentedException {
191 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
192 configRegistryClient, NETCONF_SESSION_ID);
193 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
196 @Test(expected = NetconfDocumentedException.class)
197 public void testConfigNetconfReplaceDefaultEx() throws Exception {
199 createModule(INSTANCE_NAME);
201 edit("netconfMessages/editConfig.xml");
202 edit("netconfMessages/editConfig_replace_default_ex.xml");
206 public void testConfigNetconfReplaceDefault() throws Exception {
208 createModule(INSTANCE_NAME);
210 edit("netconfMessages/editConfig.xml");
212 Element response = getConfigRunning();
213 final int allInstances = response.getElementsByTagName("module").getLength();
215 edit("netconfMessages/editConfig_replace_default.xml");
218 response = getConfigRunning();
220 final int afterReplace = response.getElementsByTagName("module").getLength();
221 assertEquals(4, allInstances);
222 assertEquals(2, afterReplace);
225 @Test(expected = NetconfDocumentedException.class)
226 public void testSameAttrDifferentNamespaces() throws Exception {
228 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
229 } catch (NetconfDocumentedException e) {
230 String message = e.getMessage();
233 .containsString("Element simple-long-2 present multiple times with different namespaces"));
235 JUnitMatchers.containsString("urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
238 .containsString(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
243 @Test(expected = NetconfDocumentedException.class)
244 public void testDifferentNamespaceInTO() throws Exception {
246 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
247 } catch (NetconfDocumentedException e) {
248 String message = e.getMessage();
249 assertThat(message, JUnitMatchers.containsString("Unrecognised elements"));
250 assertThat(message, JUnitMatchers.containsString("simple-int2"));
251 assertThat(message, JUnitMatchers.containsString("dto_d"));
256 @Test(expected = NetconfDocumentedException.class)
257 public void testSameAttrDifferentNamespacesList() throws Exception {
259 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
260 } catch (NetconfDocumentedException e) {
261 String message = e.getMessage();
263 JUnitMatchers.containsString("Element binaryLeaf present multiple times with different namespaces"));
265 JUnitMatchers.containsString("urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
268 .containsString(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
274 public void testTypeNameConfigAttributeMatching() throws Exception {
275 edit("netconfMessages/editConfig.xml");
277 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
280 Element response = getConfigRunning();
281 checkTypeConfigAttribute(response);
284 // TODO add <modules operation="replace"> functionality
285 @Test(expected = NetconfDocumentedException.class)
286 public void testConfigNetconfReplaceModuleEx() throws Exception {
288 createModule(INSTANCE_NAME);
290 edit("netconfMessages/editConfig.xml");
291 edit("netconfMessages/editConfig_replace_module_ex.xml");
295 public void testUnrecognisedConfigElements() throws Exception {
297 String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
298 final int TESTS_COUNT = 8;
300 for (int i = 0; i < TESTS_COUNT; i++) {
301 String file = String.format(format, i + 1);
304 } catch (NetconfDocumentedException e) {
305 assertThat(e.getMessage(), JUnitMatchers.containsString("Unrecognised elements"));
306 assertThat(e.getMessage(), JUnitMatchers.containsString("unknownAttribute"));
309 fail("Unrecognised test should throw exception " + file);
316 public void testConfigNetconfReplaceModule() throws Exception {
318 createModule(INSTANCE_NAME);
320 edit("netconfMessages/editConfig.xml");
322 Element response = getConfigRunning();
323 final int allInstances = response.getElementsByTagName("instance").getLength();
325 edit("netconfMessages/editConfig_replace_module.xml");
328 response = getConfigRunning();
329 final int afterReplace = response.getElementsByTagName("instance").getLength();
331 assertEquals(4 + 4 /* Instances from services */, allInstances);
332 assertEquals(3 + 3, afterReplace);
335 @Test(expected = NetconfDocumentedException.class)
336 public void testEx() throws Exception {
341 @Test(expected = NetconfDocumentedException.class)
342 public void testEx2() throws Exception {
346 private void discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
347 DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
348 executeOp(discardOp, "netconfMessages/discardChanges.xml");
351 private void checkBinaryLeafEdited(final Element response) {
352 final NodeList children = response.getElementsByTagName("binaryLeaf");
353 assertEquals(3, children.getLength());
354 final StringBuffer buf = new StringBuffer();
355 for (int i = 0; i < 3; i++) {
356 final Element e = (Element) children.item(i);
357 buf.append(XmlElement.fromDomElement(e).getTextContent());
359 assertEquals("810", buf.toString());
362 private void checkTypedefs(final Element response) {
363 NodeList children = response.getElementsByTagName("extended");
364 assertEquals(1, children.getLength());
366 children = response.getElementsByTagName("extended-twice");
367 assertEquals(1, children.getLength());
370 private void checkTypeConfigAttribute(Element response) {
372 XmlElement modulesElement = XmlElement.fromDomElement(response).getOnlyChildElement("data")
373 .getOnlyChildElement("modules");
375 XmlElement configAttributeType = null;
376 for (XmlElement moduleElement : modulesElement.getChildElements("module")) {
377 for (XmlElement type : moduleElement.getChildElements("type")) {
378 if (type.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY).equals("") == false) {
379 configAttributeType = type;
384 assertEquals("configAttributeType", configAttributeType.getTextContent());
387 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
388 final List<InputStream> yangDependencies = getYangs();
390 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
391 mBeanEntries.putAll(new MbeParser().parseYangFiles(yangDependencies).getModuleMXBeanEntryMap());
397 public void testConfigNetconfRuntime() throws Exception {
399 createModule(INSTANCE_NAME);
401 edit("netconfMessages/editConfig.xml");
402 checkBinaryLeafEdited(getConfigCandidate());
406 Element response = get();
408 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
410 assertEquals(2, getElementsSize(response, "asdf"));
411 // data from running config
412 assertEquals(2, getElementsSize(response, "simple-short"));
414 assertEquals(8, getElementsSize(response, "inner-running-data"));
415 assertEquals(8, getElementsSize(response, "deep2"));
416 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
417 assertEquals(8 * 4, getElementsSize(response, "deep3"));
418 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
419 assertEquals(8, getElementsSize(response, "inner-running-data-additional"));
420 assertEquals(8, getElementsSize(response, "deep4"));
423 RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
425 response = executeOp(netconf, "netconfMessages/rpc.xml");
426 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("testarg1".toUpperCase()));
428 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
429 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("ok"));
431 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
432 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("true"));
434 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
435 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("1"));
436 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("2"));
439 private Element get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
440 Get getOp = new Get(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
441 return executeOp(getOp, "netconfMessages/get.xml");
444 private int getElementsSize(Element response, String elementName) {
445 return response.getElementsByTagName(elementName).getLength();
448 private Element executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
449 SAXException, IOException, NetconfDocumentedException {
451 final Document request = XmlFileLoader.xmlFileToDocument(filename);
453 logger.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
454 HandlingPriority priority = op.canHandle(request);
456 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
458 final Document response = op.handle(request, netconfOperationRouter);
459 logger.debug("Got response\n{}", XmlUtil.toString(response));
460 return response.getDocumentElement();
463 private List<InputStream> getYangs() throws FileNotFoundException {
464 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
465 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
466 "/META-INF/yang/ietf-inet-types.yang");
467 final Collection<InputStream> yangDependencies = new ArrayList<>();
468 for (String path : paths) {
469 final InputStream is = Preconditions
470 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
471 yangDependencies.add(is);
473 return Lists.newArrayList(yangDependencies);
476 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction)
477 throws InstanceAlreadyExistsException {
478 mxBean.setSimpleInt((long) 44);
479 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
480 final DtoD dtob = getDtoD();
481 mxBean.setDtoD(dtob);
483 final DtoC dtoa = getDtoC();
484 mxBean.setDtoC(dtoa);
485 mxBean.setSimpleBoolean(false);
487 final Peers p1 = new Peers();
490 p1.setSimpleInt3(456);
491 final Peers p2 = new Peers();
493 p2.setPort("port23");
494 p2.setSimpleInt3(456);
495 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
497 mxBean.setSimpleLong(454545L);
498 mxBean.setSimpleLong2(44L);
499 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
500 mxBean.setSimpleByte(new Byte((byte) 4));
501 mxBean.setSimpleShort(new Short((short) 4));
502 mxBean.setSimpleTest(545);
504 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
505 mxBean.setSimpleList(Lists.<Integer> newArrayList());
507 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), "dep");
508 mxBean.setTestingDep(testingDepOn);
511 private static DtoD getDtoD() {
512 final DtoD dtob = new DtoD();
513 dtob.setSimpleInt1((long) 444);
514 dtob.setSimpleInt2((long) 4444);
515 dtob.setSimpleInt3(454);
516 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
517 final Deep deep = new Deep();
518 deep.setSimpleInt3(4);
519 dtobInner.setDeep(deep);
520 dtobInner.setSimpleInt3(44);
521 dtobInner.setSimpleList(Lists.newArrayList(4));
522 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
523 dtob.setSimpleList(Lists.newArrayList(4));
527 private static DtoC getDtoC() {
528 final DtoC dtoa = new DtoC();
529 // dtoa.setSimpleArg((long) 55);
530 final DtoAInner dtoAInner = new DtoAInner();
531 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
532 dtoAInnerInner.setSimpleArg(456L);
533 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
534 dtoAInner.setSimpleArg(44L);
535 dtoa.setDtoAInner(dtoAInner);