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.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;
87 public class NetconfITTest extends AbstractConfigTest {
89 private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
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";
97 private NetconfMessage getConfig, getConfigCandidate, editConfig,
98 closeSession, startExi, stopExi;
99 private DefaultCommitNotificationProducer commitNot;
100 private NetconfServerDispatcher dispatch;
101 private EventLoopGroup nettyThreadgroup;
103 private NetconfClientDispatcher clientDispatcher;
107 public void setUp() throws Exception {
108 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
109 new ModuleFactory[0])));
113 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
114 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
116 nettyThreadgroup = new NioEventLoopGroup();
118 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
120 dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
121 ChannelFuture s = dispatch.createServer(tcpAddress);
124 clientDispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
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);
133 NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
134 factoriesListener, commitNot, idProvider);
136 NetconfServerDispatcher.ServerSslChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerSslChannelInitializer(
137 sslC, serverNegotiatorFactory, listenerFactory);
138 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
142 public void tearDown() throws Exception {
144 nettyThreadgroup.shutdownGracefully();
145 clientDispatcher.close();
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");
159 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
160 final Collection<InputStream> yangDependencies = getBasicYangs();
161 return new HardcodedYangStoreService(yangDependencies);
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);
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 registerRuntimeBean();
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);
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() {
307 public Asdf getAsdf() {
312 public Long getCreatedSessions() {
317 public String noArg(String arg1) {
318 return "from no arg";
325 public void testStartExi() throws Exception {
326 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
329 Document rpcReply = netconfClient.sendMessage(this.startExi)
331 assertIsOK(rpcReply);
333 ExiParameters exiParams = new ExiParameters();
334 exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
336 netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
337 netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
339 rpcReply = netconfClient.sendMessage(this.editConfig)
341 assertIsOK(rpcReply);
343 rpcReply = netconfClient.sendMessage(this.stopExi)
345 assertIsOK(rpcReply);
351 public void testCloseSession() throws Exception {
352 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
355 Document rpcReply = netconfClient.sendMessage(this.editConfig)
357 assertIsOK(rpcReply);
359 rpcReply = netconfClient.sendMessage(this.closeSession)
362 assertIsOK(rpcReply);
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);
376 public void testValidate() throws Exception {
377 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
379 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
380 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
383 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
385 assertIsOK(rpcReply);
389 private void assertIsOK(final Document rpcReply) {
390 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
391 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
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);
411 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
412 return assertGetConfigWorks(netconfClient, this.getConfig);
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();
424 public void testGetConfig() throws Exception {
425 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
426 assertGetConfigWorks(netconfClient);
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"))
436 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
437 assertIsOK(rpcReply);
438 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
439 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
441 assertIsOK(rpcReply);
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));
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;
456 private class TestSSHServer implements Runnable {
459 NetconfSSHServer.start();
460 } catch (Exception e) {
461 logger.info(e.getMessage());
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");
474 public void sshTest() throws Exception {
476 Connection conn = new Connection(sshAddress.getHostName(),sshAddress.getPort());
477 Assert.assertNotNull(conn);
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) {