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 java.util.regex.Pattern;
31 import javax.management.ObjectName;
32 import javax.net.ssl.SSLContext;
33 import javax.xml.parsers.ParserConfigurationException;
34 import junit.framework.Assert;
35 import org.junit.After;
36 import org.junit.Before;
37 import org.junit.Ignore;
38 import org.junit.Test;
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.persist.api.Persister;
42 import org.opendaylight.controller.config.spi.ModuleFactory;
43 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
44 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
45 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
46 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
47 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
48 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
49 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
50 import org.opendaylight.controller.netconf.api.NetconfMessage;
51 import org.opendaylight.controller.netconf.client.NetconfClient;
52 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
53 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
54 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
55 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
56 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
57 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
58 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
59 import org.opendaylight.controller.netconf.impl.mapping.ExiDecoderHandler;
60 import org.opendaylight.controller.netconf.impl.mapping.ExiEncoderHandler;
61 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
62 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
63 import org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPersisterActivator;
64 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
65 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
66 import org.opendaylight.controller.netconf.util.xml.ExiParameters;
67 import org.opendaylight.controller.netconf.util.xml.XmlElement;
68 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import org.w3c.dom.Document;
72 import org.w3c.dom.Element;
73 import org.w3c.dom.NamedNodeMap;
74 import org.w3c.dom.Node;
75 import org.xml.sax.SAXException;
76 import static java.util.Collections.emptyList;
77 import static junit.framework.Assert.assertEquals;
78 import static junit.framework.Assert.assertNotNull;
79 import static junit.framework.Assert.assertTrue;
80 import static org.mockito.Mockito.doReturn;
81 import static org.mockito.Mockito.mock;
83 public class NetconfITTest extends AbstractConfigTest {
85 private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
88 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
89 private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
90 private static final String USERNAME = "netconf";
91 private static final String PASSWORD = "netconf";
93 private NetconfMessage getConfig, getConfigCandidate, editConfig,
94 closeSession, startExi, stopExi;
95 private DefaultCommitNotificationProducer commitNot;
96 private NetconfServerDispatcher dispatch;
97 private EventLoopGroup nettyThreadgroup;
99 private NetconfClientDispatcher clientDispatcher;
103 public void setUp() throws Exception {
104 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
105 new ModuleFactory[0])));
109 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
110 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
112 nettyThreadgroup = new NioEventLoopGroup();
114 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
116 dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
117 ChannelFuture s = dispatch.createServer(tcpAddress);
120 clientDispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
123 private NetconfServerDispatcher createDispatcher(Optional<SSLContext> sslC,
124 NetconfOperationServiceFactoryListenerImpl factoriesListener) {
125 SessionIdProvider idProvider = new SessionIdProvider();
126 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
127 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
129 NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
130 factoriesListener, commitNot, idProvider);
132 NetconfServerDispatcher.ServerSslChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerSslChannelInitializer(
133 sslC, serverNegotiatorFactory, listenerFactory);
134 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
138 public void tearDown() throws Exception {
140 nettyThreadgroup.shutdownGracefully();
141 clientDispatcher.close();
144 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
145 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
146 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
147 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
148 this.startExi = XmlFileLoader
149 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
150 this.stopExi = XmlFileLoader
151 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
152 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
155 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
156 final Collection<InputStream> yangDependencies = getBasicYangs();
157 return new HardcodedYangStoreService(yangDependencies);
160 static Collection<InputStream> getBasicYangs() throws IOException {
161 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
162 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
163 "/META-INF/yang/ietf-inet-types.yang");
164 final Collection<InputStream> yangDependencies = new ArrayList<>();
165 List<String> failedToFind = new ArrayList<>();
166 for (String path : paths) {
167 InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
168 if (resourceAsStream == null) {
169 failedToFind.add(path);
171 yangDependencies.add(resourceAsStream);
174 assertEquals("Some yang files were not found",emptyList(), failedToFind);
175 return yangDependencies;
178 protected List<ModuleFactory> getModuleFactories() {
179 return getModuleFactoriesS();
181 static List<ModuleFactory> getModuleFactoriesS() {
182 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
183 new NetconfTestImplModuleFactory());
187 public void testNetconfClientDemonstration() throws Exception {
188 try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
190 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
191 long sessionId = netconfClient.getSessionId();
193 // NetconfMessage can be created :
194 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
196 NetconfMessage response = netconfClient.sendMessage(getConfig);
197 response.getDocument();
202 public void testTwoSessions() throws Exception {
203 try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 10000, clientDispatcher)) {
204 try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 10000, clientDispatcher)) {
209 @Test(timeout = 10000)
210 public void testPersister() throws Exception {
211 Persister persister = mock(Persister.class);
212 doReturn("mockPersister").when(persister).toString();
213 doReturn(Optional.absent()).when(persister).loadLastConfig();
214 ConfigPersisterNotificationHandler h =
215 new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer(), Pattern.compile(ConfigPersisterActivator.DEFAULT_IGNORED_REGEX));
221 public void waitingTest() throws Exception {
222 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
223 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
224 transaction.commit();
225 Thread.currentThread().suspend();
229 public void rpcReplyContainsAllAttributesTest() throws Exception {
230 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
231 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
232 + "<get/>" + "</rpc>";
233 final Document doc = XmlUtil.readXmlToDocument(rpc);
234 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
235 assertNotNull(message);
236 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
237 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
239 assertSameAttributes(expectedAttributes, returnedAttributes);
243 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
244 assertNotNull("Expecting 4 attributes", returnedAttributes);
245 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
247 for (int i = 0; i < expectedAttributes.getLength(); i++) {
248 final Node expAttr = expectedAttributes.item(i);
249 final Node attr = returnedAttributes.item(i);
250 assertEquals(expAttr.getNodeName(), attr.getNodeName());
251 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
252 assertEquals(expAttr.getTextContent(), attr.getTextContent());
257 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
258 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
259 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
260 + "<commit/>" + "</rpc>";
261 final Document doc = XmlUtil.readXmlToDocument(rpc);
262 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
263 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
264 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
266 assertSameAttributes(expectedAttributes, returnedAttributes);
271 public void rpcOutputContainsCorrectNamespace() throws Exception {
272 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
273 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
274 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
275 NetconfTestImplModuleMXBean proxy = configRegistryClient
276 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
277 proxy.setTestingDep(dep);
278 proxy.setSimpleShort((short)0);
280 transaction.commit();
282 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
283 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
285 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
289 + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
290 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
291 final Document doc = XmlUtil.readXmlToDocument(rpc);
292 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
294 final Element rpcReply = message.getDocument().getDocumentElement();
295 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
296 assertEquals("result", resultElement.getName());
298 final String namespace = resultElement.getNamespaceAttribute();
299 assertEquals(expectedNamespace, namespace);
305 public void testStartExi() throws Exception {
306 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
309 Document rpcReply = netconfClient.sendMessage(this.startExi)
311 assertIsOK(rpcReply);
313 ExiParameters exiParams = new ExiParameters();
314 exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
316 netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
317 netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
319 rpcReply = netconfClient.sendMessage(this.editConfig)
321 assertIsOK(rpcReply);
323 rpcReply = netconfClient.sendMessage(this.stopExi)
325 assertIsOK(rpcReply);
331 public void testCloseSession() throws Exception {
332 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
335 Document rpcReply = netconfClient.sendMessage(this.editConfig)
337 assertIsOK(rpcReply);
339 rpcReply = netconfClient.sendMessage(this.closeSession)
342 assertIsOK(rpcReply);
347 public void testEditConfig() throws Exception {
348 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
349 // send edit_config.xml
350 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
351 assertIsOK(rpcReply);
356 public void testValidate() throws Exception {
357 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
359 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
360 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
363 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
365 assertIsOK(rpcReply);
369 private void assertIsOK(final Document rpcReply) {
370 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
371 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
376 // TODO can only send NetconfMessage - it must be valid xml
377 public void testClientHelloWithAuth() throws Exception {
378 final String fileName = "netconfMessages/client_hello_with_auth.xml";
379 // final InputStream resourceAsStream =
380 // AbstractListenerTest.class.getResourceAsStream(fileName);
381 // assertNotNull(resourceAsStream);
382 try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000, clientDispatcher)) {
383 // IOUtils.copy(resourceAsStream, netconfClient.getStream());
384 // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
385 // server should not write anything back
386 // assertEquals(null, netconfClient.readMessage());
387 assertGetConfigWorks(netconfClient);
391 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
392 return assertGetConfigWorks(netconfClient, this.getConfig);
395 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
396 throws InterruptedException {
397 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
398 assertNotNull(rpcReply);
399 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
400 return rpcReply.getDocument();
404 public void testGetConfig() throws Exception {
405 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
406 assertGetConfigWorks(netconfClient);
411 public void createYangTestBasedOnYuma() throws Exception {
412 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
413 Document rpcReply = netconfClient.sendMessage(
414 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
416 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
417 assertIsOK(rpcReply);
418 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
419 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
421 assertIsOK(rpcReply);
423 final ObjectName on = new ObjectName(
424 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
425 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
426 assertEquals(cfgBeans, Sets.newHashSet(on));
430 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
431 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
432 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
433 return netconfClient;
436 private void startSSHServer() throws Exception{
437 logger.info("Creating SSH server");
438 Thread sshServerThread = new Thread(NetconfSSHServer.start(10830,tcpAddress));
439 sshServerThread.setDaemon(true);
440 sshServerThread.start();
441 logger.info("SSH server on");
445 public void sshTest() throws Exception {
447 logger.info("creating connection");
448 Connection conn = new Connection(sshAddress.getHostName(),sshAddress.getPort());
449 Assert.assertNotNull(conn);
450 logger.info("connection created");
452 boolean isAuthenticated = conn.authenticateWithPassword(USERNAME,PASSWORD);
453 assertTrue(isAuthenticated);
454 logger.info("user authenticated");
455 final Session sess = conn.openSession();
456 sess.startSubSystem("netconf");
457 logger.info("user authenticated");
458 sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
463 byte[] bytes = new byte[1024];
466 c = sess.getStdout().read(bytes);
467 } catch (IOException e) {
468 e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
470 logger.info("got data:"+bytes);