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