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 static java.util.Collections.emptyList;
12 import static junit.framework.Assert.assertEquals;
13 import static junit.framework.Assert.assertNotNull;
14 import static junit.framework.Assert.assertTrue;
15 import static org.mockito.Matchers.anyLong;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.Mockito.mock;
18 import io.netty.channel.ChannelFuture;
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.Collections;
28 import java.util.List;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.TimeoutException;
33 import javax.management.ObjectName;
34 import javax.xml.parsers.ParserConfigurationException;
36 import junit.framework.Assert;
38 import org.junit.After;
39 import org.junit.Before;
40 import org.junit.Ignore;
41 import org.junit.Test;
42 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
43 import org.opendaylight.controller.config.spi.ModuleFactory;
44 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
45 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
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.StubUserManager;
51 import org.opendaylight.controller.netconf.api.NetconfMessage;
52 import org.opendaylight.controller.netconf.client.NetconfClient;
53 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
54 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
55 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
56 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
57 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
58 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListener;
59 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
60 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshot;
61 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
62 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
63 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
64 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
65 import org.opendaylight.controller.netconf.util.xml.XmlElement;
66 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import org.w3c.dom.Document;
70 import org.w3c.dom.Element;
71 import org.w3c.dom.NamedNodeMap;
72 import org.w3c.dom.Node;
73 import org.xml.sax.SAXException;
75 import ch.ethz.ssh2.Connection;
76 import ch.ethz.ssh2.Session;
78 import com.google.common.collect.Lists;
79 import com.google.common.collect.Sets;
81 public class NetconfITTest extends AbstractNetconfConfigTest {
83 // TODO refactor, pull common code up to AbstractNetconfITTest
85 private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
87 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
88 private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
89 private static final String USERNAME = "netconf";
90 private static final String PASSWORD = "netconf";
92 private NetconfMessage getConfig, getConfigCandidate, editConfig,
93 closeSession, startExi, stopExi;
94 private DefaultCommitNotificationProducer commitNot;
95 private NetconfServerDispatcher dispatch;
97 private NetconfClientDispatcher clientDispatcher;
100 public void setUp() throws Exception {
101 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
102 new ModuleFactory[0])));
106 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
107 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
110 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
112 dispatch = createDispatcher(factoriesListener);
113 ChannelFuture s = dispatch.createServer(tcpAddress);
116 clientDispatcher = new NetconfClientDispatcher( nettyThreadgroup, nettyThreadgroup, 5000);
119 private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
120 return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNot);
123 static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
124 NetconfOperationServiceFactoryListener factoriesListener = mock(NetconfOperationServiceFactoryListener.class);
125 NetconfOperationServiceSnapshot snap = mock(NetconfOperationServiceSnapshot.class);
126 doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
127 doReturn(snap).when(factoriesListener).getSnapshot(anyLong());
128 return new NetconfMonitoringServiceImpl(factoriesListener);
132 public void tearDown() throws Exception {
134 clientDispatcher.close();
137 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
138 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
139 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
140 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
141 this.startExi = XmlFileLoader
142 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
143 this.stopExi = XmlFileLoader
144 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
145 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
148 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
149 final Collection<InputStream> yangDependencies = getBasicYangs();
150 return new HardcodedYangStoreService(yangDependencies);
153 static Collection<InputStream> getBasicYangs() throws IOException {
154 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
155 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
156 "/META-INF/yang/ietf-inet-types.yang");
157 final Collection<InputStream> yangDependencies = new ArrayList<>();
158 List<String> failedToFind = new ArrayList<>();
159 for (String path : paths) {
160 InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
161 if (resourceAsStream == null) {
162 failedToFind.add(path);
164 yangDependencies.add(resourceAsStream);
167 assertEquals("Some yang files were not found",emptyList(), failedToFind);
168 return yangDependencies;
171 protected List<ModuleFactory> getModuleFactories() {
172 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 (NetconfClient netconfClient = new NetconfClient("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 (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 10000, clientDispatcher)) {
197 try (NetconfClient netconfClient2 = new NetconfClient("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 (NetconfClient 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 (NetconfClient 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 (NetconfClient 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);
288 public void testStartExi() throws Exception {
289 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
292 Document rpcReply = netconfClient.sendMessage(this.startExi)
294 assertIsOK(rpcReply);
296 ExiParameters exiParams = new ExiParameters();
297 exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
299 netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
300 netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
302 rpcReply = netconfClient.sendMessage(this.editConfig)
304 assertIsOK(rpcReply);
306 rpcReply = netconfClient.sendMessage(this.stopExi)
308 assertIsOK(rpcReply);
315 public void testCloseSession() throws Exception {
316 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
319 Document rpcReply = netconfClient.sendMessage(this.editConfig)
321 assertIsOK(rpcReply);
323 rpcReply = netconfClient.sendMessage(this.closeSession)
326 assertIsOK(rpcReply);
331 public void testEditConfig() throws Exception {
332 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
333 // send edit_config.xml
334 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
335 assertIsOK(rpcReply);
340 public void testValidate() throws Exception {
341 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
343 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
344 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
347 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
349 assertIsOK(rpcReply);
353 private void assertIsOK(final Document rpcReply) {
354 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
355 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
358 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException {
359 return assertGetConfigWorks(netconfClient, this.getConfig);
362 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
363 throws InterruptedException, ExecutionException, TimeoutException {
364 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
365 assertNotNull(rpcReply);
366 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
367 return rpcReply.getDocument();
371 public void testGetConfig() throws Exception {
372 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
373 assertGetConfigWorks(netconfClient);
378 public void createYangTestBasedOnYuma() throws Exception {
379 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
380 Document rpcReply = netconfClient.sendMessage(
381 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
383 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
384 assertIsOK(rpcReply);
385 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
386 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
388 assertIsOK(rpcReply);
390 final ObjectName on = new ObjectName(
391 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
392 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
393 assertEquals(cfgBeans, Sets.newHashSet(on));
397 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
398 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
399 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
400 return netconfClient;
403 private void startSSHServer() throws Exception{
404 logger.info("Creating SSH server");
405 StubUserManager um = new StubUserManager(USERNAME,PASSWORD);
406 InputStream is = getClass().getResourceAsStream("/RSA.pk");
407 AuthProvider ap = new AuthProvider(um, is);
408 Thread sshServerThread = new Thread(NetconfSSHServer.start(10830,tcpAddress,ap));
409 sshServerThread.setDaemon(true);
410 sshServerThread.start();
411 logger.info("SSH server on");
415 public void sshTest() throws Exception {
417 logger.info("creating connection");
418 Connection conn = new Connection(sshAddress.getHostName(),sshAddress.getPort());
419 Assert.assertNotNull(conn);
420 logger.info("connection created");
422 boolean isAuthenticated = conn.authenticateWithPassword(USERNAME,PASSWORD);
423 assertTrue(isAuthenticated);
424 logger.info("user authenticated");
425 final Session sess = conn.openSession();
426 sess.startSubSystem("netconf");
427 logger.info("user authenticated");
428 sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
434 byte[] bytes = new byte[1024];
437 c = sess.getStdout().read(bytes);
438 } catch (IOException e) {
439 e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
441 logger.info("got data:"+bytes);