Resolve Bug:681 - Fix config module registration to Service Registry.
[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 ch.ethz.ssh2.Connection;
12 import ch.ethz.ssh2.Session;
13 import com.google.common.collect.Lists;
14 import com.google.common.collect.Sets;
15 import io.netty.channel.ChannelFuture;
16 import junit.framework.Assert;
17 import org.apache.commons.io.IOUtils;
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.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
23 import org.opendaylight.controller.config.spi.ModuleFactory;
24 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
25 import org.opendaylight.controller.netconf.client.test.TestingNetconfClient;
26 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
27 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
28 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
29 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
30 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
31 import org.opendaylight.controller.netconf.StubUserManager;
32 import org.opendaylight.controller.netconf.api.NetconfMessage;
33 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
34 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
35 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
36 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
37 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
38 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
39 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
40 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
41 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
42 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
43 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
44 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
45 import org.opendaylight.controller.netconf.util.xml.XmlElement;
46 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.w3c.dom.Document;
50 import org.w3c.dom.Element;
51 import org.w3c.dom.NamedNodeMap;
52 import org.w3c.dom.Node;
53 import org.xml.sax.SAXException;
54
55 import javax.management.ObjectName;
56 import javax.xml.parsers.ParserConfigurationException;
57 import java.io.IOException;
58 import java.io.InputStream;
59 import java.lang.management.ManagementFactory;
60 import java.net.InetSocketAddress;
61 import java.util.ArrayList;
62 import java.util.Arrays;
63 import java.util.Collection;
64 import java.util.Collections;
65 import java.util.List;
66 import java.util.Set;
67 import java.util.concurrent.ExecutionException;
68 import java.util.concurrent.TimeoutException;
69
70 import static java.util.Collections.emptyList;
71 import static org.junit.Assert.assertEquals;
72 import static org.junit.Assert.assertNotNull;
73 import static org.junit.Assert.assertTrue;
74 import static org.mockito.Matchers.anyString;
75 import static org.mockito.Mockito.doReturn;
76 import static org.mockito.Mockito.mock;
77
78 public class NetconfITTest extends AbstractNetconfConfigTest {
79
80     // TODO refactor, pull common code up to AbstractNetconfITTest
81
82     private static final Logger logger = LoggerFactory.getLogger(NetconfITTest.class);
83
84     private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
85     private static final InetSocketAddress sshAddress = new InetSocketAddress("127.0.0.1", 10830);
86     private static final String USERNAME = "netconf";
87     private static final String PASSWORD = "netconf";
88
89     private NetconfMessage getConfig, getConfigCandidate, editConfig,
90             closeSession, startExi, stopExi;
91     private DefaultCommitNotificationProducer commitNot;
92     private NetconfServerDispatcher dispatch;
93
94     private NetconfClientDispatcher clientDispatcher;
95
96     @Before
97     public void setUp() throws Exception {
98         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,getModuleFactories().toArray(
99                 new ModuleFactory[0])));
100
101         loadMessages();
102
103         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
104         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
105
106
107         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
108
109         dispatch = createDispatcher(factoriesListener);
110         ChannelFuture s = dispatch.createServer(tcpAddress);
111         s.await();
112
113         clientDispatcher = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup, 5000);
114     }
115
116     private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
117         return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNot);
118     }
119
120     static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
121         NetconfOperationProvider netconfOperationProvider = mock(NetconfOperationProvider.class);
122         NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class);
123         doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
124         doReturn(snap).when(netconfOperationProvider).openSnapshot(anyString());
125         return new NetconfMonitoringServiceImpl(netconfOperationProvider);
126     }
127
128     @After
129     public void tearDown() throws Exception {
130         commitNot.close();
131         clientDispatcher.close();
132     }
133
134     private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
135         this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
136         this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
137         this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
138         this.startExi = XmlFileLoader
139                 .xmlFileToNetconfMessage("netconfMessages/startExi.xml");
140         this.stopExi = XmlFileLoader
141                 .xmlFileToNetconfMessage("netconfMessages/stopExi.xml");
142         this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
143     }
144
145     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
146         final Collection<InputStream> yangDependencies = getBasicYangs();
147         return new HardcodedYangStoreService(yangDependencies);
148     }
149
150     static Collection<InputStream> getBasicYangs() throws IOException {
151
152         List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
153                 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
154                 "/META-INF/yang/ietf-inet-types.yang");
155         final Collection<InputStream> yangDependencies = new ArrayList<>();
156         List<String> failedToFind = new ArrayList<>();
157         for (String path : paths) {
158             InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
159             if (resourceAsStream == null) {
160                 failedToFind.add(path);
161             } else {
162                 yangDependencies.add(resourceAsStream);
163             }
164         }
165         assertEquals("Some yang files were not found", emptyList(), failedToFind);
166         return yangDependencies;
167     }
168
169     protected List<ModuleFactory> getModuleFactories() {
170         return getModuleFactoriesS();
171     }
172
173     static List<ModuleFactory> getModuleFactoriesS() {
174         return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
175                 new NetconfTestImplModuleFactory());
176     }
177
178     @Test
179     public void testNetconfClientDemonstration() throws Exception {
180         try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", tcpAddress, 4000, clientDispatcher)) {
181
182             Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
183             long sessionId = netconfClient.getSessionId();
184
185             // NetconfMessage can be created :
186             // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
187
188             NetconfMessage response = netconfClient.sendMessage(getConfig);
189             response.getDocument();
190         }
191     }
192
193     @Test
194     public void testTwoSessions() throws Exception {
195         try (TestingNetconfClient netconfClient = new TestingNetconfClient("1", tcpAddress, 10000, clientDispatcher))  {
196             try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("2", tcpAddress, 10000, clientDispatcher)) {
197             }
198         }
199     }
200
201     @Ignore
202     @Test
203     public void waitingTest() throws Exception {
204         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
205         transaction.createModule(DepTestImplModuleFactory.NAME, "eb");
206         transaction.commit();
207         Thread.currentThread().suspend();
208     }
209
210     @Test
211     public void rpcReplyContainsAllAttributesTest() throws Exception {
212         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
213             final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
214                     + "<get/>" + "</rpc>";
215             final Document doc = XmlUtil.readXmlToDocument(rpc);
216             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
217             assertNotNull(message);
218             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
219             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
220
221             assertSameAttributes(expectedAttributes, returnedAttributes);
222         }
223     }
224
225     private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
226         assertNotNull("Expecting 4 attributes", returnedAttributes);
227         assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
228
229         for (int i = 0; i < expectedAttributes.getLength(); i++) {
230             final Node expAttr = expectedAttributes.item(i);
231             final Node attr = returnedAttributes.item(i);
232             assertEquals(expAttr.getNodeName(), attr.getNodeName());
233             assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
234             assertEquals(expAttr.getTextContent(), attr.getTextContent());
235         }
236     }
237
238     @Test
239     public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
240         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
241             final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
242                     + "<commit/>" + "</rpc>";
243             final Document doc = XmlUtil.readXmlToDocument(rpc);
244             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
245             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
246             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
247
248             assertSameAttributes(expectedAttributes, returnedAttributes);
249         }
250     }
251
252     @Test
253     public void rpcOutputContainsCorrectNamespace() throws Exception {
254         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
255         ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
256         ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
257         NetconfTestImplModuleMXBean proxy = configRegistryClient
258                 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
259         proxy.setTestingDep(dep);
260         proxy.setSimpleShort((short) 0);
261
262         transaction.commit();
263
264         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
265             final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
266
267             final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
268                     + "<no-arg xmlns=\""
269                     + expectedNamespace
270                     + "\">    "
271                     + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
272                     + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
273             final Document doc = XmlUtil.readXmlToDocument(rpc);
274             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
275
276             final Element rpcReply = message.getDocument().getDocumentElement();
277             final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
278             assertEquals("result", resultElement.getName());
279
280             final String namespace = resultElement.getNamespaceAttribute();
281             assertEquals(expectedNamespace, namespace);
282         }
283     }
284
285     @Test
286     public void testCloseSession() throws Exception {
287         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
288
289             // edit config
290             Document rpcReply = netconfClient.sendMessage(this.editConfig)
291                     .getDocument();
292             assertIsOK(rpcReply);
293
294             rpcReply = netconfClient.sendMessage(this.closeSession)
295                     .getDocument();
296
297             assertIsOK(rpcReply);
298         }
299     }
300
301     @Test
302     public void testEditConfig() throws Exception {
303         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
304             // send edit_config.xml
305             final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
306             assertIsOK(rpcReply);
307         }
308     }
309
310     @Test
311     public void testValidate() throws Exception {
312         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
313             // begin transaction
314             Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
315             assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
316
317             // operations empty
318             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
319                     .getDocument();
320             assertIsOK(rpcReply);
321         }
322     }
323
324     private void assertIsOK(final Document rpcReply) {
325         assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
326         assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
327     }
328
329     private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException {
330         return assertGetConfigWorks(netconfClient, this.getConfig);
331     }
332
333     private Document assertGetConfigWorks(final TestingNetconfClient netconfClient, final NetconfMessage getConfigMessage)
334             throws InterruptedException, ExecutionException, TimeoutException {
335         final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
336         assertNotNull(rpcReply);
337         assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
338         return rpcReply.getDocument();
339     }
340
341     @Test
342     public void testGetConfig() throws Exception {
343         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
344             assertGetConfigWorks(netconfClient);
345         }
346     }
347
348     @Test
349     public void createYangTestBasedOnYuma() throws Exception {
350         try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
351             Document rpcReply = netconfClient.sendMessage(
352                     XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
353                     .getDocument();
354             assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
355             assertIsOK(rpcReply);
356             assertGetConfigWorks(netconfClient, this.getConfigCandidate);
357             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
358                     .getDocument();
359             assertIsOK(rpcReply);
360
361             final ObjectName on = new ObjectName(
362                     "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
363             Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
364             assertEquals(cfgBeans, Sets.newHashSet(on));
365         }
366     }
367
368     private TestingNetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
369         final TestingNetconfClient netconfClient = new TestingNetconfClient("test " + address.toString(), address, 5000, clientDispatcher);
370         assertEquals(expected, Long.toString(netconfClient.getSessionId()));
371         return netconfClient;
372     }
373
374     private void startSSHServer() throws Exception {
375         logger.info("Creating SSH server");
376         StubUserManager um = new StubUserManager(USERNAME, PASSWORD);
377         String pem;
378         try (InputStream is = getClass().getResourceAsStream("/RSA.pk")) {
379             pem = IOUtils.toString(is);
380         }
381         AuthProvider ap = new AuthProvider(um, pem);
382         Thread sshServerThread = new Thread(NetconfSSHServer.start(10830, tcpAddress, ap));
383         sshServerThread.setDaemon(true);
384         sshServerThread.start();
385         logger.info("SSH server on");
386     }
387
388     @Test
389     public void sshTest() throws Exception {
390         startSSHServer();
391         logger.info("creating connection");
392         Connection conn = new Connection(sshAddress.getHostName(), sshAddress.getPort());
393         Assert.assertNotNull(conn);
394         logger.info("connection created");
395         conn.connect();
396         boolean isAuthenticated = conn.authenticateWithPassword(USERNAME, PASSWORD);
397         assertTrue(isAuthenticated);
398         logger.info("user authenticated");
399         final Session sess = conn.openSession();
400         sess.startSubSystem("netconf");
401         logger.info("user authenticated");
402         sess.getStdin().write(XmlUtil.toString(this.getConfig.getDocument()).getBytes());
403
404         new Thread() {
405             @Override
406             public void run() {
407                 while (true) {
408                     byte[] bytes = new byte[1024];
409                     int c = 0;
410                     try {
411                         c = sess.getStdout().read(bytes);
412                     } catch (IOException e) {
413                         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
414                     }
415                     logger.info("got data:" + bytes);
416                     if (c == 0) {
417                         break;
418                     }
419                 }
420             }
421         }.join();
422     }
423
424 }