8f35f199cbd9ef624aeb3527d575ef2a333acc1e
[netconf.git] / netconf / netconf-impl / src / test / java / org / opendaylight / netconf / impl / ConcurrentClientsTest.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
9 package org.opendaylight.netconf.impl;
10
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static org.junit.Assert.assertEquals;
13 import static org.mockito.Matchers.any;
14 import static org.mockito.Mockito.doNothing;
15 import static org.mockito.Mockito.doReturn;
16 import static org.mockito.Mockito.mock;
17
18 import com.google.common.base.Preconditions;
19 import com.google.common.collect.Lists;
20 import com.google.common.collect.Sets;
21 import com.google.common.io.ByteStreams;
22 import io.netty.channel.ChannelFuture;
23 import io.netty.channel.EventLoopGroup;
24 import io.netty.channel.nio.NioEventLoopGroup;
25 import io.netty.util.HashedWheelTimer;
26 import io.netty.util.concurrent.GlobalEventExecutor;
27 import java.io.DataOutputStream;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.net.InetSocketAddress;
31 import java.net.Socket;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.List;
36 import java.util.Set;
37 import java.util.concurrent.ExecutionException;
38 import java.util.concurrent.ExecutorService;
39 import java.util.concurrent.Executors;
40 import java.util.concurrent.Future;
41 import java.util.concurrent.ThreadFactory;
42 import java.util.concurrent.atomic.AtomicLong;
43 import org.junit.After;
44 import org.junit.AfterClass;
45 import org.junit.Before;
46 import org.junit.BeforeClass;
47 import org.junit.Test;
48 import org.junit.runner.RunWith;
49 import org.junit.runners.Parameterized;
50 import org.opendaylight.controller.config.util.capability.Capability;
51 import org.opendaylight.controller.config.util.xml.DocumentedException;
52 import org.opendaylight.controller.config.util.xml.XmlUtil;
53 import org.opendaylight.netconf.api.NetconfMessage;
54 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
55 import org.opendaylight.netconf.api.monitoring.CapabilityListener;
56 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
57 import org.opendaylight.netconf.api.monitoring.SessionEvent;
58 import org.opendaylight.netconf.api.monitoring.SessionListener;
59 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
60 import org.opendaylight.netconf.client.NetconfClientDispatcher;
61 import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
62 import org.opendaylight.netconf.client.SimpleNetconfClientSessionListener;
63 import org.opendaylight.netconf.client.TestingNetconfClient;
64 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
65 import org.opendaylight.netconf.client.conf.NetconfClientConfigurationBuilder;
66 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
67 import org.opendaylight.netconf.mapping.api.HandlingPriority;
68 import org.opendaylight.netconf.mapping.api.NetconfOperation;
69 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
70 import org.opendaylight.netconf.mapping.api.NetconfOperationService;
71 import org.opendaylight.netconf.mapping.api.NetconfOperationServiceFactory;
72 import org.opendaylight.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
73 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
74 import org.opendaylight.netconf.util.test.XmlFileLoader;
75 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.CapabilitiesBuilder;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80 import org.w3c.dom.Document;
81
82 @RunWith(Parameterized.class)
83 public class ConcurrentClientsTest {
84     private static final Logger LOG = LoggerFactory.getLogger(ConcurrentClientsTest.class);
85
86     private static ExecutorService clientExecutor;
87
88     private static final int CONCURRENCY = 32;
89     private static final InetSocketAddress netconfAddress = new InetSocketAddress("127.0.0.1", 8303);
90
91     private int nettyThreads;
92     private Class<? extends Runnable> clientRunnable;
93     private Set<String> serverCaps;
94
95     public ConcurrentClientsTest(int nettyThreads, Class<? extends Runnable> clientRunnable, Set<String> serverCaps) {
96         this.nettyThreads = nettyThreads;
97         this.clientRunnable = clientRunnable;
98         this.serverCaps = serverCaps;
99     }
100
101     @Parameterized.Parameters()
102     public static Collection<Object[]> data() {
103         return Arrays.asList(new Object[][]{{4, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
104                                             {1, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
105                                             // empty set of capabilities = only base 1.0 netconf capability
106                                             {4, TestingNetconfClientRunnable.class, Collections.emptySet()},
107                                             {4, TestingNetconfClientRunnable.class, getOnlyExiServerCaps()},
108                                             {4, TestingNetconfClientRunnable.class, getOnlyChunkServerCaps()},
109                                             {4, BlockingClientRunnable.class, getOnlyExiServerCaps()},
110                                             {1, BlockingClientRunnable.class, getOnlyExiServerCaps()},
111         });
112     }
113
114     private EventLoopGroup nettyGroup;
115     private NetconfClientDispatcher netconfClientDispatcher;
116
117     HashedWheelTimer hashedWheelTimer;
118     private TestingNetconfOperation testingNetconfOperation;
119
120     public static NetconfMonitoringService createMockedMonitoringService() {
121         NetconfMonitoringService monitoring = mock(NetconfMonitoringService.class);
122         final SessionListener sessionListener = mock(SessionListener.class);
123         doNothing().when(sessionListener).onSessionUp(any(NetconfServerSession.class));
124         doNothing().when(sessionListener).onSessionDown(any(NetconfServerSession.class));
125         doNothing().when(sessionListener).onSessionEvent(any(SessionEvent.class));
126         doReturn(new AutoCloseable() {
127             @Override
128             public void close() throws Exception {
129
130             }
131         }).when(monitoring).registerCapabilitiesListener(any(NetconfMonitoringService.CapabilitiesListener.class));
132         doReturn(sessionListener).when(monitoring).getSessionListener();
133         doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(monitoring).getCapabilities();
134         return monitoring;
135     }
136
137     @BeforeClass
138     public static void setUpClientExecutor() {
139         clientExecutor = Executors.newFixedThreadPool(CONCURRENCY, new ThreadFactory() {
140             int i = 1;
141
142             @Override
143             public Thread newThread(final Runnable r) {
144                 Thread thread = new Thread(r);
145                 thread.setName("client-" + i++);
146                 thread.setDaemon(true);
147                 return thread;
148             }
149         });
150     }
151
152     @Before
153     public void setUp() throws Exception {
154         hashedWheelTimer = new HashedWheelTimer();
155         nettyGroup = new NioEventLoopGroup(nettyThreads);
156         netconfClientDispatcher = new NetconfClientDispatcherImpl(nettyGroup, nettyGroup, hashedWheelTimer);
157
158         AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
159
160         testingNetconfOperation = new TestingNetconfOperation();
161         factoriesListener.onAddNetconfOperationServiceFactory(new TestingOperationServiceFactory(testingNetconfOperation));
162
163         SessionIdProvider idProvider = new SessionIdProvider();
164
165         NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactoryBuilder()
166                 .setTimer(hashedWheelTimer)
167                 .setAggregatedOpService(factoriesListener)
168                 .setIdProvider(idProvider)
169                 .setConnectionTimeoutMillis(5000)
170                 .setMonitoringService(createMockedMonitoringService())
171                 .setBaseCapabilities(serverCaps)
172                 .build();
173
174         NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
175         final NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer, nettyGroup, nettyGroup);
176
177         ChannelFuture s = dispatch.createServer(netconfAddress);
178         s.await();
179     }
180
181     @After
182     public void tearDown(){
183         hashedWheelTimer.stop();
184         try {
185             nettyGroup.shutdownGracefully().get();
186         } catch (InterruptedException | ExecutionException e) {
187             LOG.warn("Ignoring exception while cleaning up after test", e);
188         }
189     }
190
191     @AfterClass
192     public static void tearDownClientExecutor() {
193         clientExecutor.shutdownNow();
194     }
195
196     @Test(timeout = CONCURRENCY * 1000)
197     public void testConcurrentClients() throws Exception {
198
199         List<Future<?>> futures = Lists.newArrayListWithCapacity(CONCURRENCY);
200
201         for (int i = 0; i < CONCURRENCY; i++) {
202             futures.add(clientExecutor.submit(getInstanceOfClientRunnable()));
203         }
204
205         for (Future<?> future : futures) {
206             try {
207                 future.get();
208             } catch (InterruptedException e) {
209                 throw new IllegalStateException(e);
210             } catch (ExecutionException e) {
211                 LOG.error("Thread for testing client failed", e);
212                 throw e;
213             }
214         }
215
216         assertEquals(CONCURRENCY, testingNetconfOperation.getMessageCount());
217     }
218
219     public static Set<String> getOnlyExiServerCaps() {
220         return Sets.newHashSet(
221                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
222                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_EXI_1_0
223         );
224     }
225
226     public static Set<String> getOnlyChunkServerCaps() {
227         return Sets.newHashSet(
228                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
229                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1
230         );
231     }
232
233     public Runnable getInstanceOfClientRunnable() throws Exception {
234         return clientRunnable.getConstructor(ConcurrentClientsTest.class).newInstance(this);
235     }
236
237     /**
238      * Responds to all operations except start-exi and counts all requests
239      */
240     private static class TestingNetconfOperation implements NetconfOperation {
241
242         private final AtomicLong counter = new AtomicLong();
243
244         @Override
245         public HandlingPriority canHandle(Document message) {
246             return XmlUtil.toString(message).contains(NetconfStartExiMessage.START_EXI) ?
247                     HandlingPriority.CANNOT_HANDLE :
248                     HandlingPriority.HANDLE_WITH_MAX_PRIORITY;
249         }
250
251         @Override
252         public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
253             try {
254                 LOG.info("Handling netconf message from test {}", XmlUtil.toString(requestMessage));
255                 counter.getAndIncrement();
256                 return XmlUtil.readXmlToDocument("<test/>");
257             } catch (Exception e) {
258                 throw new RuntimeException(e);
259             }
260         }
261
262         public long getMessageCount() {
263             return counter.get();
264         }
265     }
266
267     /**
268      * Hardcoded operation service factory
269      */
270     private static class TestingOperationServiceFactory implements NetconfOperationServiceFactory {
271         private final NetconfOperation[] operations;
272
273         public TestingOperationServiceFactory(final NetconfOperation... operations) {
274             this.operations = operations;
275         }
276
277         @Override
278         public Set<Capability> getCapabilities() {
279             return Collections.emptySet();
280         }
281
282         @Override
283         public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
284             return new AutoCloseable(){
285                 @Override
286                 public void close() throws Exception {}
287             };
288         }
289
290         @Override
291         public NetconfOperationService createService(String netconfSessionIdForReporting) {
292             return new NetconfOperationService() {
293
294                 @Override
295                 public Set<NetconfOperation> getNetconfOperations() {
296                     return Sets.newHashSet(operations);
297                 }
298
299                 @Override
300                 public void close() {}
301             };
302         }
303     }
304
305     /**
306      * Pure socket based blocking client
307      */
308     public final class BlockingClientRunnable implements Runnable {
309
310         @Override
311         public void run() {
312             try {
313                 run2();
314             } catch (Exception e) {
315                 throw new IllegalStateException(Thread.currentThread().getName(), e);
316             }
317         }
318
319         private void run2() throws Exception {
320             InputStream clientHello = checkNotNull(XmlFileLoader
321                     .getResourceAsStream("netconfMessages/client_hello.xml"));
322             InputStream getConfig = checkNotNull(XmlFileLoader.getResourceAsStream("netconfMessages/getConfig.xml"));
323
324             Socket clientSocket = new Socket(netconfAddress.getHostString(), netconfAddress.getPort());
325             DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
326             InputStreamReader inFromServer = new InputStreamReader(clientSocket.getInputStream());
327
328             StringBuffer sb = new StringBuffer();
329             while (sb.toString().endsWith("]]>]]>") == false) {
330                 sb.append((char) inFromServer.read());
331             }
332             LOG.info(sb.toString());
333
334             outToServer.write(ByteStreams.toByteArray(clientHello));
335             outToServer.write("]]>]]>".getBytes());
336             outToServer.flush();
337             // Thread.sleep(100);
338             outToServer.write(ByteStreams.toByteArray(getConfig));
339             outToServer.write("]]>]]>".getBytes());
340             outToServer.flush();
341             Thread.sleep(100);
342             sb = new StringBuffer();
343             while (sb.toString().endsWith("]]>]]>") == false) {
344                 sb.append((char) inFromServer.read());
345             }
346             LOG.info(sb.toString());
347             clientSocket.close();
348         }
349     }
350
351     /**
352      * TestingNetconfClient based runnable
353      */
354     public final class TestingNetconfClientRunnable implements Runnable {
355
356         @Override
357         public void run() {
358             try {
359                 final TestingNetconfClient netconfClient =
360                         new TestingNetconfClient(Thread.currentThread().getName(), netconfClientDispatcher, getClientConfig());
361                 long sessionId = netconfClient.getSessionId();
362                 LOG.info("Client with session id {}: hello exchanged", sessionId);
363
364                 final NetconfMessage getMessage = XmlFileLoader
365                         .xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
366                 NetconfMessage result = netconfClient.sendRequest(getMessage).get();
367                 LOG.info("Client with session id {}: got result {}", sessionId, result);
368
369                 Preconditions.checkState(NetconfMessageUtil.isErrorMessage(result) == false,
370                         "Received error response: " + XmlUtil.toString(result.getDocument()) + " to request: "
371                                 + XmlUtil.toString(getMessage.getDocument()));
372
373                 netconfClient.close();
374                 LOG.info("Client with session id {}: ended", sessionId);
375             } catch (final Exception e) {
376                 throw new IllegalStateException(Thread.currentThread().getName(), e);
377             }
378         }
379
380         private NetconfClientConfiguration getClientConfig() {
381             final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
382             b.withAddress(netconfAddress);
383             b.withAdditionalHeader(new NetconfHelloMessageAdditionalHeader("uname", "10.10.10.1", "830", "tcp",
384                     "client"));
385             b.withSessionListener(new SimpleNetconfClientSessionListener());
386             b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE,
387                     NetconfClientConfigurationBuilder.DEFAULT_CONNECTION_TIMEOUT_MILLIS));
388             return b.build();
389         }
390     }
391 }