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.Before;
18 import org.junit.Ignore;
19 import org.junit.Test;
20 import org.opendaylight.controller.config.api.ModuleIdentifier;
21 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
22 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
23 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
24 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
25 import org.opendaylight.controller.config.persist.api.Persister;
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.Asdf;
31 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
32 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
33 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
34 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeMXBean;
35 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeRegistrator;
36 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
37 import org.opendaylight.controller.netconf.api.NetconfMessage;
38 import org.opendaylight.controller.netconf.client.NetconfClient;
39 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
40 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
41 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
42 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
43 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
44 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
45 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
46 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
47 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
48 import org.opendaylight.controller.netconf.util.xml.XmlElement;
49 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
50 import org.opendaylight.protocol.util.SSLUtil;
51 import org.w3c.dom.Document;
52 import org.w3c.dom.Element;
53 import org.w3c.dom.NamedNodeMap;
54 import org.w3c.dom.Node;
55 import org.xml.sax.SAXException;
57 import javax.management.ObjectName;
58 import javax.net.ssl.KeyManagerFactory;
59 import javax.net.ssl.SSLContext;
60 import javax.xml.parsers.ParserConfigurationException;
61 import java.io.IOException;
62 import java.io.InputStream;
63 import java.lang.management.ManagementFactory;
64 import java.net.InetSocketAddress;
65 import java.security.KeyManagementException;
66 import java.security.KeyStoreException;
67 import java.security.NoSuchAlgorithmException;
68 import java.security.UnrecoverableKeyException;
69 import java.security.cert.CertificateException;
70 import java.util.ArrayList;
71 import java.util.Arrays;
72 import java.util.Collection;
73 import java.util.List;
75 import java.util.concurrent.TimeUnit;
77 import static junit.framework.Assert.assertEquals;
78 import static junit.framework.Assert.assertNotNull;
79 import static org.mockito.Mockito.doReturn;
80 import static org.mockito.Mockito.mock;
81 import static org.mockito.internal.util.Checks.checkNotNull;
83 public class NetconfITTest extends AbstractConfigTest {
85 // private static final Logger logger =
86 // LoggerFactory.getLogger(NetconfITTest.class);
88 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
89 private static final InetSocketAddress tlsAddress = new InetSocketAddress("127.0.0.1", 12024);
91 private NetconfMessage getConfig, getConfigCandidate, editConfig, closeSession;
92 private DefaultCommitNotificationProducer commitNot;
93 private NetconfServerDispatcher dispatch, dispatchS;
96 public void setUp() throws Exception {
97 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
98 new ModuleFactory[0])));
102 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
103 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
105 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
107 dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
108 ChannelFuture s = dispatch.createServer(tcpAddress);
111 dispatchS = createDispatcher(Optional.of(getSslContext()), factoriesListener);
112 s = dispatchS.createServer(tlsAddress);
116 private NetconfServerDispatcher createDispatcher(Optional<SSLContext> sslC,
117 NetconfOperationServiceFactoryListenerImpl factoriesListener) {
118 SessionIdProvider idProvider = new SessionIdProvider();
119 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
120 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
122 NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
123 factoriesListener, commitNot, idProvider);
125 return new NetconfServerDispatcher(sslC, serverNegotiatorFactory, listenerFactory);
129 public void tearDown() throws Exception {
135 private SSLContext getSslContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
136 IOException, UnrecoverableKeyException, KeyManagementException {
137 final InputStream keyStore = getClass().getResourceAsStream("/keystore.jks");
138 final InputStream trustStore = getClass().getResourceAsStream("/keystore.jks");
139 SSLContext sslContext = SSLUtil.initializeSecureContext("password", keyStore, trustStore, KeyManagerFactory.getDefaultAlgorithm());
145 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
146 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
147 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
148 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
149 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
152 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
153 final Collection<InputStream> yangDependencies = getBasicYangs();
154 return new HardcodedYangStoreService(yangDependencies);
157 private Collection<InputStream> getBasicYangs() throws IOException {
158 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
159 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang",
160 "/META-INF/yang/ietf-inet-types.yang");
161 final Collection<InputStream> yangDependencies = new ArrayList<>();
162 for (String path : paths) {
163 final InputStream is = checkNotNull(getClass().getResourceAsStream(path), path + " not found");
164 yangDependencies.add(is);
166 return yangDependencies;
169 protected List<ModuleFactory> getModuleFactories() {
170 return getModuleFactoriesS();
172 static List<ModuleFactory> getModuleFactoriesS() {
173 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
174 new NetconfTestImplModuleFactory());
178 public void testNetconfClientDemonstration() throws Exception {
179 try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000)) {
181 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
182 long sessionId = netconfClient.getSessionId();
184 // NetconfMessage can be created :
185 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
187 NetconfMessage response = netconfClient.sendMessage(getConfig);
188 response.getDocument();
193 public void testTwoSessions() throws Exception {
194 try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 4000)) {
195 try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 4000)) {
200 @Test(timeout = 10000)
201 public void testPersister() throws Exception {
202 Persister persister = mock(Persister.class);
203 doReturn("mockPersister").when(persister).toString();
204 doReturn(Optional.absent()).when(persister).loadLastConfig();
205 ConfigPersisterNotificationHandler h = new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer());
210 public void testSecure() throws Exception {
211 try (NetconfClient netconfClient = new NetconfClient("1", tlsAddress, 4000, Optional.of(getSslContext()))) {
218 public void waitingTest() throws Exception {
219 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
220 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
221 transaction.commit();
222 Thread.currentThread().suspend();
226 public void rpcReplyContainsAllAttributesTest() throws Exception {
227 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
228 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
229 + "<get/>" + "</rpc>";
230 final Document doc = XmlUtil.readXmlToDocument(rpc);
231 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
232 assertNotNull(message);
233 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
234 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
236 assertSameAttributes(expectedAttributes, returnedAttributes);
240 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
241 assertNotNull("Expecting 4 attributes", returnedAttributes);
242 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
244 for (int i = 0; i < expectedAttributes.getLength(); i++) {
245 final Node expAttr = expectedAttributes.item(i);
246 final Node attr = returnedAttributes.item(i);
247 assertEquals(expAttr.getNodeName(), attr.getNodeName());
248 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
249 assertEquals(expAttr.getTextContent(), attr.getTextContent());
254 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
255 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
256 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
257 + "<commit/>" + "</rpc>";
258 final Document doc = XmlUtil.readXmlToDocument(rpc);
259 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
260 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
261 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
263 assertSameAttributes(expectedAttributes, returnedAttributes);
268 public void rpcOutputContainsCorrectNamespace() throws Exception {
269 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
270 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
271 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
272 NetconfTestImplModuleMXBean proxy = configRegistryClient
273 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
274 proxy.setTestingDep(dep);
275 registerRuntimeBean();
277 transaction.commit();
279 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
280 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
282 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
286 + "<context-instance>/data/modules/module[name='impl-netconf']/instance[name='instance']</context-instance>"
287 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
288 final Document doc = XmlUtil.readXmlToDocument(rpc);
289 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
291 final Element rpcReply = message.getDocument().getDocumentElement();
292 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
293 assertEquals("result", resultElement.getName());
294 final String namespace = resultElement.getNamespaceAttribute();
295 assertEquals(expectedNamespace, namespace);
299 private void registerRuntimeBean() {
300 BaseJMXRegistrator baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
301 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
302 .createRuntimeBeanRegistrator(new ModuleIdentifier(NetconfTestImplModuleFactory.NAME, "instance"));
303 NetconfTestImplRuntimeRegistrator reg = new NetconfTestImplRuntimeRegistrator(runtimeBeanRegistrator);
304 reg.register(new NetconfTestImplRuntimeMXBean() {
306 public Asdf getAsdf() {
311 public Long getCreatedSessions() {
316 public String noArg(String arg1) {
317 return "from no arg";
323 public void testCloseSession() throws Exception {
324 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
327 Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
328 assertIsOK(rpcReply);
330 rpcReply = netconfClient.sendMessage(this.closeSession).getDocument();
332 assertIsOK(rpcReply);
337 public void testEditConfig() throws Exception {
338 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
339 // send edit_config.xml
340 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
341 assertIsOK(rpcReply);
346 public void testValidate() throws Exception {
347 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
349 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
350 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
353 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
355 assertIsOK(rpcReply);
359 private void assertIsOK(final Document rpcReply) {
360 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
361 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
366 // TODO can only send NetconfMessage - it must be valid xml
367 public void testClientHelloWithAuth() throws Exception {
368 final String fileName = "netconfMessages/client_hello_with_auth.xml";
369 // final InputStream resourceAsStream =
370 // AbstractListenerTest.class.getResourceAsStream(fileName);
371 // assertNotNull(resourceAsStream);
372 try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000)) {
373 // IOUtils.copy(resourceAsStream, netconfClient.getStream());
374 // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
375 // server should not write anything back
376 // assertEquals(null, netconfClient.readMessage());
377 assertGetConfigWorks(netconfClient);
381 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
382 return assertGetConfigWorks(netconfClient, this.getConfig);
385 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
386 throws InterruptedException {
387 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
388 assertNotNull(rpcReply);
389 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
390 return rpcReply.getDocument();
394 public void testGetConfig() throws Exception {
395 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
396 assertGetConfigWorks(netconfClient);
401 public void createYangTestBasedOnYuma() throws Exception {
402 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
403 Document rpcReply = netconfClient.sendMessage(
404 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
406 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
407 assertIsOK(rpcReply);
408 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
409 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
411 assertIsOK(rpcReply);
413 final ObjectName on = new ObjectName(
414 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
415 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
416 assertEquals(cfgBeans, Sets.newHashSet(on));
420 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
421 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000);
423 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
425 return netconfClient;