4af66532a18ec2d8a8fc067f61a777905f4011a2
[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.netconf.confignetconfconnector.osgi.YangStoreException;
34 import org.opendaylight.controller.netconf.api.NetconfMessage;
35 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
36 import org.opendaylight.controller.netconf.client.NetconfClient;
37 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
38 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
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.NetconfOperationServiceFactoryListener;
43 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
44 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshot;
45 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
46 import org.opendaylight.controller.netconf.mapping.api.Capability;
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.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.w3c.dom.Document;
54
55 import com.google.common.base.Charsets;
56 import com.google.common.base.Optional;
57 import com.google.common.collect.Sets;
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(getFactoriesListener());
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 (NetconfClient netconfClient = new NetconfClient("client-monitoring", tcpAddress, 4000, clientDispatcher)) {
124         try (NetconfClient netconfClient2 = new NetconfClient("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 = 5 * 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         org.junit.Assert.assertThat(responseBuilder.toString(), JUnitMatchers.containsString("<capability>urn:ietf:params:netconf:capability:candidate:1.0</capability>"));
169         org.junit.Assert.assertThat(responseBuilder.toString(), JUnitMatchers.containsString("<username>tomas</username>"));
170     }
171
172     private void assertSessionElementsInResponse(Document document, int i) {
173         int elementSize = document.getElementsByTagName("session-id").getLength();
174         Assert.assertEquals(i, elementSize);
175     }
176
177     private NetconfMessage loadGetMessage() throws Exception {
178         return XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/get.xml");
179     }
180
181     public static NetconfOperationServiceFactoryListener getFactoriesListener() {
182         NetconfOperationServiceFactoryListener factoriesListener = mock(NetconfOperationServiceFactoryListener.class);
183         NetconfOperationServiceSnapshot snap = mock(NetconfOperationServiceSnapshot.class);
184         NetconfOperationService service = mock(NetconfOperationService.class);
185         Set<Capability> caps = Sets.newHashSet();
186         caps.add(new Capability() {
187             @Override
188             public String getCapabilityUri() {
189                 return "namespaceModuleRevision";
190             }
191
192             @Override
193             public Optional<String> getModuleNamespace() {
194                 return Optional.of("namespace");
195             }
196
197             @Override
198             public Optional<String> getModuleName() {
199                 return Optional.of("name");
200             }
201
202             @Override
203             public Optional<String> getRevision() {
204                 return Optional.of("revision");
205             }
206
207             @Override
208             public Optional<String> getCapabilitySchema() {
209                 return Optional.of("content");
210             }
211
212             @Override
213             public Optional<List<String>> getLocation() {
214                 return Optional.absent();
215             }
216         });
217
218         doReturn(caps).when(service).getCapabilities();
219         Set<NetconfOperationService> services = Sets.newHashSet(service);
220         doReturn(services).when(snap).getServices();
221         doReturn(snap).when(factoriesListener).getSnapshot(anyLong());
222
223         return factoriesListener;
224     }
225
226
227 }