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.util.HashedWheelTimer;
16 import org.junit.After;
17 import org.junit.AfterClass;
18 import org.junit.Before;
19 import org.junit.Ignore;
20 import org.junit.Test;
21 import org.opendaylight.controller.config.api.ModuleIdentifier;
22 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
23 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
24 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
25 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
26 import org.opendaylight.controller.config.persist.api.Persister;
27 import org.opendaylight.controller.config.spi.ModuleFactory;
28 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
29 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
30 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
31 import org.opendaylight.controller.config.yang.test.impl.Asdf;
32 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
33 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
34 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
35 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeMXBean;
36 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeRegistrator;
37 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
38 import org.opendaylight.controller.netconf.api.NetconfMessage;
39 import org.opendaylight.controller.netconf.client.NetconfClient;
40 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
41 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
42 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
43 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
44 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
45 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
46 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
47 import org.opendaylight.controller.netconf.impl.mapping.ExiDecoderHandler;
48 import org.opendaylight.controller.netconf.impl.mapping.ExiEncoderHandler;
49 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
50 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
51 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
52 import org.opendaylight.controller.netconf.util.xml.ExiParameters;
53 import org.opendaylight.controller.netconf.util.xml.XmlElement;
54 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
55 import org.w3c.dom.Document;
56 import org.w3c.dom.Element;
57 import org.w3c.dom.NamedNodeMap;
58 import org.w3c.dom.Node;
59 import org.xml.sax.SAXException;
61 import javax.management.ObjectName;
62 import javax.net.ssl.SSLContext;
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.List;
73 import java.util.concurrent.TimeUnit;
75 import static junit.framework.Assert.assertEquals;
76 import static junit.framework.Assert.assertNotNull;
77 import static org.mockito.Mockito.doReturn;
78 import static org.mockito.Mockito.mock;
79 import static org.mockito.internal.util.Checks.checkNotNull;
81 public class NetconfITTest extends AbstractConfigTest {
83 // private static final Logger logger =
84 // LoggerFactory.getLogger(NetconfITTest.class);
87 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
89 private NetconfMessage getConfig, getConfigCandidate, editConfig,
90 closeSession, startExi, stopExi;
91 private DefaultCommitNotificationProducer commitNot;
92 private NetconfServerDispatcher dispatch;
94 private static NetconfClientDispatcher NETCONF_CLIENT_DISPATCHER = new NetconfClientDispatcher(Optional.<SSLContext>absent());
97 public void setUp() throws Exception {
98 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
99 new ModuleFactory[0])));
103 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
104 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
106 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
108 dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
109 ChannelFuture s = dispatch.createServer(tcpAddress);
113 private NetconfServerDispatcher createDispatcher(Optional<SSLContext> sslC,
114 NetconfOperationServiceFactoryListenerImpl factoriesListener) {
115 SessionIdProvider idProvider = new SessionIdProvider();
116 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
117 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
119 NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
120 factoriesListener, commitNot, idProvider);
122 return new NetconfServerDispatcher(sslC, serverNegotiatorFactory, listenerFactory);
126 public void tearDown() throws Exception {
132 public static void tearDownStatic() {
133 NETCONF_CLIENT_DISPATCHER.close();
136 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
137 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
138 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
139 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
140 this.startExi = XmlFileLoader
141 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
142 this.stopExi = XmlFileLoader
143 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
144 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
147 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
148 final Collection<InputStream> yangDependencies = getBasicYangs();
149 return new HardcodedYangStoreService(yangDependencies);
152 static Collection<InputStream> getBasicYangs() throws IOException {
153 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
154 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang",
155 "/META-INF/yang/ietf-inet-types.yang");
156 final Collection<InputStream> yangDependencies = new ArrayList<>();
157 for (String path : paths) {
158 final InputStream is = checkNotNull(NetconfITTest.class.getResourceAsStream(path), path + " not found");
159 yangDependencies.add(is);
161 return yangDependencies;
164 protected List<ModuleFactory> getModuleFactories() {
165 return getModuleFactoriesS();
167 static List<ModuleFactory> getModuleFactoriesS() {
168 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
169 new NetconfTestImplModuleFactory());
173 public void testNetconfClientDemonstration() throws Exception {
174 try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, NETCONF_CLIENT_DISPATCHER)) {
176 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
177 long sessionId = netconfClient.getSessionId();
179 // NetconfMessage can be created :
180 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
182 NetconfMessage response = netconfClient.sendMessage(getConfig);
183 response.getDocument();
188 public void testTwoSessions() throws Exception {
189 try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 4000, NETCONF_CLIENT_DISPATCHER)) {
190 try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 4000, NETCONF_CLIENT_DISPATCHER)) {
195 @Test(timeout = 10000)
196 public void testPersister() throws Exception {
197 Persister persister = mock(Persister.class);
198 doReturn("mockPersister").when(persister).toString();
199 doReturn(Optional.absent()).when(persister).loadLastConfig();
200 ConfigPersisterNotificationHandler h = new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer());
206 public void waitingTest() throws Exception {
207 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
208 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
209 transaction.commit();
210 Thread.currentThread().suspend();
214 public void rpcReplyContainsAllAttributesTest() throws Exception {
215 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
216 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
217 + "<get/>" + "</rpc>";
218 final Document doc = XmlUtil.readXmlToDocument(rpc);
219 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
220 assertNotNull(message);
221 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
222 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
224 assertSameAttributes(expectedAttributes, returnedAttributes);
228 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
229 assertNotNull("Expecting 4 attributes", returnedAttributes);
230 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
232 for (int i = 0; i < expectedAttributes.getLength(); i++) {
233 final Node expAttr = expectedAttributes.item(i);
234 final Node attr = returnedAttributes.item(i);
235 assertEquals(expAttr.getNodeName(), attr.getNodeName());
236 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
237 assertEquals(expAttr.getTextContent(), attr.getTextContent());
242 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
243 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
244 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
245 + "<commit/>" + "</rpc>";
246 final Document doc = XmlUtil.readXmlToDocument(rpc);
247 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
248 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
249 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
251 assertSameAttributes(expectedAttributes, returnedAttributes);
256 public void rpcOutputContainsCorrectNamespace() throws Exception {
257 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
258 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
259 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
260 NetconfTestImplModuleMXBean proxy = configRegistryClient
261 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
262 proxy.setTestingDep(dep);
263 registerRuntimeBean();
265 transaction.commit();
267 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
268 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
270 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
274 + "<context-instance>/data/modules/module[name='impl-netconf']/instance[name='instance']</context-instance>"
275 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
276 final Document doc = XmlUtil.readXmlToDocument(rpc);
277 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
279 final Element rpcReply = message.getDocument().getDocumentElement();
280 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
281 assertEquals("result", resultElement.getName());
283 final String namespace = resultElement.getNamespaceAttribute();
284 assertEquals(expectedNamespace, namespace);
288 private void registerRuntimeBean() {
289 BaseJMXRegistrator baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
290 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
291 .createRuntimeBeanRegistrator(new ModuleIdentifier(NetconfTestImplModuleFactory.NAME, "instance"));
292 NetconfTestImplRuntimeRegistrator reg = new NetconfTestImplRuntimeRegistrator(runtimeBeanRegistrator);
293 reg.register(new NetconfTestImplRuntimeMXBean() {
295 public Asdf getAsdf() {
300 public Long getCreatedSessions() {
305 public String noArg(String arg1) {
306 return "from no arg";
313 public void testStartExi() throws Exception {
314 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
317 Document rpcReply = netconfClient.sendMessage(this.startExi)
319 assertIsOK(rpcReply);
321 ExiParameters exiParams = new ExiParameters();
322 exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
324 netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
325 netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
327 rpcReply = netconfClient.sendMessage(this.editConfig)
329 assertIsOK(rpcReply);
331 rpcReply = netconfClient.sendMessage(this.stopExi)
333 assertIsOK(rpcReply);
339 public void testCloseSession() throws Exception {
340 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
343 Document rpcReply = netconfClient.sendMessage(this.editConfig)
345 assertIsOK(rpcReply);
347 rpcReply = netconfClient.sendMessage(this.closeSession)
350 assertIsOK(rpcReply);
355 public void testEditConfig() throws Exception {
356 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
357 // send edit_config.xml
358 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
359 assertIsOK(rpcReply);
364 public void testValidate() throws Exception {
365 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
367 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
368 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
371 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
373 assertIsOK(rpcReply);
377 private void assertIsOK(final Document rpcReply) {
378 assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
379 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
384 // TODO can only send NetconfMessage - it must be valid xml
385 public void testClientHelloWithAuth() throws Exception {
386 final String fileName = "netconfMessages/client_hello_with_auth.xml";
387 // final InputStream resourceAsStream =
388 // AbstractListenerTest.class.getResourceAsStream(fileName);
389 // assertNotNull(resourceAsStream);
390 try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000, NETCONF_CLIENT_DISPATCHER)) {
391 // IOUtils.copy(resourceAsStream, netconfClient.getStream());
392 // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
393 // server should not write anything back
394 // assertEquals(null, netconfClient.readMessage());
395 assertGetConfigWorks(netconfClient);
399 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
400 return assertGetConfigWorks(netconfClient, this.getConfig);
403 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
404 throws InterruptedException {
405 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
406 assertNotNull(rpcReply);
407 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
408 return rpcReply.getDocument();
412 public void testGetConfig() throws Exception {
413 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
414 assertGetConfigWorks(netconfClient);
419 public void createYangTestBasedOnYuma() throws Exception {
420 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
421 Document rpcReply = netconfClient.sendMessage(
422 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
424 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
425 assertIsOK(rpcReply);
426 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
427 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
429 assertIsOK(rpcReply);
431 final ObjectName on = new ObjectName(
432 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
433 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
434 assertEquals(cfgBeans, Sets.newHashSet(on));
438 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
439 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, NETCONF_CLIENT_DISPATCHER);
440 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
441 return netconfClient;