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 com.google.common.base.Optional;
12 import com.google.common.collect.Lists;
13 import com.google.common.collect.Sets;
14 import io.netty.channel.ChannelFuture;
15 import io.netty.channel.EventLoopGroup;
16 import io.netty.channel.nio.NioEventLoopGroup;
17 import io.netty.util.HashedWheelTimer;
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.api.ModuleIdentifier;
23 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
24 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
25 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
26 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
27 import org.opendaylight.controller.config.persist.api.Persister;
28 import org.opendaylight.controller.config.spi.ModuleFactory;
29 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
30 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
31 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
32 import org.opendaylight.controller.config.yang.test.impl.Asdf;
33 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
34 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
35 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
36 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeMXBean;
37 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeRegistrator;
38 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
39 import org.opendaylight.controller.netconf.api.NetconfMessage;
40 import org.opendaylight.controller.netconf.client.NetconfClient;
41 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
42 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
43 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
44 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
45 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
46 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
47 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
48 import org.opendaylight.controller.netconf.impl.mapping.ExiDecoderHandler;
49 import org.opendaylight.controller.netconf.impl.mapping.ExiEncoderHandler;
50 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
51 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
52 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
53 import org.opendaylight.controller.netconf.util.xml.ExiParameters;
54 import org.opendaylight.controller.netconf.util.xml.XmlElement;
55 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
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.net.ssl.SSLContext;
64 import javax.xml.parsers.ParserConfigurationException;
65 import java.io.IOException;
66 import java.io.InputStream;
67 import java.lang.management.ManagementFactory;
68 import java.net.InetSocketAddress;
69 import java.util.ArrayList;
70 import java.util.Arrays;
71 import java.util.Collection;
72 import java.util.List;
74 import java.util.concurrent.TimeUnit;
76 import static junit.framework.Assert.assertEquals;
77 import static junit.framework.Assert.assertNotNull;
78 import static org.mockito.Mockito.doReturn;
79 import static org.mockito.Mockito.mock;
80 import static org.mockito.internal.util.Checks.checkNotNull;
82 public class NetconfITTest extends AbstractConfigTest {
84 // private static final Logger logger =
85 // LoggerFactory.getLogger(NetconfITTest.class);
88 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
90 private NetconfMessage getConfig, getConfigCandidate, editConfig,
91 closeSession, startExi, stopExi;
92 private DefaultCommitNotificationProducer commitNot;
93 private NetconfServerDispatcher dispatch;
94 private EventLoopGroup nettyThreadgroup;
96 private NetconfClientDispatcher clientDispatcher;
99 public void setUp() throws Exception {
100 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
101 new ModuleFactory[0])));
105 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
106 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
108 nettyThreadgroup = new NioEventLoopGroup();
110 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
112 dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
113 ChannelFuture s = dispatch.createServer(tcpAddress);
116 clientDispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
119 private NetconfServerDispatcher createDispatcher(Optional<SSLContext> sslC,
120 NetconfOperationServiceFactoryListenerImpl factoriesListener) {
121 SessionIdProvider idProvider = new SessionIdProvider();
122 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
123 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
125 NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
126 factoriesListener, commitNot, idProvider);
128 NetconfServerDispatcher.ServerSslChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerSslChannelInitializer(
129 sslC, serverNegotiatorFactory, listenerFactory);
130 return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
134 public void tearDown() throws Exception {
136 nettyThreadgroup.shutdownGracefully();
139 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
140 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
141 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
142 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
143 this.startExi = XmlFileLoader
144 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
145 this.stopExi = XmlFileLoader
146 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
147 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
150 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
151 final Collection<InputStream> yangDependencies = getBasicYangs();
152 return new HardcodedYangStoreService(yangDependencies);
155 static Collection<InputStream> getBasicYangs() throws IOException {
156 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
157 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang",
158 "/META-INF/yang/ietf-inet-types.yang");
159 final Collection<InputStream> yangDependencies = new ArrayList<>();
160 for (String path : paths) {
161 final InputStream is = checkNotNull(NetconfITTest.class.getResourceAsStream(path), path + " not found");
162 yangDependencies.add(is);
164 return yangDependencies;
167 protected List<ModuleFactory> getModuleFactories() {
168 return getModuleFactoriesS();
170 static List<ModuleFactory> getModuleFactoriesS() {
171 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
172 new NetconfTestImplModuleFactory());
176 public void testNetconfClientDemonstration() throws Exception {
177 try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
179 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
180 long sessionId = netconfClient.getSessionId();
182 // NetconfMessage can be created :
183 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
185 NetconfMessage response = netconfClient.sendMessage(getConfig);
186 response.getDocument();
191 public void testTwoSessions() throws Exception {
192 try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 4000, clientDispatcher)) {
193 try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 4000, clientDispatcher)) {
198 @Test(timeout = 10000)
199 public void testPersister() throws Exception {
200 Persister persister = mock(Persister.class);
201 doReturn("mockPersister").when(persister).toString();
202 doReturn(Optional.absent()).when(persister).loadLastConfig();
203 ConfigPersisterNotificationHandler h = new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer());
209 public void waitingTest() throws Exception {
210 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
211 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
212 transaction.commit();
213 Thread.currentThread().suspend();
217 public void rpcReplyContainsAllAttributesTest() throws Exception {
218 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
219 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
220 + "<get/>" + "</rpc>";
221 final Document doc = XmlUtil.readXmlToDocument(rpc);
222 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
223 assertNotNull(message);
224 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
225 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
227 assertSameAttributes(expectedAttributes, returnedAttributes);
231 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
232 assertNotNull("Expecting 4 attributes", returnedAttributes);
233 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
235 for (int i = 0; i < expectedAttributes.getLength(); i++) {
236 final Node expAttr = expectedAttributes.item(i);
237 final Node attr = returnedAttributes.item(i);
238 assertEquals(expAttr.getNodeName(), attr.getNodeName());
239 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
240 assertEquals(expAttr.getTextContent(), attr.getTextContent());
245 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
246 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
247 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
248 + "<commit/>" + "</rpc>";
249 final Document doc = XmlUtil.readXmlToDocument(rpc);
250 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
251 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
252 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
254 assertSameAttributes(expectedAttributes, returnedAttributes);
259 public void rpcOutputContainsCorrectNamespace() throws Exception {
260 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
261 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
262 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
263 NetconfTestImplModuleMXBean proxy = configRegistryClient
264 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
265 proxy.setTestingDep(dep);
266 registerRuntimeBean();
268 transaction.commit();
270 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
271 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
273 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
277 + "<context-instance>/data/modules/module[name='impl-netconf']/instance[name='instance']</context-instance>"
278 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
279 final Document doc = XmlUtil.readXmlToDocument(rpc);
280 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
282 final Element rpcReply = message.getDocument().getDocumentElement();
283 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
284 assertEquals("result", resultElement.getName());
286 final String namespace = resultElement.getNamespaceAttribute();
287 assertEquals(expectedNamespace, namespace);
291 private void registerRuntimeBean() {
292 BaseJMXRegistrator baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
293 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
294 .createRuntimeBeanRegistrator(new ModuleIdentifier(NetconfTestImplModuleFactory.NAME, "instance"));
295 NetconfTestImplRuntimeRegistrator reg = new NetconfTestImplRuntimeRegistrator(runtimeBeanRegistrator);
296 reg.register(new NetconfTestImplRuntimeMXBean() {
298 public Asdf getAsdf() {
303 public Long getCreatedSessions() {
308 public String noArg(String arg1) {
309 return "from no arg";
316 public void testStartExi() throws Exception {
317 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
320 Document rpcReply = netconfClient.sendMessage(this.startExi)
322 assertIsOK(rpcReply);
324 ExiParameters exiParams = new ExiParameters();
325 exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
327 netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
328 netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
330 rpcReply = netconfClient.sendMessage(this.editConfig)
332 assertIsOK(rpcReply);
334 rpcReply = netconfClient.sendMessage(this.stopExi)
336 assertIsOK(rpcReply);
342 public void testCloseSession() throws Exception {
343 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
346 Document rpcReply = netconfClient.sendMessage(this.editConfig)
348 assertIsOK(rpcReply);
350 rpcReply = netconfClient.sendMessage(this.closeSession)
353 assertIsOK(rpcReply);
358 public void testEditConfig() throws Exception {
359 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
360 // send edit_config.xml
361 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
362 assertIsOK(rpcReply);
367 public void testValidate() throws Exception {
368 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
370 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
371 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
374 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
376 assertIsOK(rpcReply);
380 private void assertIsOK(final Document rpcReply) {
381 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
382 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
387 // TODO can only send NetconfMessage - it must be valid xml
388 public void testClientHelloWithAuth() throws Exception {
389 final String fileName = "netconfMessages/client_hello_with_auth.xml";
390 // final InputStream resourceAsStream =
391 // AbstractListenerTest.class.getResourceAsStream(fileName);
392 // assertNotNull(resourceAsStream);
393 try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000, clientDispatcher)) {
394 // IOUtils.copy(resourceAsStream, netconfClient.getStream());
395 // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
396 // server should not write anything back
397 // assertEquals(null, netconfClient.readMessage());
398 assertGetConfigWorks(netconfClient);
402 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
403 return assertGetConfigWorks(netconfClient, this.getConfig);
406 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
407 throws InterruptedException {
408 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
409 assertNotNull(rpcReply);
410 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
411 return rpcReply.getDocument();
415 public void testGetConfig() throws Exception {
416 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
417 assertGetConfigWorks(netconfClient);
422 public void createYangTestBasedOnYuma() throws Exception {
423 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
424 Document rpcReply = netconfClient.sendMessage(
425 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
427 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
428 assertIsOK(rpcReply);
429 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
430 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
432 assertIsOK(rpcReply);
434 final ObjectName on = new ObjectName(
435 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
436 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
437 assertEquals(cfgBeans, Sets.newHashSet(on));
441 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
442 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
443 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
444 return netconfClient;