2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.netconf.impl;
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;
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;
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.netconf.api.DocumentedException;
51 import org.opendaylight.netconf.api.NetconfMessage;
52 import org.opendaylight.netconf.api.capability.Capability;
53 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
54 import org.opendaylight.netconf.api.monitoring.CapabilityListener;
55 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
56 import org.opendaylight.netconf.api.monitoring.SessionEvent;
57 import org.opendaylight.netconf.api.monitoring.SessionListener;
58 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
59 import org.opendaylight.netconf.api.xml.XmlUtil;
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;
82 @RunWith(Parameterized.class)
83 public class ConcurrentClientsTest {
84 private static final Logger LOG = LoggerFactory.getLogger(ConcurrentClientsTest.class);
86 private static ExecutorService clientExecutor;
88 private static final int CONCURRENCY = 32;
89 private static final InetSocketAddress NETCONF_ADDRESS = new InetSocketAddress("127.0.0.1", 8303);
91 private final int nettyThreads;
92 private final Class<? extends Runnable> clientRunnable;
93 private final Set<String> serverCaps;
95 public ConcurrentClientsTest(int nettyThreads, Class<? extends Runnable> clientRunnable, Set<String> serverCaps) {
96 this.nettyThreads = nettyThreads;
97 this.clientRunnable = clientRunnable;
98 this.serverCaps = serverCaps;
101 @Parameterized.Parameters()
102 public static Collection<Object[]> data() {
103 return Arrays.asList(new Object[][]{{4, TestingNetconfClientRunnable.class,
104 NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
105 {1, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
106 // empty set of capabilities = only base 1.0 netconf capability
107 {4, TestingNetconfClientRunnable.class, Collections.emptySet()},
108 {4, TestingNetconfClientRunnable.class, getOnlyExiServerCaps()},
109 {4, TestingNetconfClientRunnable.class, getOnlyChunkServerCaps()},
110 {4, BlockingClientRunnable.class, getOnlyExiServerCaps()},
111 {1, BlockingClientRunnable.class, getOnlyExiServerCaps()},
115 private EventLoopGroup nettyGroup;
116 private NetconfClientDispatcher netconfClientDispatcher;
118 HashedWheelTimer hashedWheelTimer;
119 private TestingNetconfOperation testingNetconfOperation;
121 public static NetconfMonitoringService createMockedMonitoringService() {
122 NetconfMonitoringService monitoring = mock(NetconfMonitoringService.class);
123 final SessionListener sessionListener = mock(SessionListener.class);
124 doNothing().when(sessionListener).onSessionUp(any(NetconfServerSession.class));
125 doNothing().when(sessionListener).onSessionDown(any(NetconfServerSession.class));
126 doNothing().when(sessionListener).onSessionEvent(any(SessionEvent.class));
127 doReturn((AutoCloseable) () -> {
129 }).when(monitoring).registerCapabilitiesListener(any(NetconfMonitoringService.CapabilitiesListener.class));
130 doReturn(sessionListener).when(monitoring).getSessionListener();
131 doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(monitoring)
137 public static void setUpClientExecutor() {
138 clientExecutor = Executors.newFixedThreadPool(CONCURRENCY, new ThreadFactory() {
142 public Thread newThread(final Runnable runnable) {
143 Thread thread = new Thread(runnable);
144 thread.setName("client-" + index++);
145 thread.setDaemon(true);
152 public void setUp() throws Exception {
153 hashedWheelTimer = new HashedWheelTimer();
154 nettyGroup = new NioEventLoopGroup(nettyThreads);
155 netconfClientDispatcher = new NetconfClientDispatcherImpl(nettyGroup, nettyGroup, hashedWheelTimer);
157 AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
159 testingNetconfOperation = new TestingNetconfOperation();
160 factoriesListener.onAddNetconfOperationServiceFactory(
161 new TestingOperationServiceFactory(testingNetconfOperation));
163 SessionIdProvider idProvider = new SessionIdProvider();
165 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new
166 NetconfServerSessionNegotiatorFactoryBuilder()
167 .setTimer(hashedWheelTimer)
168 .setAggregatedOpService(factoriesListener)
169 .setIdProvider(idProvider)
170 .setConnectionTimeoutMillis(5000)
171 .setMonitoringService(createMockedMonitoringService())
172 .setBaseCapabilities(serverCaps)
175 NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer =
176 new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
177 final NetconfServerDispatcherImpl dispatch =
178 new NetconfServerDispatcherImpl(serverChannelInitializer, nettyGroup, nettyGroup);
180 ChannelFuture server = dispatch.createServer(NETCONF_ADDRESS);
185 public void tearDown() {
186 hashedWheelTimer.stop();
188 nettyGroup.shutdownGracefully().get();
189 } catch (InterruptedException | ExecutionException e) {
190 LOG.warn("Ignoring exception while cleaning up after test", e);
195 public static void tearDownClientExecutor() {
196 clientExecutor.shutdownNow();
199 @Test(timeout = CONCURRENCY * 1000)
200 public void testConcurrentClients() throws Exception {
202 List<Future<?>> futures = Lists.newArrayListWithCapacity(CONCURRENCY);
204 for (int i = 0; i < CONCURRENCY; i++) {
205 futures.add(clientExecutor.submit(getInstanceOfClientRunnable()));
208 for (Future<?> future : futures) {
211 } catch (InterruptedException e) {
212 throw new IllegalStateException(e);
213 } catch (ExecutionException e) {
214 LOG.error("Thread for testing client failed", e);
219 assertEquals(CONCURRENCY, testingNetconfOperation.getMessageCount());
222 public static Set<String> getOnlyExiServerCaps() {
223 return Sets.newHashSet(
224 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
225 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_EXI_1_0
229 public static Set<String> getOnlyChunkServerCaps() {
230 return Sets.newHashSet(
231 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
232 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1
236 public Runnable getInstanceOfClientRunnable() throws Exception {
237 return clientRunnable.getConstructor(ConcurrentClientsTest.class).newInstance(this);
241 * Responds to all operations except start-exi and counts all requests.
243 private static class TestingNetconfOperation implements NetconfOperation {
245 private final AtomicLong counter = new AtomicLong();
248 public HandlingPriority canHandle(Document message) {
249 return XmlUtil.toString(message).contains(NetconfStartExiMessage.START_EXI)
250 ? HandlingPriority.CANNOT_HANDLE :
251 HandlingPriority.HANDLE_WITH_MAX_PRIORITY;
254 @SuppressWarnings("checkstyle:IllegalCatch")
256 public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation)
257 throws DocumentedException {
259 LOG.info("Handling netconf message from test {}", XmlUtil.toString(requestMessage));
260 counter.getAndIncrement();
261 return XmlUtil.readXmlToDocument("<test/>");
262 } catch (Exception e) {
263 throw new RuntimeException(e);
267 public long getMessageCount() {
268 return counter.get();
273 * Hardcoded operation service factory.
275 private static class TestingOperationServiceFactory implements NetconfOperationServiceFactory {
276 private final NetconfOperation[] operations;
278 TestingOperationServiceFactory(final NetconfOperation... operations) {
279 this.operations = operations;
283 public Set<Capability> getCapabilities() {
284 return Collections.emptySet();
288 public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
294 public NetconfOperationService createService(String netconfSessionIdForReporting) {
295 return new NetconfOperationService() {
298 public Set<NetconfOperation> getNetconfOperations() {
299 return Sets.newHashSet(operations);
303 public void close() {
310 * Pure socket based blocking client.
312 @SuppressWarnings("checkstyle:IllegalCatch")
313 public final class BlockingClientRunnable implements Runnable {
319 } catch (Exception e) {
320 throw new IllegalStateException(Thread.currentThread().getName(), e);
324 private void run2() throws Exception {
325 InputStream clientHello = checkNotNull(XmlFileLoader
326 .getResourceAsStream("netconfMessages/client_hello.xml"));
327 final InputStream getConfig =
328 checkNotNull(XmlFileLoader.getResourceAsStream("netconfMessages/getConfig.xml"));
330 Socket clientSocket = new Socket(NETCONF_ADDRESS.getHostString(), NETCONF_ADDRESS.getPort());
331 DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
332 InputStreamReader inFromServer = new InputStreamReader(clientSocket.getInputStream());
334 StringBuffer sb = new StringBuffer();
335 while (sb.toString().endsWith("]]>]]>") == false) {
336 sb.append((char) inFromServer.read());
338 LOG.info(sb.toString());
340 outToServer.write(ByteStreams.toByteArray(clientHello));
341 outToServer.write("]]>]]>".getBytes());
343 // Thread.sleep(100);
344 outToServer.write(ByteStreams.toByteArray(getConfig));
345 outToServer.write("]]>]]>".getBytes());
348 sb = new StringBuffer();
349 while (sb.toString().endsWith("]]>]]>") == false) {
350 sb.append((char) inFromServer.read());
352 LOG.info(sb.toString());
353 clientSocket.close();
358 * TestingNetconfClient based runnable.
360 public final class TestingNetconfClientRunnable implements Runnable {
362 @SuppressWarnings("checkstyle:IllegalCatch")
366 final TestingNetconfClient netconfClient =
367 new TestingNetconfClient(Thread.currentThread().getName(), netconfClientDispatcher,
369 long sessionId = netconfClient.getSessionId();
370 LOG.info("Client with session id {}: hello exchanged", sessionId);
372 final NetconfMessage getMessage = XmlFileLoader
373 .xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
374 NetconfMessage result = netconfClient.sendRequest(getMessage).get();
375 LOG.info("Client with session id {}: got result {}", sessionId, result);
377 Preconditions.checkState(NetconfMessageUtil.isErrorMessage(result) == false,
378 "Received error response: " + XmlUtil.toString(result.getDocument()) + " to request: "
379 + XmlUtil.toString(getMessage.getDocument()));
381 netconfClient.close();
382 LOG.info("Client with session id {}: ended", sessionId);
383 } catch (final Exception e) {
384 throw new IllegalStateException(Thread.currentThread().getName(), e);
388 private NetconfClientConfiguration getClientConfig() {
389 final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
390 b.withAddress(NETCONF_ADDRESS);
391 b.withAdditionalHeader(new NetconfHelloMessageAdditionalHeader("uname", "10.10.10.1", "830", "tcp",
393 b.withSessionListener(new SimpleNetconfClientSessionListener());
394 b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE,
395 NetconfClientConfigurationBuilder.DEFAULT_CONNECTION_TIMEOUT_MILLIS));