Merge "Bring some reliability in the eclipse and maven mixed builds"
[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.channel.EventLoopGroup;
16 import io.netty.channel.nio.NioEventLoopGroup;
17 import io.netty.util.HashedWheelTimer;
18 import org.junit.After;
19 import org.junit.Before;
20 import org.junit.Ignore;
21 import org.junit.Test;
22 import org.opendaylight.controller.config.api.ModuleIdentifier;
23 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
24 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
25 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
26 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
27 import org.opendaylight.controller.config.persist.api.Persister;
28 import org.opendaylight.controller.config.spi.ModuleFactory;
29 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
30 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
31 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
32 import org.opendaylight.controller.config.yang.test.impl.Asdf;
33 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
34 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
35 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
36 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeMXBean;
37 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeRegistrator;
38 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
39 import org.opendaylight.controller.netconf.api.NetconfMessage;
40 import org.opendaylight.controller.netconf.client.NetconfClient;
41 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
42 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
43 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
44 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
45 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListenerFactory;
46 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
47 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
48 import org.opendaylight.controller.netconf.impl.mapping.ExiDecoderHandler;
49 import org.opendaylight.controller.netconf.impl.mapping.ExiEncoderHandler;
50 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
51 import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
52 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
53 import org.opendaylight.controller.netconf.util.xml.ExiParameters;
54 import org.opendaylight.controller.netconf.util.xml.XmlElement;
55 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.w3c.dom.NamedNodeMap;
59 import org.w3c.dom.Node;
60 import org.xml.sax.SAXException;
61
62 import javax.management.ObjectName;
63 import javax.net.ssl.SSLContext;
64 import javax.xml.parsers.ParserConfigurationException;
65 import java.io.IOException;
66 import java.io.InputStream;
67 import java.lang.management.ManagementFactory;
68 import java.net.InetSocketAddress;
69 import java.util.ArrayList;
70 import java.util.Arrays;
71 import java.util.Collection;
72 import java.util.List;
73 import java.util.Set;
74 import java.util.concurrent.TimeUnit;
75
76 import static junit.framework.Assert.assertEquals;
77 import static junit.framework.Assert.assertNotNull;
78 import static org.mockito.Mockito.doReturn;
79 import static org.mockito.Mockito.mock;
80 import static org.mockito.internal.util.Checks.checkNotNull;
81
82 public class NetconfITTest extends AbstractConfigTest {
83
84     // private static final Logger logger =
85     // LoggerFactory.getLogger(NetconfITTest.class);
86     //
87
88     private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
89
90     private NetconfMessage getConfig, getConfigCandidate, editConfig,
91             closeSession, startExi, stopExi;
92     private DefaultCommitNotificationProducer commitNot;
93     private NetconfServerDispatcher dispatch;
94     private EventLoopGroup nettyThreadgroup;
95
96     private NetconfClientDispatcher clientDispatcher;
97
98     @Before
99     public void setUp() throws Exception {
100         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(getModuleFactories().toArray(
101                 new ModuleFactory[0])));
102
103         loadMessages();
104
105         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
106         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
107
108         nettyThreadgroup = new NioEventLoopGroup();
109
110         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
111
112         dispatch = createDispatcher(Optional.<SSLContext> absent(), factoriesListener);
113         ChannelFuture s = dispatch.createServer(tcpAddress);
114         s.await();
115
116         clientDispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
117     }
118
119     private NetconfServerDispatcher createDispatcher(Optional<SSLContext> sslC,
120             NetconfOperationServiceFactoryListenerImpl factoriesListener) {
121         SessionIdProvider idProvider = new SessionIdProvider();
122         NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
123                 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
124
125         NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
126                 factoriesListener, commitNot, idProvider);
127
128         NetconfServerDispatcher.ServerSslChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerSslChannelInitializer(
129                 sslC, serverNegotiatorFactory, listenerFactory);
130         return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
131     }
132
133     @After
134     public void tearDown() throws Exception {
135         commitNot.close();
136         nettyThreadgroup.shutdownGracefully();
137     }
138
139     private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
140         this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
141         this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
142         this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
143         this.startExi = XmlFileLoader
144                 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
145         this.stopExi = XmlFileLoader
146                 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
147         this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
148     }
149
150     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
151         final Collection<InputStream> yangDependencies = getBasicYangs();
152         return new HardcodedYangStoreService(yangDependencies);
153     }
154
155     static Collection<InputStream> getBasicYangs() throws IOException {
156         List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
157                 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang",
158                 "/META-INF/yang/ietf-inet-types.yang");
159         final Collection<InputStream> yangDependencies = new ArrayList<>();
160         for (String path : paths) {
161             final InputStream is = checkNotNull(NetconfITTest.class.getResourceAsStream(path), path + " not found");
162             yangDependencies.add(is);
163         }
164         return yangDependencies;
165     }
166
167     protected List<ModuleFactory> getModuleFactories() {
168         return getModuleFactoriesS();
169     }
170     static List<ModuleFactory> getModuleFactoriesS() {
171         return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
172                 new NetconfTestImplModuleFactory());
173     }
174
175     @Test
176     public void testNetconfClientDemonstration() throws Exception {
177         try (NetconfClient netconfClient = new NetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
178
179             Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
180             long sessionId = netconfClient.getSessionId();
181
182             // NetconfMessage can be created :
183             // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
184
185             NetconfMessage response = netconfClient.sendMessage(getConfig);
186             response.getDocument();
187         }
188     }
189
190     @Test
191     public void testTwoSessions() throws Exception {
192         try (NetconfClient netconfClient = new NetconfClient("1", tcpAddress, 4000, clientDispatcher))  {
193             try (NetconfClient netconfClient2 = new NetconfClient("2", tcpAddress, 4000, clientDispatcher))  {
194             }
195         }
196     }
197
198     @Test(timeout = 10000)
199     public void testPersister() throws Exception {
200         Persister persister = mock(Persister.class);
201         doReturn("mockPersister").when(persister).toString();
202         doReturn(Optional.absent()).when(persister).loadLastConfig();
203         ConfigPersisterNotificationHandler h = new ConfigPersisterNotificationHandler(persister, tcpAddress, ManagementFactory.getPlatformMBeanServer());
204         h.init();
205     }
206
207     @Ignore
208     @Test
209     public void waitingTest() throws Exception {
210         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
211         transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
212         transaction.commit();
213         Thread.currentThread().suspend();
214     }
215
216     @Test
217     public void rpcReplyContainsAllAttributesTest() throws Exception {
218         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
219             final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
220                     + "<get/>" + "</rpc>";
221             final Document doc = XmlUtil.readXmlToDocument(rpc);
222             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
223             assertNotNull(message);
224             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
225             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
226
227             assertSameAttributes(expectedAttributes, returnedAttributes);
228         }
229     }
230
231     private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
232         assertNotNull("Expecting 4 attributes", returnedAttributes);
233         assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
234
235         for (int i = 0; i < expectedAttributes.getLength(); i++) {
236             final Node expAttr = expectedAttributes.item(i);
237             final Node attr = returnedAttributes.item(i);
238             assertEquals(expAttr.getNodeName(), attr.getNodeName());
239             assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
240             assertEquals(expAttr.getTextContent(), attr.getTextContent());
241         }
242     }
243
244     @Test
245     public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
246         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
247             final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
248                     + "<commit/>" + "</rpc>";
249             final Document doc = XmlUtil.readXmlToDocument(rpc);
250             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
251             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
252             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
253
254             assertSameAttributes(expectedAttributes, returnedAttributes);
255         }
256     }
257
258     @Test
259     public void rpcOutputContainsCorrectNamespace() throws Exception {
260         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
261         ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
262         ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
263         NetconfTestImplModuleMXBean proxy = configRegistryClient
264                 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
265         proxy.setTestingDep(dep);
266         registerRuntimeBean();
267
268         transaction.commit();
269
270         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
271             final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
272
273             final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
274                     + "<no-arg xmlns=\""
275                     + expectedNamespace
276                     + "\">    "
277                     + "<context-instance>/data/modules/module[name='impl-netconf']/instance[name='instance']</context-instance>"
278                     + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
279             final Document doc = XmlUtil.readXmlToDocument(rpc);
280             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
281
282             final Element rpcReply = message.getDocument().getDocumentElement();
283             final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
284             assertEquals("result", resultElement.getName());
285
286             final String namespace = resultElement.getNamespaceAttribute();
287             assertEquals(expectedNamespace, namespace);
288         }
289     }
290
291     private void registerRuntimeBean() {
292         BaseJMXRegistrator baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
293         RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
294                 .createRuntimeBeanRegistrator(new ModuleIdentifier(NetconfTestImplModuleFactory.NAME, "instance"));
295         NetconfTestImplRuntimeRegistrator reg = new NetconfTestImplRuntimeRegistrator(runtimeBeanRegistrator);
296         reg.register(new NetconfTestImplRuntimeMXBean() {
297             @Override
298             public Asdf getAsdf() {
299                 return null;
300             }
301
302             @Override
303             public Long getCreatedSessions() {
304                 return null;
305             }
306
307             @Override
308             public String noArg(String arg1) {
309                 return "from no arg";
310             }
311         });
312     }
313
314     @Test
315 //    @Ignore
316     public void testStartExi() throws Exception {
317         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
318
319
320             Document rpcReply = netconfClient.sendMessage(this.startExi)
321                     .getDocument();
322             assertIsOK(rpcReply);
323
324             ExiParameters exiParams = new ExiParameters();
325             exiParams.setParametersFromXmlElement(XmlElement.fromDomDocument(this.startExi.getDocument()));
326
327             netconfClient.getClientSession().addExiDecoder(ExiDecoderHandler.HANDLER_NAME, new ExiDecoderHandler(exiParams));
328             netconfClient.getClientSession().addExiEncoder(ExiEncoderHandler.HANDLER_NAME, new ExiEncoderHandler(exiParams));
329
330             rpcReply = netconfClient.sendMessage(this.editConfig)
331                     .getDocument();
332             assertIsOK(rpcReply);
333
334             rpcReply = netconfClient.sendMessage(this.stopExi)
335                     .getDocument();
336             assertIsOK(rpcReply);
337
338         }
339     }
340
341     @Test
342     public void testCloseSession() throws Exception {
343         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
344
345             // edit config
346             Document rpcReply = netconfClient.sendMessage(this.editConfig)
347                     .getDocument();
348             assertIsOK(rpcReply);
349
350             rpcReply = netconfClient.sendMessage(this.closeSession)
351                     .getDocument();
352
353             assertIsOK(rpcReply);
354         }
355     }
356
357     @Test
358     public void testEditConfig() throws Exception {
359         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
360             // send edit_config.xml
361             final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
362             assertIsOK(rpcReply);
363         }
364     }
365
366     @Test
367     public void testValidate() throws Exception {
368         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
369             // begin transaction
370             Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
371             assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
372
373             // operations empty
374             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
375                     .getDocument();
376             assertIsOK(rpcReply);
377         }
378     }
379
380     private void assertIsOK(final Document rpcReply) {
381         assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
382         assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
383     }
384
385     @Ignore
386     @Test
387     // TODO can only send NetconfMessage - it must be valid xml
388     public void testClientHelloWithAuth() throws Exception {
389         final String fileName = "netconfMessages/client_hello_with_auth.xml";
390         // final InputStream resourceAsStream =
391         // AbstractListenerTest.class.getResourceAsStream(fileName);
392         // assertNotNull(resourceAsStream);
393         try (NetconfClient netconfClient = new NetconfClient("test", tcpAddress, 5000, clientDispatcher)) {
394             // IOUtils.copy(resourceAsStream, netconfClient.getStream());
395             // netconfClient.getOutputStream().write(NetconfMessageFactory.endOfMessage);
396             // server should not write anything back
397             // assertEquals(null, netconfClient.readMessage());
398             assertGetConfigWorks(netconfClient);
399         }
400     }
401
402     private Document assertGetConfigWorks(final NetconfClient netconfClient) throws InterruptedException {
403         return assertGetConfigWorks(netconfClient, this.getConfig);
404     }
405
406     private Document assertGetConfigWorks(final NetconfClient netconfClient, final NetconfMessage getConfigMessage)
407             throws InterruptedException {
408         final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
409         assertNotNull(rpcReply);
410         assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
411         return rpcReply.getDocument();
412     }
413
414     @Test
415     public void testGetConfig() throws Exception {
416         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
417             assertGetConfigWorks(netconfClient);
418         }
419     }
420
421     @Test
422     public void createYangTestBasedOnYuma() throws Exception {
423         try (NetconfClient netconfClient = createSession(tcpAddress, "1")) {
424             Document rpcReply = netconfClient.sendMessage(
425                     XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
426                     .getDocument();
427             assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
428             assertIsOK(rpcReply);
429             assertGetConfigWorks(netconfClient, this.getConfigCandidate);
430             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
431                     .getDocument();
432             assertIsOK(rpcReply);
433
434             final ObjectName on = new ObjectName(
435                     "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
436             Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
437             assertEquals(cfgBeans, Sets.newHashSet(on));
438         }
439     }
440
441     private NetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
442         final NetconfClient netconfClient = new NetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
443         assertEquals(expected, Long.toString(netconfClient.getSessionId()));
444         return netconfClient;
445     }
446
447 }