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 junit.framework.Assert;
17 import org.apache.commons.io.IOUtils;
18 import org.junit.After;
19 import org.junit.Before;
20 import org.junit.Ignore;
21 import org.junit.Test;
22 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
23 import org.opendaylight.controller.config.spi.ModuleFactory;
24 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
25 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
26 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
27 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
28 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
29 import org.opendaylight.controller.netconf.StubUserManager;
30 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
31 import org.opendaylight.controller.netconf.api.NetconfMessage;
32 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
33 import org.opendaylight.controller.netconf.client.test.TestingNetconfClient;
34 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
35 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
36 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
37 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
38 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
39 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
40 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
41 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
42 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
43 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
44 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
45 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
46 import org.opendaylight.controller.netconf.util.xml.XmlElement;
47 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.w3c.dom.Document;
51 import org.w3c.dom.Element;
52 import org.w3c.dom.NamedNodeMap;
53 import org.w3c.dom.Node;
54 import org.xml.sax.SAXException;
56 import javax.management.ObjectName;
57 import javax.xml.parsers.ParserConfigurationException;
58 import java.io.IOException;
59 import java.io.InputStream;
60 import java.lang.management.ManagementFactory;
61 import java.net.InetSocketAddress;
62 import java.util.ArrayList;
63 import java.util.Arrays;
64 import java.util.Collection;
65 import java.util.Collections;
66 import java.util.List;
68 import java.util.concurrent.ExecutionException;
69 import java.util.concurrent.TimeoutException;
71 import static java.util.Collections.emptyList;
72 import static org.junit.Assert.assertEquals;
73 import static org.junit.Assert.assertNotNull;
74 import static org.junit.Assert.assertTrue;
75 import static org.mockito.Matchers.anyString;
76 import static org.mockito.Mockito.doReturn;
77 import static org.mockito.Mockito.mock;
79 public class NetconfITTest extends AbstractNetconfConfigTest {
81 // TODO refactor, pull common code up to AbstractNetconfITTest
83 private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
85 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
86 private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
87 private static final String USERNAME = "netconf";
88 private static final String PASSWORD = "netconf";
90 private NetconfMessage getConfig, getConfigCandidate, editConfig,
91 closeSession, startExi, stopExi;
92 private DefaultCommitNotificationProducer commitNot;
93 private NetconfServerDispatcher dispatch;
95 private NetconfClientDispatcher clientDispatcher;
98 public void setUp() throws Exception {
99 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,getModuleFactories().toArray(
100 new ModuleFactory[0])));
104 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
105 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
108 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
110 dispatch = createDispatcher(factoriesListener);
111 ChannelFuture s = dispatch.createServer(tcpAddress);
114 clientDispatcher = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup, 5000);
117 private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
118 return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNot);
121 static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
122 NetconfOperationProvider netconfOperationProvider = mock(NetconfOperationProvider.class);
123 NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class);
124 doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
125 doReturn(snap).when(netconfOperationProvider).openSnapshot(anyString());
126 return new NetconfMonitoringServiceImpl(netconfOperationProvider);
130 public void tearDown() throws Exception {
132 clientDispatcher.close();
135 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
136 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
137 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
138 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
139 this.startExi = XmlFileLoader
140 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
141 this.stopExi = XmlFileLoader
142 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
143 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
146 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
147 final Collection<InputStream> yangDependencies = getBasicYangs();
148 return new HardcodedYangStoreService(yangDependencies);
151 static Collection<InputStream> getBasicYangs() throws IOException {
153 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
154 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
155 "/META-INF/yang/ietf-inet-types.yang");
156 final Collection<InputStream> yangDependencies = new ArrayList<>();
157 List<String> failedToFind = new ArrayList<>();
158 for (String path : paths) {
159 InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
160 if (resourceAsStream == null) {
161 failedToFind.add(path);
163 yangDependencies.add(resourceAsStream);
166 assertEquals("Some yang files were not found", emptyList(), failedToFind);
167 return yangDependencies;
170 protected List<ModuleFactory> getModuleFactories() {
171 return getModuleFactoriesS();
174 static List<ModuleFactory> getModuleFactoriesS() {
175 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
176 new NetconfTestImplModuleFactory());
180 public void testNetconfClientDemonstration() throws Exception {
181 try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
183 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
184 long sessionId = netconfClient.getSessionId();
186 // NetconfMessage can be created :
187 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
189 NetconfMessage response = netconfClient.sendMessage(getConfig);
190 response.getDocument();
195 public void testTwoSessions() throws Exception {
196 try (TestingNetconfClient netconfClient = new TestingNetconfClient("1", tcpAddress, 10000, clientDispatcher)) {
197 try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("2", tcpAddress, 10000, clientDispatcher)) {
204 public void waitingTest() throws Exception {
205 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
206 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
207 transaction.commit();
208 Thread.currentThread().suspend();
212 public void rpcReplyContainsAllAttributesTest() throws Exception {
213 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
214 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
215 + "<get/>" + "</rpc>";
216 final Document doc = XmlUtil.readXmlToDocument(rpc);
217 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
218 assertNotNull(message);
219 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
220 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
222 assertSameAttributes(expectedAttributes, returnedAttributes);
226 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
227 assertNotNull("Expecting 4 attributes", returnedAttributes);
228 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
230 for (int i = 0; i < expectedAttributes.getLength(); i++) {
231 final Node expAttr = expectedAttributes.item(i);
232 final Node attr = returnedAttributes.item(i);
233 assertEquals(expAttr.getNodeName(), attr.getNodeName());
234 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
235 assertEquals(expAttr.getTextContent(), attr.getTextContent());
240 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
241 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
242 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
243 + "<commit/>" + "</rpc>";
244 final Document doc = XmlUtil.readXmlToDocument(rpc);
245 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
246 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
247 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
249 assertSameAttributes(expectedAttributes, returnedAttributes);
254 public void rpcOutputContainsCorrectNamespace() throws Exception {
255 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
256 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
257 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
258 NetconfTestImplModuleMXBean proxy = configRegistryClient
259 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
260 proxy.setTestingDep(dep);
261 proxy.setSimpleShort((short) 0);
263 transaction.commit();
265 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
266 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
268 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
272 + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
273 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
274 final Document doc = XmlUtil.readXmlToDocument(rpc);
275 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
277 final Element rpcReply = message.getDocument().getDocumentElement();
278 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
279 assertEquals("result", resultElement.getName());
281 final String namespace = resultElement.getNamespaceAttribute();
282 assertEquals(expectedNamespace, namespace);
287 public void testCloseSession() throws Exception {
288 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
291 Document rpcReply = netconfClient.sendMessage(this.editConfig)
293 assertIsOK(rpcReply);
295 rpcReply = netconfClient.sendMessage(this.closeSession)
298 assertIsOK(rpcReply);
303 public void testEditConfig() throws Exception {
304 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
305 // send edit_config.xml
306 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
307 assertIsOK(rpcReply);
312 public void testValidate() throws Exception {
313 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
315 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
316 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
319 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
321 assertIsOK(rpcReply);
325 private void assertIsOK(final Document rpcReply) throws NetconfDocumentedException {
326 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
327 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
330 private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
331 return assertGetConfigWorks(netconfClient, this.getConfig);
334 private Document assertGetConfigWorks(final TestingNetconfClient netconfClient, final NetconfMessage getConfigMessage)
335 throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
336 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
337 assertNotNull(rpcReply);
338 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
339 return rpcReply.getDocument();
343 public void testGetConfig() throws Exception {
344 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
345 assertGetConfigWorks(netconfClient);
350 public void createYangTestBasedOnYuma() throws Exception {
351 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
352 Document rpcReply = netconfClient.sendMessage(
353 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
355 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
356 assertIsOK(rpcReply);
357 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
358 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
360 assertIsOK(rpcReply);
362 final ObjectName on = new ObjectName(
363 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
364 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
365 assertEquals(cfgBeans, Sets.newHashSet(on));
369 private TestingNetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
370 final TestingNetconfClient netconfClient = new TestingNetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
371 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
372 return netconfClient;
375 private void startSSHServer() throws Exception {
376 logger.info("Creating SSH server");
377 StubUserManager um = new StubUserManager(USERNAME, PASSWORD);
379 try (InputStream is = getClass().getResourceAsStream("/RSA.pk")) {
380 pem = IOUtils.toString(is);
382 AuthProvider ap = new AuthProvider(um, pem);
383 Thread sshServerThread = new Thread(NetconfSSHServer.start(10830, tcpAddress, ap));
384 sshServerThread.setDaemon(true);
385 sshServerThread.start();
386 logger.info("SSH server on");
390 public void sshTest() throws Exception {
392 logger.info("creating connection");
393 Connection conn = new Connection(sshAddress.getHostName(), sshAddress.getPort());
394 Assert.assertNotNull(conn);
395 logger.info("connection created");
397 boolean isAuthenticated = conn.authenticateWithPassword(USERNAME, PASSWORD);
398 assertTrue(isAuthenticated);
399 logger.info("user authenticated");
400 final Session sess = conn.openSession();
401 sess.startSubSystem("netconf");
402 logger.info("user authenticated");
403 sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
409 byte[] bytes = new byte[1024];
412 c = sess.getStdout().read(bytes);
413 } catch (IOException e) {
414 e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
416 logger.info("got data:" + bytes);