Untangle the XML/Hello message decoders
[controller.git] / opendaylight / netconf / netconf-it / src / test / java / org / opendaylight / controller / netconf / it / NetconfMonitoringITTest.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 package org.opendaylight.controller.netconf.it;
9
10 import com.google.common.base.Charsets;
11 import com.google.common.base.Optional;
12 import com.google.common.collect.Sets;
13 import io.netty.channel.ChannelFuture;
14 import junit.framework.Assert;
15 import org.junit.Before;
16 import org.junit.Test;
17 import org.junit.matchers.JUnitMatchers;
18 import org.mockito.Mock;
19 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
20 import org.opendaylight.controller.config.spi.ModuleFactory;
21 import org.opendaylight.controller.config.yang.store.api.YangStoreException;
22 import org.opendaylight.controller.config.yang.store.impl.HardcodedYangStoreService;
23 import org.opendaylight.controller.netconf.api.NetconfMessage;
24 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
25 import org.opendaylight.controller.netconf.client.NetconfClient;
26 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
27 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
28 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
29 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
30 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
31 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListener;
32 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
33 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshot;
34 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
35 import org.opendaylight.controller.netconf.mapping.api.Capability;
36 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
37 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
38 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
39 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.w3c.dom.Document;
43
44 import java.io.BufferedReader;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.io.InputStreamReader;
48 import java.net.InetSocketAddress;
49 import java.net.Socket;
50 import java.util.Collection;
51 import java.util.List;
52 import java.util.Set;
53
54 import static org.mockito.Matchers.anyLong;
55 import static org.mockito.Mockito.doReturn;
56 import static org.mockito.Mockito.mock;
57
58 public class NetconfMonitoringITTest extends AbstractNetconfConfigTest {
59
60     private static final Logger logger =  LoggerFactory.getLogger(NetconfITTest.class);
61
62     private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
63
64     @Mock
65     private DefaultCommitNotificationProducer commitNot;
66     private NetconfServerDispatcher dispatch;
67
68     private NetconfClientDispatcher clientDispatcher;
69
70     private NetconfMonitoringServiceImpl monitoringService;
71
72     @Before
73     public void setUp() throws Exception {
74         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(NetconfITTest.getModuleFactoriesS().toArray(
75                 new ModuleFactory[0])));
76
77         monitoringService = new NetconfMonitoringServiceImpl(getFactoriesListener());
78
79         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
80         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
81         factoriesListener
82                 .onAddNetconfOperationServiceFactory(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(
83                         new NetconfMonitoringOperationService(monitoringService)));
84
85
86         dispatch = createDispatcher(factoriesListener);
87         ChannelFuture s = dispatch.createServer(tcpAddress);
88         s.await();
89
90         clientDispatcher = new NetconfClientDispatcher(nettyThreadgroup, nettyThreadgroup, 5000);
91     }
92
93     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
94         final Collection<InputStream> yangDependencies = NetconfITTest.getBasicYangs();
95         return new HardcodedYangStoreService(yangDependencies);
96     }
97
98     private NetconfServerDispatcher createDispatcher(
99                                                      NetconfOperationServiceFactoryListenerImpl factoriesListener) {
100         return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(logger, monitoringService), commitNot);
101     }
102
103     static SessionMonitoringService getNetconfMonitoringListenerService(final Logger logger, final NetconfMonitoringServiceImpl monitor) {
104         return new SessionMonitoringService() {
105             @Override
106             public void onSessionUp(NetconfManagementSession session) {
107                 logger.debug("Management session up {}", session);
108                 monitor.onSessionUp(session);
109             }
110
111             @Override
112             public void onSessionDown(NetconfManagementSession session) {
113                 logger.debug("Management session down {}", session);
114                 monitor.onSessionDown(session);
115             }
116         };
117     }
118
119
120     @Test
121     public void testGetResponseFromMonitoring() throws Exception {
122         try (NetconfClient netconfClient = new NetconfClient("client-monitoring", tcpAddress, 4000, clientDispatcher)) {
123         try (NetconfClient netconfClient2 = new NetconfClient("client-monitoring2", tcpAddress, 4000, clientDispatcher)) {
124             NetconfMessage response = netconfClient.sendMessage(loadGetMessage());
125             assertSessionElementsInResponse(response.getDocument(), 2);
126         }
127             NetconfMessage response = netconfClient.sendMessage(loadGetMessage());
128             assertSessionElementsInResponse(response.getDocument(), 1);
129         }
130     }
131
132
133     @Test(timeout = 5 * 10000)
134     public void testClientHelloWithAuth() throws Exception {
135         String fileName = "netconfMessages/client_hello_with_auth.xml";
136         String hello = XmlFileLoader.fileToString(fileName);
137
138         fileName = "netconfMessages/get.xml";
139         String get = XmlFileLoader.fileToString(fileName);
140
141         Socket sock = new Socket(tcpAddress.getHostName(), tcpAddress.getPort());
142         sock.getOutputStream().write(hello.getBytes(Charsets.UTF_8));
143         String separator = "]]>]]>";
144
145         sock.getOutputStream().write(separator.getBytes(Charsets.UTF_8));
146         sock.getOutputStream().write(get.getBytes(Charsets.UTF_8));
147         sock.getOutputStream().write(separator.getBytes(Charsets.UTF_8));
148
149         StringBuilder responseBuilder = new StringBuilder();
150
151         try (InputStream inputStream = sock.getInputStream();
152              InputStreamReader reader = new InputStreamReader(inputStream);
153              BufferedReader buff = new BufferedReader(reader)) {
154             String line;
155             while ((line = buff.readLine()) != null) {
156
157                 responseBuilder.append(line);
158                 responseBuilder.append(System.lineSeparator());
159
160                 if(line.contains("</rpc-reply>"))
161                     break;
162             }
163         }
164
165         org.junit.Assert.assertThat(responseBuilder.toString(), JUnitMatchers.containsString("<capability>urn:ietf:params:netconf:capability:candidate:1.0</capability>"));
166         org.junit.Assert.assertThat(responseBuilder.toString(), JUnitMatchers.containsString("<username>tomas</username>"));
167     }
168
169     private void assertSessionElementsInResponse(Document document, int i) {
170         int elementSize = document.getElementsByTagName("session-id").getLength();
171         Assert.assertEquals(i, elementSize);
172     }
173
174     private NetconfMessage loadGetMessage() throws Exception {
175         return XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/get.xml");
176     }
177
178     public static NetconfOperationServiceFactoryListener getFactoriesListener() {
179         NetconfOperationServiceFactoryListener factoriesListener = mock(NetconfOperationServiceFactoryListener.class);
180         NetconfOperationServiceSnapshot snap = mock(NetconfOperationServiceSnapshot.class);
181         NetconfOperationService service = mock(NetconfOperationService.class);
182         Set<Capability> caps = Sets.newHashSet();
183         caps.add(new Capability() {
184             @Override
185             public String getCapabilityUri() {
186                 return "namespaceModuleRevision";
187             }
188
189             @Override
190             public Optional<String> getModuleNamespace() {
191                 return Optional.of("namespace");
192             }
193
194             @Override
195             public Optional<String> getModuleName() {
196                 return Optional.of("name");
197             }
198
199             @Override
200             public Optional<String> getRevision() {
201                 return Optional.of("revision");
202             }
203
204             @Override
205             public Optional<String> getCapabilitySchema() {
206                 return Optional.of("content");
207             }
208
209             @Override
210             public Optional<List<String>> getLocation() {
211                 return Optional.absent();
212             }
213         });
214
215         doReturn(caps).when(service).getCapabilities();
216         Set<NetconfOperationService> services = Sets.newHashSet(service);
217         doReturn(services).when(snap).getServices();
218         doReturn(snap).when(factoriesListener).getSnapshot(anyLong());
219
220         return factoriesListener;
221     }
222
223
224 }