bump netty to version 4.0.10.Final
[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 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;
18
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;
32 import java.util.Set;
33 import java.util.concurrent.TimeUnit;
34
35 import javax.management.ObjectName;
36 import javax.net.ssl.KeyManagerFactory;
37 import javax.net.ssl.SSLContext;
38 import javax.xml.parsers.ParserConfigurationException;
39
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;
80
81 import com.google.common.base.Optional;
82 import com.google.common.collect.Lists;
83 import com.google.common.collect.Sets;
84
85 public class NetconfITTest extends AbstractConfigTest {
86
87     // private static final Logger logger =
88     // LoggerFactory.getLogger(NetconfITTest.class);
89     //
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);
92
93     private NetconfMessage getConfig, getConfigCandidate, editConfig, closeSession;
94     private DefaultCommitNotificationProducer commitNot;
95     private NetconfServerDispatcher dispatch, dispatchS;
96
97     @Before
98     public void setUp() throws Exception {
99         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
100                 new ModuleFactory[0])));
101
102         loadMessages();
103
104         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
105         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
106
107         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
108
109         dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
110         ChannelFuture s = dispatch.createServer(tcpAddress);
111         s.await();
112
113         dispatchS = createDispatcher(Optional.of(getSslContext()), factoriesListener);
114         s = dispatchS.createServer(tlsAddress);
115         s.await();
116     }
117
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);
123
124         NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
125                 factoriesListener, commitNot, idProvider);
126
127         return new NetconfServerDispatcher(sslC, serverNegotiatorFactory, listenerFactory);
128     }
129
130     @After
131     public void tearDown() throws Exception {
132         commitNot.close();
133         dispatch.close();
134         dispatchS.close();
135     }
136
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());
142         keyStore.close();
143         trustStore.close();
144         return sslContext;
145     }
146
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");
152     }
153
154     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
155         final Collection<InputStream> yangDependencies = getBasicYangs();
156         return new HardcodedYangStoreService(yangDependencies);
157     }
158
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);
167         }
168         return yangDependencies;
169     }
170
171     protected List<ModuleFactory> getModuleFactories() {
172         return getModuleFactoriesS();
173     }
174     static List<ModuleFactory> getModuleFactoriesS() {
175         return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
176                 new NetconfTestImplModuleFactory());
177     }
178
179     @Test
180     public void testTwoSessions() throws Exception {
181         try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 4000)) {
182             try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 4000)) {
183             }
184         }
185     }
186
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());
193         h.init();
194     }
195
196     @Test
197     public void testSecure() throws Exception {
198         try (NetconfClient netconfClient = new NetconfClient("1", tlsAddress, 4000, Optional.of(getSslContext()))) {
199
200         }
201     }
202
203     @Ignore
204     @Test
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();
210     }
211
212     @Test
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();
222
223             assertSameAttributes(expectedAttributes, returnedAttributes);
224         }
225     }
226
227     private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
228         assertNotNull("Expecting 4 attributes", returnedAttributes);
229         assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
230
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());
237         }
238     }
239
240     @Test
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();
249
250             assertSameAttributes(expectedAttributes, returnedAttributes);
251         }
252     }
253
254     @Test
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();
263
264         transaction.commit();
265
266         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
267             final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
268
269             final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
270                     + "<no-arg xmlns=\""
271                     + expectedNamespace
272                     + "\">    "
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));
277
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);
283         }
284     }
285
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() {
292             @Override
293             public Asdf getAsdf() {
294                 return null;
295             }
296
297             @Override
298             public Long getCreatedSessions() {
299                 return null;
300             }
301
302             @Override
303             public String noArg(String arg1) {
304                 return "from no arg";
305             }
306         });
307     }
308
309     @Test
310     public void testCloseSession() throws Exception {
311         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
312
313             // edit config
314             Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
315             assertIsOK(rpcReply);
316
317             rpcReply = netconfClient.sendMessage(this.closeSession).getDocument();
318
319             assertIsOK(rpcReply);
320         }
321     }
322
323     @Test
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);
329         }
330     }
331
332     @Test
333     public void testValidate() throws Exception {
334         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
335             // begin transaction
336             Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
337             assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
338
339             // operations empty
340             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
341                     .getDocument();
342             assertIsOK(rpcReply);
343         }
344     }
345
346     private void assertIsOK(final Document rpcReply) {
347         assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
348         assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
349     }
350
351     @Ignore
352     @Test
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);
365         }
366     }
367
368     private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
369         return assertGetConfigWorks(netconfClient, this.getConfig);
370     }
371
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();
378     }
379
380     @Test
381     public void testGetConfig() throws Exception {
382         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
383             assertGetConfigWorks(netconfClient);
384         }
385     }
386
387     @Test
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"))
392                     .getDocument();
393             assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
394             assertIsOK(rpcReply);
395             assertGetConfigWorks(netconfClient, this.getConfigCandidate);
396             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
397                     .getDocument();
398             assertIsOK(rpcReply);
399
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));
404         }
405     }
406
407     private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
408         final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000);
409
410         assertEquals(expected, Long.toString(netconfClient.getSessionId()));
411
412         return netconfClient;
413     }
414
415 }