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 io.netty.channel.EventLoopGroup;
17 import io.netty.channel.nio.NioEventLoopGroup;
18 import io.netty.util.HashedWheelTimer;
19 import junit.framework.Assert;
20 import org.junit.After;
21 import org.junit.Before;
22 import org.junit.Ignore;
23 import org.junit.Test;
24 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
25 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
26 import org.opendaylight.controller.config.spi.ModuleFactory;
27 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
28 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
29 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
30 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
31 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
32 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
33 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
34 import org.opendaylight.controller.netconf.StubUserManager;
35 import org.opendaylight.controller.netconf.api.NetconfMessage;
36 import org.opendaylight.controller.netconf.client.NetconfClient;
37 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
38 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
39 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
40 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
41 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
42 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
43 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
44 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
45 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListener;
46 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
47 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshot;
48 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
49 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
50 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
51 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
52 import org.opendaylight.controller.netconf.util.xml.XmlElement;
53 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.w3c.dom.NamedNodeMap;
59 import org.w3c.dom.Node;
60 import org.xml.sax.SAXException;
62 import javax.management.ObjectName;
63 import javax.xml.parsers.ParserConfigurationException;
64 import java.io.IOException;
65 import java.io.InputStream;
66 import java.lang.management.ManagementFactory;
67 import java.net.InetSocketAddress;
68 import java.util.ArrayList;
69 import java.util.Arrays;
70 import java.util.Collection;
71 import java.util.Collections;
72 import java.util.List;
74 import java.util.concurrent.TimeUnit;
76 import static java.util.Collections.emptyList;
77 import static junit.framework.Assert.assertEquals;
78 import static junit.framework.Assert.assertNotNull;
79 import static junit.framework.Assert.assertTrue;
80 import static org.mockito.Matchers.anyLong;
81 import static org.mockito.Mockito.doReturn;
82 import static org.mockito.Mockito.mock;
84 public class NetconfITTest extends AbstractConfigTest {
86 // TODO refactor, pull common code up to AbstractNetconfITTest
88 private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
90 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
91 private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
92 private static final String USERNAME = "netconf";
93 private static final String PASSWORD = "netconf";
95 private NetconfMessage getConfig, getConfigCandidate, editConfig,
96 closeSession, startExi, stopExi;
97 private DefaultCommitNotificationProducer commitNot;
98 private NetconfServerDispatcher dispatch;
99 private EventLoopGroup nettyThreadgroup;
101 private NetconfClientDispatcher clientDispatcher;
104 public void setUp() throws Exception {
105 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
106 new ModuleFactory[0])));
110 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
111 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
113 nettyThreadgroup = new NioEventLoopGroup();
115 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
117 dispatch = createDispatcher(factoriesListener);
118 ChannelFuture s = dispatch.createServer(tcpAddress);
121 clientDispatcher = new NetconfClientDispatcher( nettyThreadgroup, nettyThreadgroup);
124 private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
125 SessionIdProvider idProvider = new SessionIdProvider();
126 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
127 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
129 NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
130 factoriesListener, commitNot, idProvider, getNetconfMonitoringListenerService());
132 NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
133 serverNegotiatorFactory, listenerFactory);
134 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
137 static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
138 NetconfOperationServiceFactoryListener factoriesListener = mock(NetconfOperationServiceFactoryListener.class);
139 NetconfOperationServiceSnapshot snap = mock(NetconfOperationServiceSnapshot.class);
140 doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
141 doReturn(snap).when(factoriesListener).getSnapshot(anyLong());
142 return new NetconfMonitoringServiceImpl(factoriesListener);
146 public void tearDown() throws Exception {
148 nettyThreadgroup.shutdownGracefully();
149 clientDispatcher.close();
152 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
153 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
154 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
155 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
156 this.startExi = XmlFileLoader
157 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
158 this.stopExi = XmlFileLoader
159 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
160 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
163 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
164 final Collection<InputStream> yangDependencies = getBasicYangs();
165 return new HardcodedYangStoreService(yangDependencies);
168 static Collection<InputStream> getBasicYangs() throws IOException {
169 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
170 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
171 "/META-INF/yang/ietf-inet-types.yang");
172 final Collection<InputStream> yangDependencies = new ArrayList<>();
173 List<String> failedToFind = new ArrayList<>();
174 for (String path : paths) {
175 InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
176 if (resourceAsStream == null) {
177 failedToFind.add(path);
179 yangDependencies.add(resourceAsStream);
182 assertEquals("Some yang files were not found",emptyList(), failedToFind);
183 return yangDependencies;
186 protected List<ModuleFactory> getModuleFactories() {
187 return getModuleFactoriesS();
189 static List<ModuleFactory> getModuleFactoriesS() {
190 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
191 new NetconfTestImplModuleFactory());
195 public void testNetconfClientDemonstration() throws Exception {
196 try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
198 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
199 long sessionId = netconfClient.getSessionId();
201 // NetconfMessage can be created :
202 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
204 NetconfMessage response = netconfClient.sendMessage(getConfig);
205 response.getDocument();
210 public void testTwoSessions() throws Exception {
211 try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 10000, clientDispatcher)) {
212 try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 10000, clientDispatcher)) {
219 public void waitingTest() throws Exception {
220 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
221 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
222 transaction.commit();
223 Thread.currentThread().suspend();
227 public void rpcReplyContainsAllAttributesTest() throws Exception {
228 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
229 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
230 + "<get/>" + "</rpc>";
231 final Document doc = XmlUtil.readXmlToDocument(rpc);
232 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
233 assertNotNull(message);
234 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
235 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
237 assertSameAttributes(expectedAttributes, returnedAttributes);
241 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
242 assertNotNull("Expecting 4 attributes", returnedAttributes);
243 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
245 for (int i = 0; i < expectedAttributes.getLength(); i++) {
246 final Node expAttr = expectedAttributes.item(i);
247 final Node attr = returnedAttributes.item(i);
248 assertEquals(expAttr.getNodeName(), attr.getNodeName());
249 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
250 assertEquals(expAttr.getTextContent(), attr.getTextContent());
255 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
256 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
257 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
258 + "<commit/>" + "</rpc>";
259 final Document doc = XmlUtil.readXmlToDocument(rpc);
260 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
261 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
262 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
264 assertSameAttributes(expectedAttributes, returnedAttributes);
269 public void rpcOutputContainsCorrectNamespace() throws Exception {
270 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
271 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
272 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
273 NetconfTestImplModuleMXBean proxy = configRegistryClient
274 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
275 proxy.setTestingDep(dep);
276 proxy.setSimpleShort((short)0);
278 transaction.commit();
280 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
281 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
283 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
287 + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
288 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
289 final Document doc = XmlUtil.readXmlToDocument(rpc);
290 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
292 final Element rpcReply = message.getDocument().getDocumentElement();
293 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
294 assertEquals("result", resultElement.getName());
296 final String namespace = resultElement.getNamespaceAttribute();
297 assertEquals(expectedNamespace, namespace);
303 public void testStartExi() throws Exception {
304 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
307 Document rpcReply = netconfClient.sendMessage(this.startExi)
309 assertIsOK(rpcReply);
311 ExiParameters exiParams = new ExiParameters();
312 exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
314 netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
315 netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
317 rpcReply = netconfClient.sendMessage(this.editConfig)
319 assertIsOK(rpcReply);
321 rpcReply = netconfClient.sendMessage(this.stopExi)
323 assertIsOK(rpcReply);
330 public void testCloseSession() throws Exception {
331 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
334 Document rpcReply = netconfClient.sendMessage(this.editConfig)
336 assertIsOK(rpcReply);
338 rpcReply = netconfClient.sendMessage(this.closeSession)
341 assertIsOK(rpcReply);
346 public void testEditConfig() throws Exception {
347 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
348 // send edit_config.xml
349 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
350 assertIsOK(rpcReply);
355 public void testValidate() throws Exception {
356 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
358 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
359 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
362 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
364 assertIsOK(rpcReply);
368 private void assertIsOK(final Document rpcReply) {
369 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
370 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
373 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
374 return assertGetConfigWorks(netconfClient, this.getConfig);
377 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
378 throws InterruptedException {
379 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
380 assertNotNull(rpcReply);
381 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
382 return rpcReply.getDocument();
386 public void testGetConfig() throws Exception {
387 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
388 assertGetConfigWorks(netconfClient);
393 public void createYangTestBasedOnYuma() throws Exception {
394 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
395 Document rpcReply = netconfClient.sendMessage(
396 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
398 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
399 assertIsOK(rpcReply);
400 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
401 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
403 assertIsOK(rpcReply);
405 final ObjectName on = new ObjectName(
406 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
407 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
408 assertEquals(cfgBeans, Sets.newHashSet(on));
412 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
413 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
414 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
415 return netconfClient;
418 private void startSSHServer() throws Exception{
419 logger.info("Creating SSH server");
420 StubUserManager um = new StubUserManager(USERNAME,PASSWORD);
421 InputStream is = getClass().getResourceAsStream("/RSA.pk");
422 AuthProvider ap = new AuthProvider(um, is);
423 Thread sshServerThread = new Thread(NetconfSSHServer.start(10830,tcpAddress,ap));
424 sshServerThread.setDaemon(true);
425 sshServerThread.start();
426 logger.info("SSH server on");
430 public void sshTest() throws Exception {
432 logger.info("creating connection");
433 Connection conn = new Connection(sshAddress.getHostName(),sshAddress.getPort());
434 Assert.assertNotNull(conn);
435 logger.info("connection created");
437 boolean isAuthenticated = conn.authenticateWithPassword(USERNAME,PASSWORD);
438 assertTrue(isAuthenticated);
439 logger.info("user authenticated");
440 final Session sess = conn.openSession();
441 sess.startSubSystem("netconf");
442 logger.info("user authenticated");
443 sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
448 byte[] bytes = new byte[1024];
451 c = sess.getStdout().read(bytes);
452 } catch (IOException e) {
453 e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
455 logger.info("got data:"+bytes);