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