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