- introduced netconf ssh wrapper bundle
[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.base.Optional;
14 import com.google.common.collect.Lists;
15 import com.google.common.collect.Sets;
16 import io.netty.channel.ChannelFuture;
17 import io.netty.channel.EventLoopGroup;
18 import io.netty.channel.nio.NioEventLoopGroup;
19 import io.netty.util.HashedWheelTimer;
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.List;
28 import java.util.Set;
29 import java.util.concurrent.TimeUnit;
30 import javax.management.ObjectName;
31 import javax.net.ssl.SSLContext;
32 import javax.xml.parsers.ParserConfigurationException;
33 import junit.framework.Assert;
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Ignore;
37 import org.junit.Test;
38 import org.opendaylight.controller.config.api.ModuleIdentifier;
39 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
40 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
41 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
42 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
43 import org.opendaylight.controller.config.persist.api.Persister;
44 import org.opendaylight.controller.config.spi.ModuleFactory;
45 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
46 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
47 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
48 import org.opendaylight.controller.config.yang.test.impl.Asdf;
49 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
50 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
51 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
52 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeMXBean;
53 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeRegistrator;
54 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
55 import org.opendaylight.controller.netconf.api.NetconfMessage;
56 import org.opendaylight.controller.netconf.client.NetconfClient;
57 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
58 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
59 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
60 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
61 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
62 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
63 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
64 import org.opendaylight.controller.netconf.impl.mapping.ExiDecoderHandler;
65 import org.opendaylight.controller.netconf.impl.mapping.ExiEncoderHandler;
66 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
67 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
68 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
69 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
70 import org.opendaylight.controller.netconf.util.xml.ExiParameters;
71 import org.opendaylight.controller.netconf.util.xml.XmlElement;
72 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75 import org.w3c.dom.Document;
76 import org.w3c.dom.Element;
77 import org.w3c.dom.NamedNodeMap;
78 import org.w3c.dom.Node;
79 import org.xml.sax.SAXException;
80 import static junit.framework.Assert.assertEquals;
81 import static junit.framework.Assert.assertNotNull;
82 import static junit.framework.Assert.assertTrue;
83 import static org.mockito.Mockito.doReturn;
84 import static org.mockito.Mockito.mock;
85 import static org.mockito.internal.util.Checks.checkNotNull;
86
87 public class NetconfITTest extends AbstractConfigTest {
88
89      private static final Logger logger =  LoggerFactory.getLogger(NetconfITTest.class);
90     //
91
92     private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
93     private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 830);
94     private static final String USERNAME = "netconf";
95     private static final String PASSWORD = "netconf";
96
97     private NetconfMessage getConfig, getConfigCandidate, editConfig,
98             closeSession, startExi, stopExi;
99     private DefaultCommitNotificationProducer commitNot;
100     private NetconfServerDispatcher dispatch;
101     private EventLoopGroup nettyThreadgroup;
102
103     private NetconfClientDispatcher clientDispatcher;
104
105
106     @Before
107     public void setUp() throws Exception {
108         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
109                 new ModuleFactory[0])));
110
111         loadMessages();
112
113         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
114         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
115
116         nettyThreadgroup = new NioEventLoopGroup();
117
118         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
119
120         dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
121         ChannelFuture s = dispatch.createServer(tcpAddress);
122         s.await();
123
124         clientDispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
125     }
126
127     private NetconfServerDispatcher createDispatcher(Optional<SSLContext> sslC,
128             NetconfOperationServiceFactoryListenerImpl factoriesListener) {
129         SessionIdProvider idProvider = new SessionIdProvider();
130         NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
131                 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
132
133         NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
134                 factoriesListener, commitNot, idProvider);
135
136         NetconfServerDispatcher.ServerSslChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerSslChannelInitializer(
137                 sslC, serverNegotiatorFactory, listenerFactory);
138         return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
139     }
140
141     @After
142     public void tearDown() throws Exception {
143         commitNot.close();
144         nettyThreadgroup.shutdownGracefully();
145         clientDispatcher.close();
146     }
147
148     private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
149         this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
150         this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
151         this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
152         this.startExi = XmlFileLoader
153                 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
154         this.stopExi = XmlFileLoader
155                 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
156         this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
157     }
158
159     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
160         final Collection<InputStream> yangDependencies = getBasicYangs();
161         return new HardcodedYangStoreService(yangDependencies);
162     }
163
164     static Collection<InputStream> getBasicYangs() throws IOException {
165         List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
166                 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang",
167                 "/META-INF/yang/ietf-inet-types.yang");
168         final Collection<InputStream> yangDependencies = new ArrayList<>();
169         for (String path : paths) {
170             final InputStream is = checkNotNull(NetconfITTest.class.getResourceAsStream(path), path + " not found");
171             yangDependencies.add(is);
172         }
173         return yangDependencies;
174     }
175
176     protected List<ModuleFactory> getModuleFactories() {
177         return getModuleFactoriesS();
178     }
179     static List<ModuleFactory> getModuleFactoriesS() {
180         return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
181                 new NetconfTestImplModuleFactory());
182     }
183
184     @Test
185     public void testNetconfClientDemonstration() throws Exception {
186         try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
187
188             Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
189             long sessionId = netconfClient.getSessionId();
190
191             // NetconfMessage can be created :
192             // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
193
194             NetconfMessage response = netconfClient.sendMessage(getConfig);
195             response.getDocument();
196         }
197     }
198
199     @Test
200     public void testTwoSessions() throws Exception {
201         try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 4000, clientDispatcher))  {
202             try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 4000, clientDispatcher))  {
203             }
204         }
205     }
206
207     @Test(timeout = 10000)
208     public void testPersister() throws Exception {
209         Persister persister = mock(Persister.class);
210         doReturn("mockPersister").when(persister).toString();
211         doReturn(Optional.absent()).when(persister).loadLastConfig();
212         ConfigPersisterNotificationHandler h = new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer());
213         h.init();
214     }
215
216     @Ignore
217     @Test
218     public void waitingTest() throws Exception {
219         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
220         transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
221         transaction.commit();
222         Thread.currentThread().suspend();
223     }
224
225     @Test
226     public void rpcReplyContainsAllAttributesTest() throws Exception {
227         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
228             final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
229                     + "<get/>" + "</rpc>";
230             final Document doc = XmlUtil.readXmlToDocument(rpc);
231             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
232             assertNotNull(message);
233             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
234             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
235
236             assertSameAttributes(expectedAttributes, returnedAttributes);
237         }
238     }
239
240     private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
241         assertNotNull("Expecting 4 attributes", returnedAttributes);
242         assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
243
244         for (int i = 0; i < expectedAttributes.getLength(); i++) {
245             final Node expAttr = expectedAttributes.item(i);
246             final Node attr = returnedAttributes.item(i);
247             assertEquals(expAttr.getNodeName(), attr.getNodeName());
248             assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
249             assertEquals(expAttr.getTextContent(), attr.getTextContent());
250         }
251     }
252
253     @Test
254     public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
255         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
256             final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
257                     + "<commit/>" + "</rpc>";
258             final Document doc = XmlUtil.readXmlToDocument(rpc);
259             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
260             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
261             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
262
263             assertSameAttributes(expectedAttributes, returnedAttributes);
264         }
265     }
266
267     @Test
268     public void rpcOutputContainsCorrectNamespace() throws Exception {
269         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
270         ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
271         ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
272         NetconfTestImplModuleMXBean proxy = configRegistryClient
273                 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
274         proxy.setTestingDep(dep);
275         registerRuntimeBean();
276
277         transaction.commit();
278
279         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
280             final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
281
282             final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
283                     + "<no-arg xmlns=\""
284                     + expectedNamespace
285                     + "\">    "
286                     + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
287                     + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
288             final Document doc = XmlUtil.readXmlToDocument(rpc);
289             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
290
291             final Element rpcReply = message.getDocument().getDocumentElement();
292             final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
293             assertEquals("result", resultElement.getName());
294
295             final String namespace = resultElement.getNamespaceAttribute();
296             assertEquals(expectedNamespace, namespace);
297         }
298     }
299
300     private void registerRuntimeBean() {
301         BaseJMXRegistrator baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
302         RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
303                 .createRuntimeBeanRegistrator(new ModuleIdentifier(NetconfTestImplModuleFactory.NAME, "instance"));
304         NetconfTestImplRuntimeRegistrator reg = new NetconfTestImplRuntimeRegistrator(runtimeBeanRegistrator);
305         reg.register(new NetconfTestImplRuntimeMXBean() {
306             @Override
307             public Asdf getAsdf() {
308                 return null;
309             }
310
311             @Override
312             public Long getCreatedSessions() {
313                 return null;
314             }
315
316             @Override
317             public String noArg(String arg1) {
318                 return "from no arg";
319             }
320         });
321     }
322
323     @Test
324 //    @Ignore
325     public void testStartExi() throws Exception {
326         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
327
328
329             Document rpcReply = netconfClient.sendMessage(this.startExi)
330                     .getDocument();
331             assertIsOK(rpcReply);
332
333             ExiParameters exiParams = new ExiParameters();
334             exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
335
336             netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
337             netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
338
339             rpcReply = netconfClient.sendMessage(this.editConfig)
340                     .getDocument();
341             assertIsOK(rpcReply);
342
343             rpcReply = netconfClient.sendMessage(this.stopExi)
344                     .getDocument();
345             assertIsOK(rpcReply);
346
347         }
348     }
349
350     @Test
351     public void testCloseSession() throws Exception {
352         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
353
354             // edit config
355             Document rpcReply = netconfClient.sendMessage(this.editConfig)
356                     .getDocument();
357             assertIsOK(rpcReply);
358
359             rpcReply = netconfClient.sendMessage(this.closeSession)
360                     .getDocument();
361
362             assertIsOK(rpcReply);
363         }
364     }
365
366     @Test
367     public void testEditConfig() throws Exception {
368         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
369             // send edit_config.xml
370             final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
371             assertIsOK(rpcReply);
372         }
373     }
374
375     @Test
376     public void testValidate() throws Exception {
377         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
378             // begin transaction
379             Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
380             assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
381
382             // operations empty
383             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
384                     .getDocument();
385             assertIsOK(rpcReply);
386         }
387     }
388
389     private void assertIsOK(final Document rpcReply) {
390         assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
391         assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
392     }
393
394     @Ignore
395     @Test
396     // TODO can only send NetconfMessage - it must be valid xml
397     public void testClientHelloWithAuth() throws Exception {
398         final String fileName = "netconfMessages/client_hello_with_auth.xml";
399         // final InputStream resourceAsStream =
400         // AbstractListenerTest.class.getResourceAsStream(fileName);
401         // assertNotNull(resourceAsStream);
402         try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000, clientDispatcher)) {
403             // IOUtils.copy(resourceAsStream, netconfClient.getStream());
404             // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
405             // server should not write anything back
406             // assertEquals(null, netconfClient.readMessage());
407             assertGetConfigWorks(netconfClient);
408         }
409     }
410
411     private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
412         return assertGetConfigWorks(netconfClient, this.getConfig);
413     }
414
415     private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
416             throws InterruptedException {
417         final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
418         assertNotNull(rpcReply);
419         assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
420         return rpcReply.getDocument();
421     }
422
423     @Test
424     public void testGetConfig() throws Exception {
425         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
426             assertGetConfigWorks(netconfClient);
427         }
428     }
429
430     @Test
431     public void createYangTestBasedOnYuma() throws Exception {
432         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
433             Document rpcReply = netconfClient.sendMessage(
434                     XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
435                     .getDocument();
436             assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
437             assertIsOK(rpcReply);
438             assertGetConfigWorks(netconfClient, this.getConfigCandidate);
439             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
440                     .getDocument();
441             assertIsOK(rpcReply);
442
443             final ObjectName on = new ObjectName(
444                     "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
445             Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
446             assertEquals(cfgBeans, Sets.newHashSet(on));
447         }
448     }
449
450     private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
451         final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
452         assertEquals(expected, Long.toString(netconfClient.getSessionId()));
453         return netconfClient;
454     }
455
456     private class TestSSHServer implements Runnable {
457         public void run()  {
458             try {
459                 NetconfSSHServer.start();
460             } catch (Exception e) {
461                 logger.info(e.getMessage());
462             }
463         }
464     }
465     private void startSSHServer() throws Exception{
466         logger.info("Creating SSH server");
467         Thread sshServerThread = new Thread(new TestSSHServer());
468         sshServerThread.setDaemon(true);
469         sshServerThread.start();
470         logger.info("SSH server on");
471     }
472
473     @Test
474     public void sshTest() throws Exception {
475         startSSHServer();
476         Connection conn = new Connection(sshAddress.getHostName(),sshAddress.getPort());
477         Assert.assertNotNull(conn);
478         try {
479             conn.connect();
480             boolean isAuthenticated = conn.authenticateWithPassword(USERNAME,PASSWORD);
481             assertTrue(isAuthenticated);
482             Session sess = conn.openSession();
483             sess.startSubSystem("netconf");
484 //            sess.requestPTY("");
485         } catch (IOException e) {
486             e.printStackTrace();
487         }
488     }
489
490
491 }