Merge "BUG-704 Remove pax from netconf identity-ref test."
[controller.git] / opendaylight / netconf / netconf-it / src / test / java / org / opendaylight / controller / netconf / it / NetconfITTest.java
1 /*
2  * Copyright (c) 2013 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.it;
10
11 import static java.util.Collections.emptyList;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertThat;
15 import static org.junit.Assert.fail;
16 import static org.mockito.Matchers.anyString;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.lang.management.ManagementFactory;
23 import java.net.InetSocketAddress;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.List;
29 import java.util.Set;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.TimeoutException;
32
33 import javax.management.ObjectName;
34 import javax.xml.parsers.ParserConfigurationException;
35
36 import org.junit.After;
37 import org.junit.Before;
38 import org.junit.Ignore;
39 import org.junit.Test;
40 import org.junit.matchers.JUnitMatchers;
41 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
42 import org.opendaylight.controller.config.spi.ModuleFactory;
43 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
44 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
45 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
46 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
47 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
48 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
49 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
50 import org.opendaylight.controller.netconf.api.NetconfMessage;
51 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
52 import org.opendaylight.controller.netconf.client.test.TestingNetconfClient;
53 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
54 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
55 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
56 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
57 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
58 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
59 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
60 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
61 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
62 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
63 import org.opendaylight.controller.netconf.util.xml.XmlElement;
64 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
67 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
68 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import org.w3c.dom.Document;
72 import org.w3c.dom.Element;
73 import org.w3c.dom.NamedNodeMap;
74 import org.w3c.dom.Node;
75 import org.xml.sax.SAXException;
76
77 import com.google.common.base.Throwables;
78 import com.google.common.collect.Lists;
79 import com.google.common.collect.Sets;
80 import io.netty.channel.ChannelFuture;
81
82 public class NetconfITTest extends AbstractNetconfConfigTest {
83
84     // TODO refactor, pull common code up to AbstractNetconfITTest
85
86     private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
87
88     private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
89     private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
90     private static final String USERNAME = "netconf";
91     private static final String PASSWORD = "netconf";
92
93     private NetconfMessage getConfig, getConfigCandidate, editConfig,
94             closeSession, startExi, stopExi;
95     private DefaultCommitNotificationProducer commitNot;
96     private NetconfServerDispatcher dispatch;
97
98     private NetconfClientDispatcherImpl clientDispatcher;
99
100     @Before
101     public void setUp() throws Exception {
102         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,getModuleFactories().toArray(
103                 new ModuleFactory[0])));
104
105         loadMessages();
106
107         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
108         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
109
110
111         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
112
113         dispatch = createDispatcher(factoriesListener);
114         ChannelFuture s = dispatch.createServer(tcpAddress);
115         s.await();
116
117         clientDispatcher = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
118     }
119
120     private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
121         return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNot);
122     }
123
124     static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
125         NetconfOperationProvider netconfOperationProvider = mock(NetconfOperationProvider.class);
126         NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class);
127         doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
128         doReturn(snap).when(netconfOperationProvider).openSnapshot(anyString());
129         return new NetconfMonitoringServiceImpl(netconfOperationProvider);
130     }
131
132     @After
133     public void tearDown() throws Exception {
134         commitNot.close();
135         clientDispatcher.close();
136     }
137
138     private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
139         this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
140         this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
141         this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
142         this.startExi = XmlFileLoader
143                 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
144         this.stopExi = XmlFileLoader
145                 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
146         this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
147     }
148
149     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
150         final Collection<InputStream> yangDependencies = getBasicYangs();
151         return new HardcodedYangStoreService(yangDependencies);
152     }
153
154     static Collection<InputStream> getBasicYangs() throws IOException {
155
156         List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
157                 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
158                 "/META-INF/yang/ietf-inet-types.yang");
159         final Collection<InputStream> yangDependencies = new ArrayList<>();
160         List<String> failedToFind = new ArrayList<>();
161         for (String path : paths) {
162             InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
163             if (resourceAsStream == null) {
164                 failedToFind.add(path);
165             } else {
166                 yangDependencies.add(resourceAsStream);
167             }
168         }
169         assertEquals("Some yang files were not found", emptyList(), failedToFind);
170         return yangDependencies;
171     }
172
173     protected List<ModuleFactory> getModuleFactories() {
174         return getModuleFactoriesS();
175     }
176
177     static List<ModuleFactory> getModuleFactoriesS() {
178         return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
179                 new NetconfTestImplModuleFactory(), new IdentityTestModuleFactory());
180     }
181
182     @Test
183     public void testNetconfClientDemonstration() throws Exception {
184         try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", clientDispatcher, getClientConfiguration(tcpAddress, 4000))) {
185
186             Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
187             long sessionId = netconfClient.getSessionId();
188
189             // NetconfMessage can be created :
190             // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
191
192             NetconfMessage response = netconfClient.sendMessage(getConfig);
193             response.getDocument();
194         }
195     }
196
197     @Test
198     public void testTwoSessions() throws Exception {
199         try (TestingNetconfClient netconfClient = new TestingNetconfClient("1", clientDispatcher, getClientConfiguration(tcpAddress, 10000)))  {
200             try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("2", clientDispatcher, getClientConfiguration(tcpAddress, 10000))) {
201             }
202         }
203     }
204
205     @Ignore
206     @Test
207     public void waitingTest() throws Exception {
208         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
209         transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
210         transaction.commit();
211         Thread.currentThread().suspend();
212     }
213
214     @Test
215     public void rpcReplyContainsAllAttributesTest() throws Exception {
216         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
217             final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
218                     + "<get/>" + "</rpc>";
219             final Document doc = XmlUtil.readXmlToDocument(rpc);
220             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
221             assertNotNull(message);
222             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
223             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
224
225             assertSameAttributes(expectedAttributes, returnedAttributes);
226         }
227     }
228
229     private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
230         assertNotNull("Expecting 4 attributes", returnedAttributes);
231         assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
232
233         for (int i = 0; i < expectedAttributes.getLength(); i++) {
234             final Node expAttr = expectedAttributes.item(i);
235             final Node attr = returnedAttributes.item(i);
236             assertEquals(expAttr.getNodeName(), attr.getNodeName());
237             assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
238             assertEquals(expAttr.getTextContent(), attr.getTextContent());
239         }
240     }
241
242     @Test
243     public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
244         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
245             final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
246                     + "<commit/>" + "</rpc>";
247             final Document doc = XmlUtil.readXmlToDocument(rpc);
248             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
249             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
250             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
251
252             assertSameAttributes(expectedAttributes, returnedAttributes);
253         }
254     }
255
256     @Test
257     public void rpcOutputContainsCorrectNamespace() throws Exception {
258         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
259         ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
260         ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
261         NetconfTestImplModuleMXBean proxy = configRegistryClient
262                 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
263         proxy.setTestingDep(dep);
264         proxy.setSimpleShort((short) 0);
265
266         transaction.commit();
267
268         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
269             final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
270
271             final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
272                     + "<no-arg xmlns=\""
273                     + expectedNamespace
274                     + "\">    "
275                     + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
276                     + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
277             final Document doc = XmlUtil.readXmlToDocument(rpc);
278             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
279
280             final Element rpcReply = message.getDocument().getDocumentElement();
281             final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
282             assertEquals("result", resultElement.getName());
283
284             final String namespace = resultElement.getNamespaceAttribute();
285             assertEquals(expectedNamespace, namespace);
286         }
287     }
288
289     @Test
290     public void testCloseSession() throws Exception {
291         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
292
293             // edit config
294             Document rpcReply = netconfClient.sendMessage(this.editConfig)
295                     .getDocument();
296             assertIsOK(rpcReply);
297
298             rpcReply = netconfClient.sendMessage(this.closeSession)
299                     .getDocument();
300
301             assertIsOK(rpcReply);
302         }
303     }
304
305     @Test
306     public void testEditConfig() throws Exception {
307         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
308             // send edit_config.xml
309             final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
310             assertIsOK(rpcReply);
311         }
312     }
313
314     @Test
315     public void testValidate() throws Exception {
316         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
317             // begin transaction
318             Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
319             assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
320
321             // operations empty
322             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
323                     .getDocument();
324             assertIsOK(rpcReply);
325         }
326     }
327
328     private void assertIsOK(final Document rpcReply) throws NetconfDocumentedException {
329         assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
330         assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
331     }
332
333     private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
334         return assertGetConfigWorks(netconfClient, this.getConfig);
335     }
336
337     private Document assertGetConfigWorks(final TestingNetconfClient netconfClient, final NetconfMessage getConfigMessage)
338             throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
339         final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
340         assertNotNull(rpcReply);
341         assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
342         return rpcReply.getDocument();
343     }
344
345     @Test
346     public void testGetConfig() throws Exception {
347         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
348             assertGetConfigWorks(netconfClient);
349         }
350     }
351
352     @Test
353     public void createYangTestBasedOnYuma() throws Exception {
354         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
355             Document rpcReply = netconfClient.sendMessage(
356                     XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
357                     .getDocument();
358             assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
359             assertIsOK(rpcReply);
360             assertGetConfigWorks(netconfClient, this.getConfigCandidate);
361             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
362                     .getDocument();
363             assertIsOK(rpcReply);
364
365             final ObjectName on = new ObjectName(
366                     "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
367             Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
368             assertEquals(cfgBeans, Sets.newHashSet(on));
369         }
370     }
371
372     private TestingNetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
373         final TestingNetconfClient netconfClient = new TestingNetconfClient("test " + address.toString(), clientDispatcher, getClientConfiguration(address, 5000));
374         assertEquals(expected, Long.toString(netconfClient.getSessionId()));
375         return netconfClient;
376     }
377
378     @Test
379     public void testIdRef() throws Exception {
380         NetconfMessage editId = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_identities.xml");
381         NetconfMessage commit = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml");
382
383         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
384             assertIsOK(netconfClient.sendMessage(editId).getDocument());
385             assertIsOK(netconfClient.sendMessage(commit).getDocument());
386
387             NetconfMessage response = netconfClient.sendMessage(getConfig);
388
389             assertThat(XmlUtil.toString(response.getDocument()), JUnitMatchers.containsString("<prefix:afi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity1</prefix:afi>"));
390             assertThat(XmlUtil.toString(response.getDocument()), JUnitMatchers.containsString("<prefix:afi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity2</prefix:afi>"));
391             assertThat(XmlUtil.toString(response.getDocument()), JUnitMatchers.containsString("<prefix:safi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity2</prefix:safi>"));
392             assertThat(XmlUtil.toString(response.getDocument()), JUnitMatchers.containsString("<prefix:safi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity1</prefix:safi>"));
393
394         } catch (Exception e) {
395             fail(Throwables.getStackTraceAsString(e));
396         }
397     }
398
399     @Override
400     protected CodecRegistry getCodecRegistry() {
401         final IdentityCodec<?> codec = mock(IdentityCodec.class);
402         doReturn(TestIdentity1.class).when(codec).deserialize(TestIdentity1.QNAME);
403         doReturn(TestIdentity2.class).when(codec).deserialize(TestIdentity2.QNAME);
404
405         final CodecRegistry ret = super.getCodecRegistry();
406         doReturn(codec).when(ret).getIdentityCodec();
407         return ret;
408     }
409 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.