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.*;
31 import org.opendaylight.controller.netconf.api.NetconfMessage;
32 import org.opendaylight.controller.netconf.client.NetconfClient;
33 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
34 import org.opendaylight.controller.netconf.impl.*;
35 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
36 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
37 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
38 import org.opendaylight.controller.netconf.util.xml.XmlElement;
39 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
40 import org.opendaylight.protocol.util.SSLUtil;
41 import org.w3c.dom.Document;
42 import org.w3c.dom.Element;
43 import org.w3c.dom.NamedNodeMap;
44 import org.w3c.dom.Node;
45 import org.xml.sax.SAXException;
47 import javax.management.ObjectName;
48 import javax.net.ssl.KeyManagerFactory;
49 import javax.net.ssl.SSLContext;
50 import javax.xml.parsers.ParserConfigurationException;
51 import java.io.IOException;
52 import java.io.InputStream;
53 import java.lang.management.ManagementFactory;
54 import java.net.InetSocketAddress;
55 import java.security.KeyManagementException;
56 import java.security.KeyStoreException;
57 import java.security.NoSuchAlgorithmException;
58 import java.security.UnrecoverableKeyException;
59 import java.security.cert.CertificateException;
61 import java.util.concurrent.TimeUnit;
63 import static junit.framework.Assert.assertEquals;
64 import static junit.framework.Assert.assertNotNull;
65 import static org.mockito.Mockito.doReturn;
66 import static org.mockito.Mockito.mock;
67 import static org.mockito.internal.util.Checks.checkNotNull;
69 public class NetconfITTest extends AbstractConfigTest {
71 // private static final Logger logger =
72 // LoggerFactory.getLogger(NetconfITTest.class);
74 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
75 private static final InetSocketAddress tlsAddress = new InetSocketAddress("127.0.0.1", 12024);
77 private NetconfMessage getConfig, getConfigCandidate, editConfig, closeSession;
78 private DefaultCommitNotificationProducer commitNot;
79 private NetconfServerDispatcher dispatch, dispatchS;
82 public void setUp() throws Exception {
83 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
84 new ModuleFactory[0])));
88 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
89 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
91 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
93 dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
94 ChannelFuture s = dispatch.createServer(tcpAddress);
97 dispatchS = createDispatcher(Optional.of(getSslContext()), factoriesListener);
98 s = dispatchS.createServer(tlsAddress);
102 private NetconfServerDispatcher createDispatcher(Optional<SSLContext> sslC,
103 NetconfOperationServiceFactoryListenerImpl factoriesListener) {
104 SessionIdProvider idProvider = new SessionIdProvider();
105 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
106 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
108 NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
109 factoriesListener, commitNot, idProvider);
111 return new NetconfServerDispatcher(sslC, serverNegotiatorFactory, listenerFactory);
115 public void tearDown() throws Exception {
121 private SSLContext getSslContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
122 IOException, UnrecoverableKeyException, KeyManagementException {
123 final InputStream keyStore = getClass().getResourceAsStream("/keystore.jks");
124 final InputStream trustStore = getClass().getResourceAsStream("/keystore.jks");
125 SSLContext sslContext = SSLUtil.initializeSecureContext("password", keyStore, trustStore, KeyManagerFactory.getDefaultAlgorithm());
131 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
132 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
133 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
134 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
135 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
138 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
139 final Collection<InputStream> yangDependencies = getBasicYangs();
140 return new HardcodedYangStoreService(yangDependencies);
143 private Collection<InputStream> getBasicYangs() throws IOException {
144 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
145 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang",
146 "/META-INF/yang/ietf-inet-types.yang");
147 final Collection<InputStream> yangDependencies = new ArrayList<>();
148 for (String path : paths) {
149 final InputStream is = checkNotNull(getClass().getResourceAsStream(path), path + " not found");
150 yangDependencies.add(is);
152 return yangDependencies;
155 protected List<ModuleFactory> getModuleFactories() {
156 return getModuleFactoriesS();
158 static List<ModuleFactory> getModuleFactoriesS() {
159 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
160 new NetconfTestImplModuleFactory());
164 public void testNetconfClientDemonstration() throws Exception {
165 try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000)) {
167 Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
168 long sessionId = netconfClient.getSessionId();
170 // NetconfMessage can be created :
171 // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
173 NetconfMessage response = netconfClient.sendMessage(getConfig);
174 response.getDocument();
179 public void testTwoSessions() throws Exception {
180 try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 4000)) {
181 try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 4000)) {
186 @Test(timeout = 10000)
187 public void testPersister() throws Exception {
188 Persister persister = mock(Persister.class);
189 doReturn("mockPersister").when(persister).toString();
190 doReturn(Optional.absent()).when(persister).loadLastConfig();
191 ConfigPersisterNotificationHandler h = new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer());
196 public void testSecure() throws Exception {
197 try (NetconfClient netconfClient = new NetconfClient("1", tlsAddress, 4000, Optional.of(getSslContext()))) {
204 public void waitingTest() throws Exception {
205 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
206 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
207 transaction.commit();
208 Thread.currentThread().suspend();
212 public void rpcReplyContainsAllAttributesTest() throws Exception {
213 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
214 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
215 + "<get/>" + "</rpc>";
216 final Document doc = XmlUtil.readXmlToDocument(rpc);
217 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
218 assertNotNull(message);
219 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
220 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
222 assertSameAttributes(expectedAttributes, returnedAttributes);
226 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
227 assertNotNull("Expecting 4 attributes", returnedAttributes);
228 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
230 for (int i = 0; i < expectedAttributes.getLength(); i++) {
231 final Node expAttr = expectedAttributes.item(i);
232 final Node attr = returnedAttributes.item(i);
233 assertEquals(expAttr.getNodeName(), attr.getNodeName());
234 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
235 assertEquals(expAttr.getTextContent(), attr.getTextContent());
240 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
241 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
242 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
243 + "<commit/>" + "</rpc>";
244 final Document doc = XmlUtil.readXmlToDocument(rpc);
245 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
246 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
247 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
249 assertSameAttributes(expectedAttributes, returnedAttributes);
254 public void rpcOutputContainsCorrectNamespace() throws Exception {
255 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
256 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
257 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
258 NetconfTestImplModuleMXBean proxy = configRegistryClient
259 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
260 proxy.setTestingDep(dep);
261 registerRuntimeBean();
263 transaction.commit();
265 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
266 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
268 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
272 + "<context-instance>/data/modules/module[name='impl-netconf']/instance[name='instance']</context-instance>"
273 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
274 final Document doc = XmlUtil.readXmlToDocument(rpc);
275 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
277 final Element rpcReply = message.getDocument().getDocumentElement();
278 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
279 assertEquals("result", resultElement.getName());
280 final String namespace = resultElement.getNamespaceAttribute();
281 assertEquals(expectedNamespace, namespace);
285 private void registerRuntimeBean() {
286 BaseJMXRegistrator baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
287 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
288 .createRuntimeBeanRegistrator(new ModuleIdentifier(NetconfTestImplModuleFactory.NAME, "instance"));
289 NetconfTestImplRuntimeRegistrator reg = new NetconfTestImplRuntimeRegistrator(runtimeBeanRegistrator);
290 reg.register(new NetconfTestImplRuntimeMXBean() {
292 public Asdf getAsdf() {
297 public Long getCreatedSessions() {
302 public String noArg(String arg1) {
303 return "from no arg";
309 public void testCloseSession() throws Exception {
310 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
313 Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
314 assertIsOK(rpcReply);
316 rpcReply = netconfClient.sendMessage(this.closeSession).getDocument();
318 assertIsOK(rpcReply);
323 public void testEditConfig() throws Exception {
324 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
325 // send edit_config.xml
326 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
327 assertIsOK(rpcReply);
332 public void testValidate() throws Exception {
333 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
335 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
336 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
339 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
341 assertIsOK(rpcReply);
345 private void assertIsOK(final Document rpcReply) {
346 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
347 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
352 // TODO can only send NetconfMessage - it must be valid xml
353 public void testClientHelloWithAuth() throws Exception {
354 final String fileName = "netconfMessages/client_hello_with_auth.xml";
355 // final InputStream resourceAsStream =
356 // AbstractListenerTest.class.getResourceAsStream(fileName);
357 // assertNotNull(resourceAsStream);
358 try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000)) {
359 // IOUtils.copy(resourceAsStream, netconfClient.getStream());
360 // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
361 // server should not write anything back
362 // assertEquals(null, netconfClient.readMessage());
363 assertGetConfigWorks(netconfClient);
367 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
368 return assertGetConfigWorks(netconfClient, this.getConfig);
371 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
372 throws InterruptedException {
373 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
374 assertNotNull(rpcReply);
375 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
376 return rpcReply.getDocument();
380 public void testGetConfig() throws Exception {
381 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
382 assertGetConfigWorks(netconfClient);
387 public void createYangTestBasedOnYuma() throws Exception {
388 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
389 Document rpcReply = netconfClient.sendMessage(
390 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
392 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
393 assertIsOK(rpcReply);
394 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
395 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
397 assertIsOK(rpcReply);
399 final ObjectName on = new ObjectName(
400 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
401 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
402 assertEquals(cfgBeans, Sets.newHashSet(on));
406 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
407 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000);
409 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
411 return netconfClient;