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 static junit.framework.Assert.assertEquals;
12 import static junit.framework.Assert.assertNotNull;
13 import static org.mockito.Mockito.doReturn;
14 import static org.mockito.Mockito.mock;
15 import static org.mockito.internal.util.Checks.checkNotNull;
16 import io.netty.channel.ChannelFuture;
17 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.security.KeyManagementException;
24 import java.security.KeyStoreException;
25 import java.security.NoSuchAlgorithmException;
26 import java.security.UnrecoverableKeyException;
27 import java.security.cert.CertificateException;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.List;
33 import java.util.concurrent.TimeUnit;
35 import javax.management.ObjectName;
36 import javax.net.ssl.KeyManagerFactory;
37 import javax.net.ssl.SSLContext;
38 import javax.xml.parsers.ParserConfigurationException;
40 import org.junit.After;
41 import org.junit.Before;
42 import org.junit.Ignore;
43 import org.junit.Test;
44 import org.opendaylight.controller.config.api.ModuleIdentifier;
45 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
46 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
47 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
48 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
49 import org.opendaylight.controller.config.persist.api.Persister;
50 import org.opendaylight.controller.config.spi.ModuleFactory;
51 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
52 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
53 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
54 import org.opendaylight.controller.config.yang.test.impl.Asdf;
55 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
56 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
57 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
58 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeMXBean;
59 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeRegistrator;
60 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
61 import org.opendaylight.controller.netconf.api.NetconfMessage;
62 import org.opendaylight.controller.netconf.client.NetconfClient;
63 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
64 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
65 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
66 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
67 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
68 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
69 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
70 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
71 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
72 import org.opendaylight.controller.netconf.util.xml.XmlElement;
73 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
74 import org.opendaylight.protocol.util.SSLUtil;
75 import org.w3c.dom.Document;
76 import org.w3c.dom.Element;
77 import org.w3c.dom.NamedNodeMap;
78 import org.w3c.dom.Node;
79 import org.xml.sax.SAXException;
81 import com.google.common.base.Optional;
82 import com.google.common.collect.Lists;
83 import com.google.common.collect.Sets;
85 public class NetconfITTest extends AbstractConfigTest {
87 // private static final Logger logger =
88 // LoggerFactory.getLogger(NetconfITTest.class);
90 private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
91 private static final InetSocketAddress tlsAddress = new InetSocketAddress("127.0.0.1", 12024);
93 private NetconfMessage getConfig, getConfigCandidate, editConfig, closeSession;
94 private DefaultCommitNotificationProducer commitNot;
95 private NetconfServerDispatcher dispatch, dispatchS;
98 public void setUp() throws Exception {
99 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
100 new ModuleFactory[0])));
104 NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
105 factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
107 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
109 dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
110 ChannelFuture s = dispatch.createServer(tcpAddress);
113 dispatchS = createDispatcher(Optional.of(getSslContext()), factoriesListener);
114 s = dispatchS.createServer(tlsAddress);
118 private NetconfServerDispatcher createDispatcher(Optional<SSLContext> sslC,
119 NetconfOperationServiceFactoryListenerImpl factoriesListener) {
120 SessionIdProvider idProvider = new SessionIdProvider();
121 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
122 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
124 NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
125 factoriesListener, commitNot, idProvider);
127 return new NetconfServerDispatcher(sslC, serverNegotiatorFactory, listenerFactory);
131 public void tearDown() throws Exception {
137 private SSLContext getSslContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
138 IOException, UnrecoverableKeyException, KeyManagementException {
139 final InputStream keyStore = getClass().getResourceAsStream("/keystore.jks");
140 final InputStream trustStore = getClass().getResourceAsStream("/keystore.jks");
141 SSLContext sslContext = SSLUtil.initializeSecureContext("password", keyStore, trustStore, KeyManagerFactory.getDefaultAlgorithm());
147 private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
148 this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
149 this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
150 this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
151 this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
154 private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
155 final Collection<InputStream> yangDependencies = getBasicYangs();
156 return new HardcodedYangStoreService(yangDependencies);
159 private Collection<InputStream> getBasicYangs() throws IOException {
160 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
161 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang",
162 "/META-INF/yang/ietf-inet-types.yang");
163 final Collection<InputStream> yangDependencies = new ArrayList<>();
164 for (String path : paths) {
165 final InputStream is = checkNotNull(getClass().getResourceAsStream(path), path + " not found");
166 yangDependencies.add(is);
168 return yangDependencies;
171 protected List<ModuleFactory> getModuleFactories() {
172 return getModuleFactoriesS();
174 static List<ModuleFactory> getModuleFactoriesS() {
175 return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
176 new NetconfTestImplModuleFactory());
180 public void testTwoSessions() throws Exception {
181 try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 4000)) {
182 try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 4000)) {
187 @Test(timeout = 10000)
188 public void testPersister() throws Exception {
189 Persister persister = mock(Persister.class);
190 doReturn("mockPersister").when(persister).toString();
191 doReturn(Optional.absent()).when(persister).loadLastConfig();
192 ConfigPersisterNotificationHandler h = new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer());
197 public void testSecure() throws Exception {
198 try (NetconfClient netconfClient = new NetconfClient("1", tlsAddress, 4000, Optional.of(getSslContext()))) {
205 public void waitingTest() throws Exception {
206 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
207 transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
208 transaction.commit();
209 Thread.currentThread().suspend();
213 public void rpcReplyContainsAllAttributesTest() throws Exception {
214 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
215 final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
216 + "<get/>" + "</rpc>";
217 final Document doc = XmlUtil.readXmlToDocument(rpc);
218 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
219 assertNotNull(message);
220 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
221 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
223 assertSameAttributes(expectedAttributes, returnedAttributes);
227 private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
228 assertNotNull("Expecting 4 attributes", returnedAttributes);
229 assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
231 for (int i = 0; i < expectedAttributes.getLength(); i++) {
232 final Node expAttr = expectedAttributes.item(i);
233 final Node attr = returnedAttributes.item(i);
234 assertEquals(expAttr.getNodeName(), attr.getNodeName());
235 assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
236 assertEquals(expAttr.getTextContent(), attr.getTextContent());
241 public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
242 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
243 final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
244 + "<commit/>" + "</rpc>";
245 final Document doc = XmlUtil.readXmlToDocument(rpc);
246 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
247 final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
248 final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
250 assertSameAttributes(expectedAttributes, returnedAttributes);
255 public void rpcOutputContainsCorrectNamespace() throws Exception {
256 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
257 ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
258 ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
259 NetconfTestImplModuleMXBean proxy = configRegistryClient
260 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
261 proxy.setTestingDep(dep);
262 registerRuntimeBean();
264 transaction.commit();
266 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
267 final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
269 final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
273 + "<context-instance>/data/modules/module[name='impl-netconf']/instance[name='instance']</context-instance>"
274 + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
275 final Document doc = XmlUtil.readXmlToDocument(rpc);
276 final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
278 final Element rpcReply = message.getDocument().getDocumentElement();
279 final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
280 assertEquals("result", resultElement.getName());
281 final String namespace = resultElement.getNamespaceAttribute();
282 assertEquals(expectedNamespace, namespace);
286 private void registerRuntimeBean() {
287 BaseJMXRegistrator baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
288 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
289 .createRuntimeBeanRegistrator(new ModuleIdentifier(NetconfTestImplModuleFactory.NAME, "instance"));
290 NetconfTestImplRuntimeRegistrator reg = new NetconfTestImplRuntimeRegistrator(runtimeBeanRegistrator);
291 reg.register(new NetconfTestImplRuntimeMXBean() {
293 public Asdf getAsdf() {
298 public Long getCreatedSessions() {
303 public String noArg(String arg1) {
304 return "from no arg";
310 public void testCloseSession() throws Exception {
311 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
314 Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
315 assertIsOK(rpcReply);
317 rpcReply = netconfClient.sendMessage(this.closeSession).getDocument();
319 assertIsOK(rpcReply);
324 public void testEditConfig() throws Exception {
325 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
326 // send edit_config.xml
327 final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
328 assertIsOK(rpcReply);
333 public void testValidate() throws Exception {
334 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
336 Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
337 assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
340 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
342 assertIsOK(rpcReply);
346 private void assertIsOK(final Document rpcReply) {
347 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
348 assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
353 // TODO can only send NetconfMessage - it must be valid xml
354 public void testClientHelloWithAuth() throws Exception {
355 final String fileName = "netconfMessages/client_hello_with_auth.xml";
356 // final InputStream resourceAsStream =
357 // AbstractListenerTest.class.getResourceAsStream(fileName);
358 // assertNotNull(resourceAsStream);
359 try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000)) {
360 // IOUtils.copy(resourceAsStream, netconfClient.getStream());
361 // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
362 // server should not write anything back
363 // assertEquals(null, netconfClient.readMessage());
364 assertGetConfigWorks(netconfClient);
368 private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
369 return assertGetConfigWorks(netconfClient, this.getConfig);
372 private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
373 throws InterruptedException {
374 final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
375 assertNotNull(rpcReply);
376 assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
377 return rpcReply.getDocument();
381 public void testGetConfig() throws Exception {
382 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
383 assertGetConfigWorks(netconfClient);
388 public void createYangTestBasedOnYuma() throws Exception {
389 try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
390 Document rpcReply = netconfClient.sendMessage(
391 XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
393 assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
394 assertIsOK(rpcReply);
395 assertGetConfigWorks(netconfClient, this.getConfigCandidate);
396 rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
398 assertIsOK(rpcReply);
400 final ObjectName on = new ObjectName(
401 "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
402 Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
403 assertEquals(cfgBeans, Sets.newHashSet(on));
407 private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
408 final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000);
410 assertEquals(expected, Long.toString(netconfClient.getSessionId()));
412 return netconfClient;