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.netconf.client.test.TestingNetconfClient;
26 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
27 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
28 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
29 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
30 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
31 import org.opendaylight.controller.netconf.StubUserManager;
32 import org.opendaylight.controller.netconf.api.NetconfMessage;
33 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
34 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
35 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
36 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
37 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
38 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
39 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
40 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
41 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
42 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
43 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
44 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
45 import org.opendaylight.controller.netconf.util.xml.XmlElement;
46 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.w3c.dom.Document;
50 import org.w3c.dom.Element;
51 import org.w3c.dom.NamedNodeMap;
52 import org.w3c.dom.Node;
53 import org.xml.sax.SAXException;
55 import javax.management.ObjectName;
56 import javax.xml.parsers.ParserConfigurationException;
57 import java.io.IOException;
58 import java.io.InputStream;
59 import java.lang.management.ManagementFactory;
60 import java.net.InetSocketAddress;
61 import java.util.ArrayList;
62 import java.util.Arrays;
63 import java.util.Collection;
64 import java.util.Collections;
65 import java.util.List;
67 import java.util.concurrent.ExecutionException;
68 import java.util.concurrent.TimeoutException;
70 import static java.util.Collections.emptyList;
71 import static org.junit.Assert.assertEquals;
72 import static org.junit.Assert.assertNotNull;
73 import static org.junit.Assert.assertTrue;
74 import static org.mockito.Matchers.anyString;
75 import static org.mockito.Mockito.doReturn;
76 import static org.mockito.Mockito.mock;
78 public class NetconfITTest extends AbstractNetconfConfigTest {
80 // TODO refactor, pull common code up to AbstractNetconfITTest
82 private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
84 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
85 private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
86 private static final String USERNAME = "netconf";
87 private static final String PASSWORD = "netconf";
89 private NetconfMessage getConfig, getConfigCandidate, editConfig,
90 closeSession, startExi, stopExi;
91 private DefaultCommitNotificationProducer commitNot;
92 private NetconfServerDispatcher dispatch;
94 private NetconfClientDispatcher clientDispatcher;
97 public void setUp() throws Exception {
98 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,getModuleFactories().toArray(
99 new ModuleFactory[0])));
103 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
104 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
107 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
109 dispatch = createDispatcher(factoriesListener);
110 ChannelFuture s = dispatch.createServer(tcpAddress);
113 clientDispatcher = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup, 5000);
116 private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
117 return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNot);
120 static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
121 NetconfOperationProvider netconfOperationProvider = mock(NetconfOperationProvider.class);
122 NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class);
123 doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
124 doReturn(snap).when(netconfOperationProvider).openSnapshot(anyString());
125 return new NetconfMonitoringServiceImpl(netconfOperationProvider);
129 public void tearDown() throws Exception {
131 clientDispatcher.close();
134 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
135 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
136 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
137 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
138 this.startExi = XmlFileLoader
139 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
140 this.stopExi = XmlFileLoader
141 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
142 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
145 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
146 final Collection<InputStream> yangDependencies = getBasicYangs();
147 return new HardcodedYangStoreService(yangDependencies);
150 static Collection<InputStream> getBasicYangs() throws IOException {
152 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
153 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
154 "/META-INF/yang/ietf-inet-types.yang");
155 final Collection<InputStream> yangDependencies = new ArrayList<>();
156 List<String> failedToFind = new ArrayList<>();
157 for (String path : paths) {
158 InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
159 if (resourceAsStream == null) {
160 failedToFind.add(path);
162 yangDependencies.add(resourceAsStream);
165 assertEquals("Some yang files were not found", emptyList(), failedToFind);
166 return yangDependencies;
169 protected List<ModuleFactory> getModuleFactories() {
170 return getModuleFactoriesS();
173 static List<ModuleFactory> getModuleFactoriesS() {
174 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
175 new NetconfTestImplModuleFactory());
179 public void testNetconfClientDemonstration() throws Exception {
180 try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
182 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
183 long sessionId = netconfClient.getSessionId();
185 // NetconfMessage can be created :
186 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
188 NetconfMessage response = netconfClient.sendMessage(getConfig);
189 response.getDocument();
194 public void testTwoSessions() throws Exception {
195 try (TestingNetconfClient netconfClient = new TestingNetconfClient("1", tcpAddress, 10000, clientDispatcher)) {
196 try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("2", tcpAddress, 10000, clientDispatcher)) {
203 public void waitingTest() throws Exception {
204 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
205 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
206 transaction.commit();
207 Thread.currentThread().suspend();
211 public void rpcReplyContainsAllAttributesTest() throws Exception {
212 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
213 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
214 + "<get/>" + "</rpc>";
215 final Document doc = XmlUtil.readXmlToDocument(rpc);
216 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
217 assertNotNull(message);
218 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
219 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
221 assertSameAttributes(expectedAttributes, returnedAttributes);
225 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
226 assertNotNull("Expecting 4 attributes", returnedAttributes);
227 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
229 for (int i = 0; i < expectedAttributes.getLength(); i++) {
230 final Node expAttr = expectedAttributes.item(i);
231 final Node attr = returnedAttributes.item(i);
232 assertEquals(expAttr.getNodeName(), attr.getNodeName());
233 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
234 assertEquals(expAttr.getTextContent(), attr.getTextContent());
239 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
240 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
241 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
242 + "<commit/>" + "</rpc>";
243 final Document doc = XmlUtil.readXmlToDocument(rpc);
244 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
245 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
246 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
248 assertSameAttributes(expectedAttributes, returnedAttributes);
253 public void rpcOutputContainsCorrectNamespace() throws Exception {
254 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
255 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
256 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
257 NetconfTestImplModuleMXBean proxy = configRegistryClient
258 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
259 proxy.setTestingDep(dep);
260 proxy.setSimpleShort((short) 0);
262 transaction.commit();
264 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
265 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
267 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
271 + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
272 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
273 final Document doc = XmlUtil.readXmlToDocument(rpc);
274 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
276 final Element rpcReply = message.getDocument().getDocumentElement();
277 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
278 assertEquals("result", resultElement.getName());
280 final String namespace = resultElement.getNamespaceAttribute();
281 assertEquals(expectedNamespace, namespace);
286 public void testCloseSession() throws Exception {
287 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
290 Document rpcReply = netconfClient.sendMessage(this.editConfig)
292 assertIsOK(rpcReply);
294 rpcReply = netconfClient.sendMessage(this.closeSession)
297 assertIsOK(rpcReply);
302 public void testEditConfig() throws Exception {
303 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
304 // send edit_config.xml
305 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
306 assertIsOK(rpcReply);
311 public void testValidate() throws Exception {
312 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
314 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
315 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
318 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
320 assertIsOK(rpcReply);
324 private void assertIsOK(final Document rpcReply) {
325 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
326 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
329 private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException {
330 return assertGetConfigWorks(netconfClient, this.getConfig);
333 private Document assertGetConfigWorks(final TestingNetconfClient netconfClient, final NetconfMessage getConfigMessage)
334 throws InterruptedException, ExecutionException, TimeoutException {
335 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
336 assertNotNull(rpcReply);
337 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
338 return rpcReply.getDocument();
342 public void testGetConfig() throws Exception {
343 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
344 assertGetConfigWorks(netconfClient);
349 public void createYangTestBasedOnYuma() throws Exception {
350 try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
351 Document rpcReply = netconfClient.sendMessage(
352 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
354 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
355 assertIsOK(rpcReply);
356 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
357 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
359 assertIsOK(rpcReply);
361 final ObjectName on = new ObjectName(
362 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
363 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
364 assertEquals(cfgBeans, Sets.newHashSet(on));
368 private TestingNetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
369 final TestingNetconfClient netconfClient = new TestingNetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
370 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
371 return netconfClient;
374 private void startSSHServer() throws Exception {
375 logger.info("Creating SSH server");
376 StubUserManager um = new StubUserManager(USERNAME, PASSWORD);
378 try (InputStream is = getClass().getResourceAsStream("/RSA.pk")) {
379 pem = IOUtils.toString(is);
381 AuthProvider ap = new AuthProvider(um, pem);
382 Thread sshServerThread = new Thread(NetconfSSHServer.start(10830, tcpAddress, ap));
383 sshServerThread.setDaemon(true);
384 sshServerThread.start();
385 logger.info("SSH server on");
389 public void sshTest() throws Exception {
391 logger.info("creating connection");
392 Connection conn = new Connection(sshAddress.getHostName(), sshAddress.getPort());
393 Assert.assertNotNull(conn);
394 logger.info("connection created");
396 boolean isAuthenticated = conn.authenticateWithPassword(USERNAME, PASSWORD);
397 assertTrue(isAuthenticated);
398 logger.info("user authenticated");
399 final Session sess = conn.openSession();
400 sess.startSubSystem("netconf");
401 logger.info("user authenticated");
402 sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
408 byte[] bytes = new byte[1024];
411 c = sess.getStdout().read(bytes);
412 } catch (IOException e) {
413 e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
415 logger.info("got data:" + bytes);