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.it;
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;
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.manager.impl.AbstractConfigTest;
39 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
40 import org.opendaylight.controller.config.persist.api.Persister;
41 import org.opendaylight.controller.config.spi.ModuleFactory;
42 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
43 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
44 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
45 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
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.NetconfMessage;
50 import org.opendaylight.controller.netconf.client.NetconfClient;
51 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
52 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
53 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
54 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
55 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
56 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
57 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
58 import org.opendaylight.controller.netconf.impl.mapping.ExiDecoderHandler;
59 import org.opendaylight.controller.netconf.impl.mapping.ExiEncoderHandler;
60 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
61 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
62 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
63 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
64 import org.opendaylight.controller.netconf.util.xml.ExiParameters;
65 import org.opendaylight.controller.netconf.util.xml.XmlElement;
66 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import org.w3c.dom.Document;
70 import org.w3c.dom.Element;
71 import org.w3c.dom.NamedNodeMap;
72 import org.w3c.dom.Node;
73 import org.xml.sax.SAXException;
74 import static java.util.Collections.emptyList;
75 import static junit.framework.Assert.assertEquals;
76 import static junit.framework.Assert.assertNotNull;
77 import static junit.framework.Assert.assertTrue;
78 import static org.mockito.Mockito.doReturn;
79 import static org.mockito.Mockito.mock;
81 public class NetconfITTest extends AbstractConfigTest {
83 private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
86 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
87 private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
88 private static final String USERNAME = "netconf";
89 private static final String PASSWORD = "netconf";
91 private NetconfMessage getConfig, getConfigCandidate, editConfig,
92 closeSession, startExi, stopExi;
93 private DefaultCommitNotificationProducer commitNot;
94 private NetconfServerDispatcher dispatch;
95 private EventLoopGroup nettyThreadgroup;
97 private NetconfClientDispatcher clientDispatcher;
101 public void setUp() throws Exception {
102 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
103 new ModuleFactory[0])));
107 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
108 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
110 nettyThreadgroup = new NioEventLoopGroup();
112 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
114 dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
115 ChannelFuture s = dispatch.createServer(tcpAddress);
118 clientDispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
121 private NetconfServerDispatcher createDispatcher(Optional<SSLContext> sslC,
122 NetconfOperationServiceFactoryListenerImpl factoriesListener) {
123 SessionIdProvider idProvider = new SessionIdProvider();
124 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
125 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
127 NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
128 factoriesListener, commitNot, idProvider);
130 NetconfServerDispatcher.ServerSslChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerSslChannelInitializer(
131 sslC, serverNegotiatorFactory, listenerFactory);
132 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
136 public void tearDown() throws Exception {
138 nettyThreadgroup.shutdownGracefully();
139 clientDispatcher.close();
142 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
143 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
144 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
145 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
146 this.startExi = XmlFileLoader
147 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
148 this.stopExi = XmlFileLoader
149 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
150 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
153 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
154 final Collection<InputStream> yangDependencies = getBasicYangs();
155 return new HardcodedYangStoreService(yangDependencies);
158 static Collection<InputStream> getBasicYangs() throws IOException {
159 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
160 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
161 "/META-INF/yang/ietf-inet-types.yang");
162 final Collection<InputStream> yangDependencies = new ArrayList<>();
163 List<String> failedToFind = new ArrayList<>();
164 for (String path : paths) {
165 InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
166 if (resourceAsStream == null) {
167 failedToFind.add(path);
169 yangDependencies.add(resourceAsStream);
172 assertEquals("Some yang files were not found",emptyList(), failedToFind);
173 return yangDependencies;
176 protected List<ModuleFactory> getModuleFactories() {
177 return getModuleFactoriesS();
179 static List<ModuleFactory> getModuleFactoriesS() {
180 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
181 new NetconfTestImplModuleFactory());
185 public void testNetconfClientDemonstration() throws Exception {
186 try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
188 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
189 long sessionId = netconfClient.getSessionId();
191 // NetconfMessage can be created :
192 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
194 NetconfMessage response = netconfClient.sendMessage(getConfig);
195 response.getDocument();
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)) {
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());
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();
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();
236 assertSameAttributes(expectedAttributes, returnedAttributes);
240 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
241 assertNotNull("Expecting 4 attributes", returnedAttributes);
242 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
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());
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();
263 assertSameAttributes(expectedAttributes, returnedAttributes);
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 proxy.setSimpleShort((short)0);
277 transaction.commit();
279 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
280 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
282 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
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));
291 final Element rpcReply = message.getDocument().getDocumentElement();
292 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
293 assertEquals("result", resultElement.getName());
295 final String namespace = resultElement.getNamespaceAttribute();
296 assertEquals(expectedNamespace, namespace);
302 public void testStartExi() throws Exception {
303 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
306 Document rpcReply = netconfClient.sendMessage(this.startExi)
308 assertIsOK(rpcReply);
310 ExiParameters exiParams = new ExiParameters();
311 exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
313 netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
314 netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
316 rpcReply = netconfClient.sendMessage(this.editConfig)
318 assertIsOK(rpcReply);
320 rpcReply = netconfClient.sendMessage(this.stopExi)
322 assertIsOK(rpcReply);
328 public void testCloseSession() throws Exception {
329 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
332 Document rpcReply = netconfClient.sendMessage(this.editConfig)
334 assertIsOK(rpcReply);
336 rpcReply = netconfClient.sendMessage(this.closeSession)
339 assertIsOK(rpcReply);
344 public void testEditConfig() throws Exception {
345 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
346 // send edit_config.xml
347 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
348 assertIsOK(rpcReply);
353 public void testValidate() throws Exception {
354 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
356 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
357 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
360 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
362 assertIsOK(rpcReply);
366 private void assertIsOK(final Document rpcReply) {
367 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
368 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
373 // TODO can only send NetconfMessage - it must be valid xml
374 public void testClientHelloWithAuth() throws Exception {
375 final String fileName = "netconfMessages/client_hello_with_auth.xml";
376 // final InputStream resourceAsStream =
377 // AbstractListenerTest.class.getResourceAsStream(fileName);
378 // assertNotNull(resourceAsStream);
379 try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000, clientDispatcher)) {
380 // IOUtils.copy(resourceAsStream, netconfClient.getStream());
381 // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
382 // server should not write anything back
383 // assertEquals(null, netconfClient.readMessage());
384 assertGetConfigWorks(netconfClient);
388 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
389 return assertGetConfigWorks(netconfClient, this.getConfig);
392 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
393 throws InterruptedException {
394 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
395 assertNotNull(rpcReply);
396 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
397 return rpcReply.getDocument();
401 public void testGetConfig() throws Exception {
402 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
403 assertGetConfigWorks(netconfClient);
408 public void createYangTestBasedOnYuma() throws Exception {
409 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
410 Document rpcReply = netconfClient.sendMessage(
411 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
413 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
414 assertIsOK(rpcReply);
415 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
416 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
418 assertIsOK(rpcReply);
420 final ObjectName on = new ObjectName(
421 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
422 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
423 assertEquals(cfgBeans, Sets.newHashSet(on));
427 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
428 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
429 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
430 return netconfClient;
433 private void startSSHServer() throws Exception{
434 logger.info("Creating SSH server");
435 Thread sshServerThread = new Thread(NetconfSSHServer.start(10830,tcpAddress));
436 sshServerThread.setDaemon(true);
437 sshServerThread.start();
438 logger.info("SSH server on");
442 public void sshTest() throws Exception {
444 logger.info("creating connection");
445 Connection conn = new Connection(sshAddress.getHostName(),sshAddress.getPort());
446 Assert.assertNotNull(conn);
447 logger.info("connection created");
449 boolean isAuthenticated = conn.authenticateWithPassword(USERNAME,PASSWORD);
450 assertTrue(isAuthenticated);
451 logger.info("user authenticated");
452 final Session sess = conn.openSession();
453 sess.startSubSystem("netconf");
454 logger.info("user authenticated");
455 sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
460 byte[] bytes = new byte[1024];
463 c = sess.getStdout().read(bytes);
464 } catch (IOException e) {
465 e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
467 logger.info("got data:"+bytes);