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 java.io.IOException;
20 import java.io.InputStream;
21 import java.lang.management.ManagementFactory;
22 import java.net.InetSocketAddress;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
29 import java.util.concurrent.TimeUnit;
30 import javax.management.ObjectName;
31 import javax.xml.parsers.ParserConfigurationException;
32 import junit.framework.Assert;
33 import org.junit.After;
34 import org.junit.Before;
35 import org.junit.Ignore;
36 import org.junit.Test;
37 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
38 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
39 import org.opendaylight.controller.config.spi.ModuleFactory;
40 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
41 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
42 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
43 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
44 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
45 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
46 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
47 import org.opendaylight.controller.netconf.StubUserManager;
48 import org.opendaylight.controller.netconf.api.NetconfMessage;
49 import org.opendaylight.controller.netconf.client.NetconfClient;
50 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
51 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
52 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
53 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
54 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
55 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
56 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
57 import org.opendaylight.controller.netconf.impl.mapping.ExiDecoderHandler;
58 import org.opendaylight.controller.netconf.impl.mapping.ExiEncoderHandler;
59 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
60 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListener;
61 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
62 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshot;
63 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
64 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
65 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
66 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
67 import org.opendaylight.controller.netconf.util.xml.ExiParameters;
68 import org.opendaylight.controller.netconf.util.xml.XmlElement;
69 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import org.w3c.dom.Document;
73 import org.w3c.dom.Element;
74 import org.w3c.dom.NamedNodeMap;
75 import org.w3c.dom.Node;
76 import org.xml.sax.SAXException;
77 import static java.util.Collections.emptyList;
78 import static junit.framework.Assert.assertEquals;
79 import static junit.framework.Assert.assertNotNull;
80 import static junit.framework.Assert.assertTrue;
81 import static org.mockito.Matchers.anyLong;
82 import static org.mockito.Mockito.doReturn;
83 import static org.mockito.Mockito.mock;
85 public class NetconfITTest extends AbstractConfigTest {
87 // TODO refactor, pull common code up to AbstractNetconfITTest
89 private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
91 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
92 private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
93 private static final String USERNAME = "netconf";
94 private static final String PASSWORD = "netconf";
96 private NetconfMessage getConfig, getConfigCandidate, editConfig,
97 closeSession, startExi, stopExi;
98 private DefaultCommitNotificationProducer commitNot;
99 private NetconfServerDispatcher dispatch;
100 private EventLoopGroup nettyThreadgroup;
102 private NetconfClientDispatcher clientDispatcher;
105 public void setUp() throws Exception {
106 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
107 new ModuleFactory[0])));
111 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
112 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
114 nettyThreadgroup = new NioEventLoopGroup();
116 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
118 dispatch = createDispatcher(factoriesListener);
119 ChannelFuture s = dispatch.createServer(tcpAddress);
122 clientDispatcher = new NetconfClientDispatcher( nettyThreadgroup, nettyThreadgroup);
125 private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
126 SessionIdProvider idProvider = new SessionIdProvider();
127 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
128 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
130 NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
131 factoriesListener, commitNot, idProvider, getNetconfMonitoringListenerService());
133 NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
134 serverNegotiatorFactory, listenerFactory);
135 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
138 static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
139 NetconfOperationServiceFactoryListener factoriesListener = mock(NetconfOperationServiceFactoryListener.class);
140 NetconfOperationServiceSnapshot snap = mock(NetconfOperationServiceSnapshot.class);
141 doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
142 doReturn(snap).when(factoriesListener).getSnapshot(anyLong());
143 return new NetconfMonitoringServiceImpl(factoriesListener);
147 public void tearDown() throws Exception {
149 nettyThreadgroup.shutdownGracefully();
150 clientDispatcher.close();
153 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
154 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
155 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
156 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
157 this.startExi = XmlFileLoader
158 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
159 this.stopExi = XmlFileLoader
160 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
161 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
164 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
165 final Collection<InputStream> yangDependencies = getBasicYangs();
166 return new HardcodedYangStoreService(yangDependencies);
169 static Collection<InputStream> getBasicYangs() throws IOException {
170 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
171 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
172 "/META-INF/yang/ietf-inet-types.yang");
173 final Collection<InputStream> yangDependencies = new ArrayList<>();
174 List<String> failedToFind = new ArrayList<>();
175 for (String path : paths) {
176 InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
177 if (resourceAsStream == null) {
178 failedToFind.add(path);
180 yangDependencies.add(resourceAsStream);
183 assertEquals("Some yang files were not found",emptyList(), failedToFind);
184 return yangDependencies;
187 protected List<ModuleFactory> getModuleFactories() {
188 return getModuleFactoriesS();
190 static List<ModuleFactory> getModuleFactoriesS() {
191 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
192 new NetconfTestImplModuleFactory());
196 public void testNetconfClientDemonstration() throws Exception {
197 try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
199 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
200 long sessionId = netconfClient.getSessionId();
202 // NetconfMessage can be created :
203 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
205 NetconfMessage response = netconfClient.sendMessage(getConfig);
206 response.getDocument();
211 public void testTwoSessions() throws Exception {
212 try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 10000, clientDispatcher)) {
213 try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 10000, clientDispatcher)) {
219 //TODO: test persister actually
221 @Test(timeout = 10000)
222 public void testPersister() throws Exception {
223 // Persister persister = mock(Persister.class);
224 // doReturn("mockPersister").when(persister).toString();
225 // doReturn(Collections.emptyList()).when(persister).loadLastConfigs();
226 // ConfigPersisterNotificationHandler h =
227 // new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer(),
228 // Pattern.compile(ConfigPersisterActivator.DEFAULT_IGNORED_REGEX));
234 public void waitingTest() throws Exception {
235 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
236 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
237 transaction.commit();
238 Thread.currentThread().suspend();
242 public void rpcReplyContainsAllAttributesTest() throws Exception {
243 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
244 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
245 + "<get/>" + "</rpc>";
246 final Document doc = XmlUtil.readXmlToDocument(rpc);
247 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
248 assertNotNull(message);
249 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
250 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
252 assertSameAttributes(expectedAttributes, returnedAttributes);
256 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
257 assertNotNull("Expecting 4 attributes", returnedAttributes);
258 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
260 for (int i = 0; i < expectedAttributes.getLength(); i++) {
261 final Node expAttr = expectedAttributes.item(i);
262 final Node attr = returnedAttributes.item(i);
263 assertEquals(expAttr.getNodeName(), attr.getNodeName());
264 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
265 assertEquals(expAttr.getTextContent(), attr.getTextContent());
270 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
271 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
272 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
273 + "<commit/>" + "</rpc>";
274 final Document doc = XmlUtil.readXmlToDocument(rpc);
275 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
276 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
277 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
279 assertSameAttributes(expectedAttributes, returnedAttributes);
284 public void rpcOutputContainsCorrectNamespace() throws Exception {
285 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
286 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
287 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
288 NetconfTestImplModuleMXBean proxy = configRegistryClient
289 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
290 proxy.setTestingDep(dep);
291 proxy.setSimpleShort((short)0);
293 transaction.commit();
295 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
296 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
298 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
302 + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
303 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
304 final Document doc = XmlUtil.readXmlToDocument(rpc);
305 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
307 final Element rpcReply = message.getDocument().getDocumentElement();
308 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
309 assertEquals("result", resultElement.getName());
311 final String namespace = resultElement.getNamespaceAttribute();
312 assertEquals(expectedNamespace, namespace);
318 public void testStartExi() throws Exception {
319 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
322 Document rpcReply = netconfClient.sendMessage(this.startExi)
324 assertIsOK(rpcReply);
326 ExiParameters exiParams = new ExiParameters();
327 exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
329 netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
330 netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
332 rpcReply = netconfClient.sendMessage(this.editConfig)
334 assertIsOK(rpcReply);
336 rpcReply = netconfClient.sendMessage(this.stopExi)
338 assertIsOK(rpcReply);
344 public void testCloseSession() throws Exception {
345 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
348 Document rpcReply = netconfClient.sendMessage(this.editConfig)
350 assertIsOK(rpcReply);
352 rpcReply = netconfClient.sendMessage(this.closeSession)
355 assertIsOK(rpcReply);
360 public void testEditConfig() throws Exception {
361 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
362 // send edit_config.xml
363 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
364 assertIsOK(rpcReply);
369 public void testValidate() throws Exception {
370 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
372 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
373 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
376 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
378 assertIsOK(rpcReply);
382 private void assertIsOK(final Document rpcReply) {
383 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
384 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
387 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
388 return assertGetConfigWorks(netconfClient, this.getConfig);
391 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
392 throws InterruptedException {
393 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
394 assertNotNull(rpcReply);
395 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
396 return rpcReply.getDocument();
400 public void testGetConfig() throws Exception {
401 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
402 assertGetConfigWorks(netconfClient);
407 public void createYangTestBasedOnYuma() throws Exception {
408 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
409 Document rpcReply = netconfClient.sendMessage(
410 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
412 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
413 assertIsOK(rpcReply);
414 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
415 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
417 assertIsOK(rpcReply);
419 final ObjectName on = new ObjectName(
420 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
421 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
422 assertEquals(cfgBeans, Sets.newHashSet(on));
426 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
427 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
428 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
429 return netconfClient;
432 private void startSSHServer() throws Exception{
433 logger.info("Creating SSH server");
434 StubUserManager um = new StubUserManager(USERNAME,PASSWORD);
435 InputStream is = getClass().getResourceAsStream("/RSA.pk");
436 AuthProvider ap = new AuthProvider(um, is);
437 Thread sshServerThread = new Thread(NetconfSSHServer.start(10830,tcpAddress,ap));
438 sshServerThread.setDaemon(true);
439 sshServerThread.start();
440 logger.info("SSH server on");
444 public void sshTest() throws Exception {
446 logger.info("creating connection");
447 Connection conn = new Connection(sshAddress.getHostName(),sshAddress.getPort());
448 Assert.assertNotNull(conn);
449 logger.info("connection created");
451 boolean isAuthenticated = conn.authenticateWithPassword(USERNAME,PASSWORD);
452 assertTrue(isAuthenticated);
453 logger.info("user authenticated");
454 final Session sess = conn.openSession();
455 sess.startSubSystem("netconf");
456 logger.info("user authenticated");
457 sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
462 byte[] bytes = new byte[1024];
465 c = sess.getStdout().read(bytes);
466 } catch (IOException e) {
467 e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
469 logger.info("got data:"+bytes);