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 java.util.Collections.emptyList;
81 import static junit.framework.Assert.assertEquals;
82 import static junit.framework.Assert.assertNotNull;
83 import static junit.framework.Assert.assertTrue;
84 import static org.mockito.Mockito.doReturn;
85 import static org.mockito.Mockito.mock;
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", 10830);
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 List<String> failedToFind = new ArrayList<>();
170 for (String path : paths) {
171 InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
172 if (resourceAsStream == null) {
173 failedToFind.add(path);
175 yangDependencies.add(resourceAsStream);
178 assertEquals("Some yang files were not found",emptyList(), failedToFind);
179 return yangDependencies;
182 protected List<ModuleFactory> getModuleFactories() {
183 return getModuleFactoriesS();
185 static List<ModuleFactory> getModuleFactoriesS() {
186 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
187 new NetconfTestImplModuleFactory());
191 public void testNetconfClientDemonstration() throws Exception {
192 try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
194 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
195 long sessionId = netconfClient.getSessionId();
197 // NetconfMessage can be created :
198 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
200 NetconfMessage response = netconfClient.sendMessage(getConfig);
201 response.getDocument();
206 public void testTwoSessions() throws Exception {
207 try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 10000, clientDispatcher)) {
208 try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 10000, clientDispatcher)) {
213 @Test(timeout = 10000)
214 public void testPersister() throws Exception {
215 Persister persister = mock(Persister.class);
216 doReturn("mockPersister").when(persister).toString();
217 doReturn(Optional.absent()).when(persister).loadLastConfig();
218 ConfigPersisterNotificationHandler h = new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer());
224 public void waitingTest() throws Exception {
225 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
226 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
227 transaction.commit();
228 Thread.currentThread().suspend();
232 public void rpcReplyContainsAllAttributesTest() throws Exception {
233 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
234 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
235 + "<get/>" + "</rpc>";
236 final Document doc = XmlUtil.readXmlToDocument(rpc);
237 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
238 assertNotNull(message);
239 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
240 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
242 assertSameAttributes(expectedAttributes, returnedAttributes);
246 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
247 assertNotNull("Expecting 4 attributes", returnedAttributes);
248 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
250 for (int i = 0; i < expectedAttributes.getLength(); i++) {
251 final Node expAttr = expectedAttributes.item(i);
252 final Node attr = returnedAttributes.item(i);
253 assertEquals(expAttr.getNodeName(), attr.getNodeName());
254 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
255 assertEquals(expAttr.getTextContent(), attr.getTextContent());
260 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
261 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
262 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
263 + "<commit/>" + "</rpc>";
264 final Document doc = XmlUtil.readXmlToDocument(rpc);
265 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
266 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
267 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
269 assertSameAttributes(expectedAttributes, returnedAttributes);
274 public void rpcOutputContainsCorrectNamespace() throws Exception {
275 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
276 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
277 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
278 NetconfTestImplModuleMXBean proxy = configRegistryClient
279 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
280 proxy.setTestingDep(dep);
281 registerRuntimeBean();
283 transaction.commit();
285 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
286 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
288 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
292 + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
293 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
294 final Document doc = XmlUtil.readXmlToDocument(rpc);
295 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
297 final Element rpcReply = message.getDocument().getDocumentElement();
298 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
299 assertEquals("result", resultElement.getName());
301 final String namespace = resultElement.getNamespaceAttribute();
302 assertEquals(expectedNamespace, namespace);
306 private void registerRuntimeBean() {
307 BaseJMXRegistrator baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
308 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
309 .createRuntimeBeanRegistrator(new ModuleIdentifier(NetconfTestImplModuleFactory.NAME, "instance"));
310 NetconfTestImplRuntimeRegistrator reg = new NetconfTestImplRuntimeRegistrator(runtimeBeanRegistrator);
311 reg.register(new NetconfTestImplRuntimeMXBean() {
313 public Asdf getAsdf() {
318 public Long getCreatedSessions() {
323 public String noArg(String arg1) {
324 return "from no arg";
331 public void testStartExi() throws Exception {
332 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
335 Document rpcReply = netconfClient.sendMessage(this.startExi)
337 assertIsOK(rpcReply);
339 ExiParameters exiParams = new ExiParameters();
340 exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
342 netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
343 netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
345 rpcReply = netconfClient.sendMessage(this.editConfig)
347 assertIsOK(rpcReply);
349 rpcReply = netconfClient.sendMessage(this.stopExi)
351 assertIsOK(rpcReply);
357 public void testCloseSession() throws Exception {
358 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
361 Document rpcReply = netconfClient.sendMessage(this.editConfig)
363 assertIsOK(rpcReply);
365 rpcReply = netconfClient.sendMessage(this.closeSession)
368 assertIsOK(rpcReply);
373 public void testEditConfig() throws Exception {
374 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
375 // send edit_config.xml
376 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
377 assertIsOK(rpcReply);
382 public void testValidate() throws Exception {
383 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
385 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
386 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
389 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
391 assertIsOK(rpcReply);
395 private void assertIsOK(final Document rpcReply) {
396 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
397 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
402 // TODO can only send NetconfMessage - it must be valid xml
403 public void testClientHelloWithAuth() throws Exception {
404 final String fileName = "netconfMessages/client_hello_with_auth.xml";
405 // final InputStream resourceAsStream =
406 // AbstractListenerTest.class.getResourceAsStream(fileName);
407 // assertNotNull(resourceAsStream);
408 try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000, clientDispatcher)) {
409 // IOUtils.copy(resourceAsStream, netconfClient.getStream());
410 // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
411 // server should not write anything back
412 // assertEquals(null, netconfClient.readMessage());
413 assertGetConfigWorks(netconfClient);
417 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
418 return assertGetConfigWorks(netconfClient, this.getConfig);
421 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
422 throws InterruptedException {
423 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
424 assertNotNull(rpcReply);
425 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
426 return rpcReply.getDocument();
430 public void testGetConfig() throws Exception {
431 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
432 assertGetConfigWorks(netconfClient);
437 public void createYangTestBasedOnYuma() throws Exception {
438 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
439 Document rpcReply = netconfClient.sendMessage(
440 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
442 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
443 assertIsOK(rpcReply);
444 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
445 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
447 assertIsOK(rpcReply);
449 final ObjectName on = new ObjectName(
450 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
451 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
452 assertEquals(cfgBeans, Sets.newHashSet(on));
456 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
457 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
458 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
459 return netconfClient;
462 private void startSSHServer() throws Exception{
463 logger.info("Creating SSH server");
464 Thread sshServerThread = new Thread(NetconfSSHServer.start(10830,tcpAddress));
465 sshServerThread.setDaemon(true);
466 sshServerThread.start();
467 logger.info("SSH server on");
471 public void sshTest() throws Exception {
473 logger.info("creating connection");
474 Connection conn = new Connection(sshAddress.getHostName(),sshAddress.getPort());
475 Assert.assertNotNull(conn);
476 logger.info("connection created");
478 boolean isAuthenticated = conn.authenticateWithPassword(USERNAME,PASSWORD);
479 assertTrue(isAuthenticated);
480 logger.info("user authenticated");
481 final Session sess = conn.openSession();
482 sess.startSubSystem("netconf");
483 logger.info("user authenticated");
484 sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
489 byte[] bytes = new byte[1024];
492 c = sess.getStdout().read(bytes);
493 } catch (IOException e) {
494 e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
496 logger.info("got data:"+bytes);