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.junit.After;
18 import org.junit.Before;
19 import org.junit.Ignore;
20 import org.junit.Test;
21 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
22 import org.opendaylight.controller.config.spi.ModuleFactory;
23 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
24 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
25 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
26 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
27 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
28 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
29 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
30 import org.opendaylight.controller.netconf.StubUserManager;
31 import org.opendaylight.controller.netconf.api.NetconfMessage;
32 import org.opendaylight.controller.netconf.client.NetconfClient;
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.NetconfOperationServiceFactoryListener;
39 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
40 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshot;
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;
68 import static java.util.Collections.emptyList;
69 import static junit.framework.Assert.assertEquals;
70 import static junit.framework.Assert.assertNotNull;
71 import static junit.framework.Assert.assertTrue;
72 import static org.mockito.Matchers.anyLong;
73 import static org.mockito.Mockito.doReturn;
74 import static org.mockito.Mockito.mock;
76 public class NetconfITTest extends AbstractNetconfConfigTest {
78 // TODO refactor, pull common code up to AbstractNetconfITTest
80 private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
82 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
83 private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
84 private static final String USERNAME = "netconf";
85 private static final String PASSWORD = "netconf";
87 private NetconfMessage getConfig, getConfigCandidate, editConfig,
88 closeSession, startExi, stopExi;
89 private DefaultCommitNotificationProducer commitNot;
90 private NetconfServerDispatcher dispatch;
92 private NetconfClientDispatcher clientDispatcher;
95 public void setUp() throws Exception {
96 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
97 new ModuleFactory[0])));
101 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
102 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
105 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
107 dispatch = createDispatcher(factoriesListener);
108 ChannelFuture s = dispatch.createServer(tcpAddress);
111 clientDispatcher = new NetconfClientDispatcher( nettyThreadgroup, nettyThreadgroup, 5000);
114 private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
115 return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNot);
118 static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
119 NetconfOperationServiceFactoryListener factoriesListener = mock(NetconfOperationServiceFactoryListener.class);
120 NetconfOperationServiceSnapshot snap = mock(NetconfOperationServiceSnapshot.class);
121 doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
122 doReturn(snap).when(factoriesListener).getSnapshot(anyLong());
123 return new NetconfMonitoringServiceImpl(factoriesListener);
127 public void tearDown() throws Exception {
129 clientDispatcher.close();
132 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
133 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
134 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
135 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
136 this.startExi = XmlFileLoader
137 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
138 this.stopExi = XmlFileLoader
139 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
140 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
143 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
144 final Collection<InputStream> yangDependencies = getBasicYangs();
145 return new HardcodedYangStoreService(yangDependencies);
148 static Collection<InputStream> getBasicYangs() throws IOException {
149 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
150 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
151 "/META-INF/yang/ietf-inet-types.yang");
152 final Collection<InputStream> yangDependencies = new ArrayList<>();
153 List<String> failedToFind = new ArrayList<>();
154 for (String path : paths) {
155 InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
156 if (resourceAsStream == null) {
157 failedToFind.add(path);
159 yangDependencies.add(resourceAsStream);
162 assertEquals("Some yang files were not found",emptyList(), failedToFind);
163 return yangDependencies;
166 protected List<ModuleFactory> getModuleFactories() {
167 return getModuleFactoriesS();
169 static List<ModuleFactory> getModuleFactoriesS() {
170 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
171 new NetconfTestImplModuleFactory());
175 public void testNetconfClientDemonstration() throws Exception {
176 try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
178 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
179 long sessionId = netconfClient.getSessionId();
181 // NetconfMessage can be created :
182 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
184 NetconfMessage response = netconfClient.sendMessage(getConfig);
185 response.getDocument();
190 public void testTwoSessions() throws Exception {
191 try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 10000, clientDispatcher)) {
192 try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 10000, clientDispatcher)) {
199 public void waitingTest() throws Exception {
200 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
201 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
202 transaction.commit();
203 Thread.currentThread().suspend();
207 public void rpcReplyContainsAllAttributesTest() throws Exception {
208 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
209 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
210 + "<get/>" + "</rpc>";
211 final Document doc = XmlUtil.readXmlToDocument(rpc);
212 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
213 assertNotNull(message);
214 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
215 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
217 assertSameAttributes(expectedAttributes, returnedAttributes);
221 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
222 assertNotNull("Expecting 4 attributes", returnedAttributes);
223 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
225 for (int i = 0; i < expectedAttributes.getLength(); i++) {
226 final Node expAttr = expectedAttributes.item(i);
227 final Node attr = returnedAttributes.item(i);
228 assertEquals(expAttr.getNodeName(), attr.getNodeName());
229 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
230 assertEquals(expAttr.getTextContent(), attr.getTextContent());
235 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
236 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
237 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
238 + "<commit/>" + "</rpc>";
239 final Document doc = XmlUtil.readXmlToDocument(rpc);
240 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
241 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
242 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
244 assertSameAttributes(expectedAttributes, returnedAttributes);
249 public void rpcOutputContainsCorrectNamespace() throws Exception {
250 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
251 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
252 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
253 NetconfTestImplModuleMXBean proxy = configRegistryClient
254 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
255 proxy.setTestingDep(dep);
256 proxy.setSimpleShort((short)0);
258 transaction.commit();
260 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
261 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
263 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
267 + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
268 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
269 final Document doc = XmlUtil.readXmlToDocument(rpc);
270 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
272 final Element rpcReply = message.getDocument().getDocumentElement();
273 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
274 assertEquals("result", resultElement.getName());
276 final String namespace = resultElement.getNamespaceAttribute();
277 assertEquals(expectedNamespace, namespace);
283 public void testStartExi() throws Exception {
284 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
287 Document rpcReply = netconfClient.sendMessage(this.startExi)
289 assertIsOK(rpcReply);
291 ExiParameters exiParams = new ExiParameters();
292 exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
294 netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
295 netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
297 rpcReply = netconfClient.sendMessage(this.editConfig)
299 assertIsOK(rpcReply);
301 rpcReply = netconfClient.sendMessage(this.stopExi)
303 assertIsOK(rpcReply);
310 public void testCloseSession() throws Exception {
311 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
314 Document rpcReply = netconfClient.sendMessage(this.editConfig)
316 assertIsOK(rpcReply);
318 rpcReply = netconfClient.sendMessage(this.closeSession)
321 assertIsOK(rpcReply);
326 public void testEditConfig() throws Exception {
327 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
328 // send edit_config.xml
329 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
330 assertIsOK(rpcReply);
335 public void testValidate() throws Exception {
336 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
338 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
339 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
342 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
344 assertIsOK(rpcReply);
348 private void assertIsOK(final Document rpcReply) {
349 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
350 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
353 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
354 return assertGetConfigWorks(netconfClient, this.getConfig);
357 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
358 throws InterruptedException {
359 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
360 assertNotNull(rpcReply);
361 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
362 return rpcReply.getDocument();
366 public void testGetConfig() throws Exception {
367 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
368 assertGetConfigWorks(netconfClient);
373 public void createYangTestBasedOnYuma() throws Exception {
374 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
375 Document rpcReply = netconfClient.sendMessage(
376 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
378 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
379 assertIsOK(rpcReply);
380 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
381 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
383 assertIsOK(rpcReply);
385 final ObjectName on = new ObjectName(
386 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
387 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
388 assertEquals(cfgBeans, Sets.newHashSet(on));
392 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
393 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
394 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
395 return netconfClient;
398 private void startSSHServer() throws Exception{
399 logger.info("Creating SSH server");
400 StubUserManager um = new StubUserManager(USERNAME,PASSWORD);
401 InputStream is = getClass().getResourceAsStream("/RSA.pk");
402 AuthProvider ap = new AuthProvider(um, is);
403 Thread sshServerThread = new Thread(NetconfSSHServer.start(10830,tcpAddress,ap));
404 sshServerThread.setDaemon(true);
405 sshServerThread.start();
406 logger.info("SSH server on");
410 public void sshTest() throws Exception {
412 logger.info("creating connection");
413 Connection conn = new Connection(sshAddress.getHostName(),sshAddress.getPort());
414 Assert.assertNotNull(conn);
415 logger.info("connection created");
417 boolean isAuthenticated = conn.authenticateWithPassword(USERNAME,PASSWORD);
418 assertTrue(isAuthenticated);
419 logger.info("user authenticated");
420 final Session sess = conn.openSession();
421 sess.startSubSystem("netconf");
422 logger.info("user authenticated");
423 sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
428 byte[] bytes = new byte[1024];
431 c = sess.getStdout().read(bytes);
432 } catch (IOException e) {
433 e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
435 logger.info("got data:"+bytes);