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