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