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