Fix star import and enable checkstyle rule to prevent it.
[controller.git] / opendaylight / netconf / netconf-it / src / test / java / org / opendaylight / controller / netconf / it / NetconfITTest.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.netconf.it;
10
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;
56
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;
74 import java.util.Set;
75 import java.util.concurrent.TimeUnit;
76
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;
82
83 public class NetconfITTest extends AbstractConfigTest {
84
85     // private static final Logger logger =
86     // LoggerFactory.getLogger(NetconfITTest.class);
87     //
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);
90
91     private NetconfMessage getConfig, getConfigCandidate, editConfig, closeSession;
92     private DefaultCommitNotificationProducer commitNot;
93     private NetconfServerDispatcher dispatch, dispatchS;
94
95     @Before
96     public void setUp() throws Exception {
97         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
98                 new ModuleFactory[0])));
99
100         loadMessages();
101
102         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
103         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
104
105         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
106
107         dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
108         ChannelFuture s = dispatch.createServer(tcpAddress);
109         s.await();
110
111         dispatchS = createDispatcher(Optional.of(getSslContext()), factoriesListener);
112         s = dispatchS.createServer(tlsAddress);
113         s.await();
114     }
115
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);
121
122         NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
123                 factoriesListener, commitNot, idProvider);
124
125         return new NetconfServerDispatcher(sslC, serverNegotiatorFactory, listenerFactory);
126     }
127
128     @After
129     public void tearDown() throws Exception {
130         commitNot.close();
131         dispatch.close();
132         dispatchS.close();
133     }
134
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());
140         keyStore.close();
141         trustStore.close();
142         return sslContext;
143     }
144
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");
150     }
151
152     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
153         final Collection<InputStream> yangDependencies = getBasicYangs();
154         return new HardcodedYangStoreService(yangDependencies);
155     }
156
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);
165         }
166         return yangDependencies;
167     }
168
169     protected List<ModuleFactory> getModuleFactories() {
170         return getModuleFactoriesS();
171     }
172     static List<ModuleFactory> getModuleFactoriesS() {
173         return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
174                 new NetconfTestImplModuleFactory());
175     }
176
177     @Test
178     public void testNetconfClientDemonstration() throws Exception {
179         try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000)) {
180
181             Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
182             long sessionId = netconfClient.getSessionId();
183
184             // NetconfMessage can be created :
185             // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
186
187             NetconfMessage response = netconfClient.sendMessage(getConfig);
188             response.getDocument();
189         }
190     }
191
192     @Test
193     public void testTwoSessions() throws Exception {
194         try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 4000)) {
195             try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 4000)) {
196             }
197         }
198     }
199
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());
206         h.init();
207     }
208
209     @Test
210     public void testSecure() throws Exception {
211         try (NetconfClient netconfClient = new NetconfClient("1", tlsAddress, 4000, Optional.of(getSslContext()))) {
212
213         }
214     }
215
216     @Ignore
217     @Test
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();
223     }
224
225     @Test
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();
235
236             assertSameAttributes(expectedAttributes, returnedAttributes);
237         }
238     }
239
240     private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
241         assertNotNull("Expecting 4 attributes", returnedAttributes);
242         assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
243
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());
250         }
251     }
252
253     @Test
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();
262
263             assertSameAttributes(expectedAttributes, returnedAttributes);
264         }
265     }
266
267     @Test
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();
276
277         transaction.commit();
278
279         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
280             final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
281
282             final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
283                     + "<no-arg xmlns=\""
284                     + expectedNamespace
285                     + "\">    "
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));
290
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);
296         }
297     }
298
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() {
305             @Override
306             public Asdf getAsdf() {
307                 return null;
308             }
309
310             @Override
311             public Long getCreatedSessions() {
312                 return null;
313             }
314
315             @Override
316             public String noArg(String arg1) {
317                 return "from no arg";
318             }
319         });
320     }
321
322     @Test
323     public void testCloseSession() throws Exception {
324         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
325
326             // edit config
327             Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
328             assertIsOK(rpcReply);
329
330             rpcReply = netconfClient.sendMessage(this.closeSession).getDocument();
331
332             assertIsOK(rpcReply);
333         }
334     }
335
336     @Test
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);
342         }
343     }
344
345     @Test
346     public void testValidate() throws Exception {
347         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
348             // begin transaction
349             Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
350             assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
351
352             // operations empty
353             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
354                     .getDocument();
355             assertIsOK(rpcReply);
356         }
357     }
358
359     private void assertIsOK(final Document rpcReply) {
360         assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
361         assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
362     }
363
364     @Ignore
365     @Test
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);
378         }
379     }
380
381     private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
382         return assertGetConfigWorks(netconfClient, this.getConfig);
383     }
384
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();
391     }
392
393     @Test
394     public void testGetConfig() throws Exception {
395         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
396             assertGetConfigWorks(netconfClient);
397         }
398     }
399
400     @Test
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"))
405                     .getDocument();
406             assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
407             assertIsOK(rpcReply);
408             assertGetConfigWorks(netconfClient, this.getConfigCandidate);
409             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
410                     .getDocument();
411             assertIsOK(rpcReply);
412
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));
417         }
418     }
419
420     private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
421         final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000);
422
423         assertEquals(expected, Long.toString(netconfClient.getSessionId()));
424
425         return netconfClient;
426     }
427
428 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.