d7f96a876148299d5a09ab765de1e558fbf8cb8e
[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
175     static List<ModuleFactory> getModuleFactoriesS() {
176         return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
177                 new NetconfTestImplModuleFactory());
178     }
179
180     @Test
181     public void testTwoSessions() throws Exception {
182         try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 4000)) {
183             try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 4000)) {
184             }
185         }
186     }
187
188     @Test(timeout = 10000)
189     public void testPersister() throws Exception {
190         Persister persister = mock(Persister.class);
191         doReturn("mockPersister").when(persister).toString();
192         doReturn(Optional.absent()).when(persister).loadLastConfig();
193         ConfigPersisterNotificationHandler h = new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer());
194         h.init();
195     }
196
197     @Test
198     public void testSecure() throws Exception {
199         try (NetconfClient netconfClient = new NetconfClient("1", tlsAddress, 4000, Optional.of(getSslContext()))) {
200
201         }
202     }
203
204     @Ignore
205     @Test
206     public void waitingTest() throws Exception {
207         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
208         transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
209         transaction.commit();
210         Thread.currentThread().suspend();
211     }
212
213     @Test
214     public void rpcReplyContainsAllAttributesTest() throws Exception {
215         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
216             final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
217                     + "<get/>" + "</rpc>";
218             final Document doc = XmlUtil.readXmlToDocument(rpc);
219             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
220             assertNotNull(message);
221             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
222             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
223
224             assertSameAttributes(expectedAttributes, returnedAttributes);
225         }
226     }
227
228     private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
229         assertNotNull("Expecting 4 attributes", returnedAttributes);
230         assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
231
232         for (int i = 0; i < expectedAttributes.getLength(); i++) {
233             final Node expAttr = expectedAttributes.item(i);
234             final Node attr = returnedAttributes.item(i);
235             assertEquals(expAttr.getNodeName(), attr.getNodeName());
236             assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
237             assertEquals(expAttr.getTextContent(), attr.getTextContent());
238         }
239     }
240
241     @Test
242     public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
243         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
244             final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
245                     + "<commit/>" + "</rpc>";
246             final Document doc = XmlUtil.readXmlToDocument(rpc);
247             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
248             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
249             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
250
251             assertSameAttributes(expectedAttributes, returnedAttributes);
252         }
253     }
254
255     @Test
256     public void rpcOutputContainsCorrectNamespace() throws Exception {
257         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
258         ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
259         ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
260         NetconfTestImplModuleMXBean proxy = configRegistryClient
261                 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
262         proxy.setTestingDep(dep);
263         registerRuntimeBean();
264
265         transaction.commit();
266
267         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
268             final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
269
270             final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
271                     + "<no-arg xmlns=\""
272                     + expectedNamespace
273                     + "\">    "
274                     + "<context-instance>/data/modules/module[name='impl-netconf']/instance[name='instance']</context-instance>"
275                     + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
276             final Document doc = XmlUtil.readXmlToDocument(rpc);
277             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
278
279             final Element rpcReply = message.getDocument().getDocumentElement();
280             final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
281             assertEquals("result", resultElement.getName());
282             final String namespace = resultElement.getNamespaceAttribute();
283             assertEquals(expectedNamespace, namespace);
284         }
285     }
286
287     private void registerRuntimeBean() {
288         BaseJMXRegistrator baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
289         RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
290                 .createRuntimeBeanRegistrator(new ModuleIdentifier(NetconfTestImplModuleFactory.NAME, "instance"));
291         NetconfTestImplRuntimeRegistrator reg = new NetconfTestImplRuntimeRegistrator(runtimeBeanRegistrator);
292         reg.register(new NetconfTestImplRuntimeMXBean() {
293             @Override
294             public Asdf getAsdf() {
295                 return null;
296             }
297
298             @Override
299             public Long getCreatedSessions() {
300                 return null;
301             }
302
303             @Override
304             public String noArg(String arg1) {
305                 return "from no arg";
306             }
307         });
308     }
309
310     @Test
311     public void testCloseSession() throws Exception {
312         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
313
314             // edit config
315             Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
316             assertIsOK(rpcReply);
317
318             rpcReply = netconfClient.sendMessage(this.closeSession).getDocument();
319
320             assertIsOK(rpcReply);
321         }
322     }
323
324     @Test
325     public void testEditConfig() throws Exception {
326         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
327             // send edit_config.xml
328             final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
329             assertIsOK(rpcReply);
330         }
331     }
332
333     @Test
334     public void testValidate() throws Exception {
335         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
336             // begin transaction
337             Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
338             assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
339
340             // operations empty
341             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
342                     .getDocument();
343             assertIsOK(rpcReply);
344         }
345     }
346
347     private void assertIsOK(final Document rpcReply) {
348         assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
349         assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
350     }
351
352     @Ignore
353     @Test
354     // TODO can only send NetconfMessage - it must be valid xml
355     public void testClientHelloWithAuth() throws Exception {
356         final String fileName = "netconfMessages/client_hello_with_auth.xml";
357         // final InputStream resourceAsStream =
358         // AbstractListenerTest.class.getResourceAsStream(fileName);
359         // assertNotNull(resourceAsStream);
360         try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000)) {
361             // IOUtils.copy(resourceAsStream, netconfClient.getStream());
362             // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
363             // server should not write anything back
364             // assertEquals(null, netconfClient.readMessage());
365             assertGetConfigWorks(netconfClient);
366         }
367     }
368
369     private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
370         return assertGetConfigWorks(netconfClient, this.getConfig);
371     }
372
373     private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
374             throws InterruptedException {
375         final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
376         assertNotNull(rpcReply);
377         assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
378         return rpcReply.getDocument();
379     }
380
381     @Test
382     public void testGetConfig() throws Exception {
383         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
384             assertGetConfigWorks(netconfClient);
385         }
386     }
387
388     @Test
389     public void createYangTestBasedOnYuma() throws Exception {
390         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
391             Document rpcReply = netconfClient.sendMessage(
392                     XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
393                     .getDocument();
394             assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
395             assertIsOK(rpcReply);
396             assertGetConfigWorks(netconfClient, this.getConfigCandidate);
397             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
398                     .getDocument();
399             assertIsOK(rpcReply);
400
401             final ObjectName on = new ObjectName(
402                     "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
403             Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
404             assertEquals(cfgBeans, Sets.newHashSet(on));
405         }
406     }
407
408     private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
409         final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000);
410
411         assertEquals(expected, Long.toString(netconfClient.getSessionId()));
412
413         return netconfClient;
414     }
415
416 }