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