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.collect.Lists;
14 import com.google.common.collect.Sets;
15 import io.netty.channel.ChannelFuture;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.lang.management.ManagementFactory;
19 import java.net.InetSocketAddress;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.TimeoutException;
28 import javax.management.ObjectName;
29 import javax.xml.parsers.ParserConfigurationException;
30 import junit.framework.Assert;
31 import org.apache.commons.io.IOUtils;
32 import org.junit.After;
33 import org.junit.Before;
34 import org.junit.Ignore;
35 import org.junit.Test;
36 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
37 import org.opendaylight.controller.config.spi.ModuleFactory;
38 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
39 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
40 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
41 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
42 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
43 import org.opendaylight.controller.netconf.StubUserManager;
44 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
45 import org.opendaylight.controller.netconf.api.NetconfMessage;
46 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
47 import org.opendaylight.controller.netconf.client.test.TestingNetconfClient;
48 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
49 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
50 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
51 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
52 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
53 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
54 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
55 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
56 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
57 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
58 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
59 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
60 import org.opendaylight.controller.netconf.util.xml.XmlElement;
61 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64 import org.w3c.dom.Document;
65 import org.w3c.dom.Element;
66 import org.w3c.dom.NamedNodeMap;
67 import org.w3c.dom.Node;
68 import org.xml.sax.SAXException;
69 import static java.util.Collections.emptyList;
70 import static org.junit.Assert.assertEquals;
71 import static org.junit.Assert.assertNotNull;
72 import static org.junit.Assert.assertTrue;
73 import static org.mockito.Matchers.anyString;
74 import static org.mockito.Mockito.doReturn;
75 import static org.mockito.Mockito.mock;
77 public class NetconfITTest extends AbstractNetconfConfigTest {
79 // TODO refactor, pull common code up to AbstractNetconfITTest
81 private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
83 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
84 private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
85 private static final String USERNAME = "netconf";
86 private static final String PASSWORD = "netconf";
88 private NetconfMessage getConfig, getConfigCandidate, editConfig,
89 closeSession, startExi, stopExi;
90 private DefaultCommitNotificationProducer commitNot;
91 private NetconfServerDispatcher dispatch;
93 private NetconfClientDispatcher clientDispatcher;
96 public void setUp() throws Exception {
97 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,getModuleFactories().toArray(
98 new ModuleFactory[0])));
102 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
103 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
106 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
108 dispatch = createDispatcher(factoriesListener);
109 ChannelFuture s = dispatch.createServer(tcpAddress);
112 clientDispatcher = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup, 5000);
115 private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
116 return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNot);
119 static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
120 NetconfOperationProvider netconfOperationProvider = mock(NetconfOperationProvider.class);
121 NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class);
122 doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
123 doReturn(snap).when(netconfOperationProvider).openSnapshot(anyString());
124 return new NetconfMonitoringServiceImpl(netconfOperationProvider);
128 public void tearDown() throws Exception {
130 clientDispatcher.close();
133 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
134 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
135 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
136 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
137 this.startExi = XmlFileLoader
138 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
139 this.stopExi = XmlFileLoader
140 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
141 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
144 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
145 final Collection<InputStream> yangDependencies = getBasicYangs();
146 return new HardcodedYangStoreService(yangDependencies);
149 static Collection<InputStream> getBasicYangs() throws IOException {
151 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
152 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
153 "/META-INF/yang/ietf-inet-types.yang");
154 final Collection<InputStream> yangDependencies = new ArrayList<>();
155 List<String> failedToFind = new ArrayList<>();
156 for (String path : paths) {
157 InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
158 if (resourceAsStream == null) {
159 failedToFind.add(path);
161 yangDependencies.add(resourceAsStream);
164 assertEquals("Some yang files were not found", emptyList(), failedToFind);
165 return yangDependencies;
168 protected List<ModuleFactory> getModuleFactories() {
169 return getModuleFactoriesS();
172 static List<ModuleFactory> getModuleFactoriesS() {
173 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
174 new NetconfTestImplModuleFactory());
178 public void testNetconfClientDemonstration() throws Exception {
179 try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
181 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
182 long sessionId = netconfClient.getSessionId();
184 // NetconfMessage can be created :
185 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
187 NetconfMessage response = netconfClient.sendMessage(getConfig);
188 response.getDocument();
193 public void testTwoSessions() throws Exception {
194 try (TestingNetconfClient netconfClient = new TestingNetconfClient("1", tcpAddress, 10000, clientDispatcher)) {
195 try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("2", tcpAddress, 10000, clientDispatcher)) {
202 public void waitingTest() throws Exception {
203 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
204 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
205 transaction.commit();
206 Thread.currentThread().suspend();
210 public void rpcReplyContainsAllAttributesTest() throws Exception {
211 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
212 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
213 + "<get/>" + "</rpc>";
214 final Document doc = XmlUtil.readXmlToDocument(rpc);
215 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
216 assertNotNull(message);
217 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
218 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
220 assertSameAttributes(expectedAttributes, returnedAttributes);
224 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
225 assertNotNull("Expecting 4 attributes", returnedAttributes);
226 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
228 for (int i = 0; i < expectedAttributes.getLength(); i++) {
229 final Node expAttr = expectedAttributes.item(i);
230 final Node attr = returnedAttributes.item(i);
231 assertEquals(expAttr.getNodeName(), attr.getNodeName());
232 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
233 assertEquals(expAttr.getTextContent(), attr.getTextContent());
238 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
239 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
240 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
241 + "<commit/>" + "</rpc>";
242 final Document doc = XmlUtil.readXmlToDocument(rpc);
243 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
244 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
245 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
247 assertSameAttributes(expectedAttributes, returnedAttributes);
252 public void rpcOutputContainsCorrectNamespace() throws Exception {
253 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
254 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
255 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
256 NetconfTestImplModuleMXBean proxy = configRegistryClient
257 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
258 proxy.setTestingDep(dep);
259 proxy.setSimpleShort((short) 0);
261 transaction.commit();
263 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
264 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
266 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
270 + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
271 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
272 final Document doc = XmlUtil.readXmlToDocument(rpc);
273 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
275 final Element rpcReply = message.getDocument().getDocumentElement();
276 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
277 assertEquals("result", resultElement.getName());
279 final String namespace = resultElement.getNamespaceAttribute();
280 assertEquals(expectedNamespace, namespace);
285 public void testCloseSession() throws Exception {
286 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
289 Document rpcReply = netconfClient.sendMessage(this.editConfig)
291 assertIsOK(rpcReply);
293 rpcReply = netconfClient.sendMessage(this.closeSession)
296 assertIsOK(rpcReply);
301 public void testEditConfig() throws Exception {
302 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
303 // send edit_config.xml
304 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
305 assertIsOK(rpcReply);
310 public void testValidate() throws Exception {
311 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
313 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
314 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
317 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
319 assertIsOK(rpcReply);
323 private void assertIsOK(final Document rpcReply) throws NetconfDocumentedException {
324 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
325 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
328 private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
329 return assertGetConfigWorks(netconfClient, this.getConfig);
332 private Document assertGetConfigWorks(final TestingNetconfClient netconfClient, final NetconfMessage getConfigMessage)
333 throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
334 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
335 assertNotNull(rpcReply);
336 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
337 return rpcReply.getDocument();
341 public void testGetConfig() throws Exception {
342 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
343 assertGetConfigWorks(netconfClient);
348 public void createYangTestBasedOnYuma() throws Exception {
349 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
350 Document rpcReply = netconfClient.sendMessage(
351 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
353 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
354 assertIsOK(rpcReply);
355 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
356 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
358 assertIsOK(rpcReply);
360 final ObjectName on = new ObjectName(
361 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
362 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
363 assertEquals(cfgBeans, Sets.newHashSet(on));
367 private TestingNetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
368 final TestingNetconfClient netconfClient = new TestingNetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
369 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
370 return netconfClient;
373 private void startSSHServer() throws Exception {
374 logger.info("Creating SSH server");
375 StubUserManager um = new StubUserManager(USERNAME, PASSWORD);
377 try (InputStream is = getClass().getResourceAsStream("/RSA.pk")) {
378 pem = IOUtils.toString(is);
380 AuthProvider ap = new AuthProvider(um, pem);
381 Thread sshServerThread = new Thread(NetconfSSHServer.start(10830, tcpAddress, ap));
382 sshServerThread.setDaemon(true);
383 sshServerThread.start();
384 logger.info("SSH server on");
388 public void sshTest() throws Exception {
390 logger.info("creating connection");
391 Connection conn = new Connection(sshAddress.getHostName(), sshAddress.getPort());
392 Assert.assertNotNull(conn);
393 logger.info("connection created");
395 boolean isAuthenticated = conn.authenticateWithPassword(USERNAME, PASSWORD);
396 assertTrue(isAuthenticated);
397 logger.info("user authenticated");
398 final Session sess = conn.openSession();
399 sess.startSubSystem("netconf");
400 logger.info("user authenticated");
401 sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
407 byte[] bytes = new byte[1024];
410 c = sess.getStdout().read(bytes);
411 } catch (IOException e) {
412 throw new IllegalStateException("IO exception while reading data on ssh bridge.");
414 logger.info("got data:" + bytes);