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.controller.netconf.impl;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.fail;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.anySetOf;
16 import static org.mockito.Mockito.doNothing;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.Lists;
21 import com.google.common.collect.Sets;
22 import com.google.common.io.ByteStreams;
23 import io.netty.channel.ChannelFuture;
24 import io.netty.channel.EventLoopGroup;
25 import io.netty.channel.nio.NioEventLoopGroup;
26 import io.netty.util.HashedWheelTimer;
27 import io.netty.util.concurrent.GlobalEventExecutor;
28 import java.io.DataOutputStream;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.lang.management.ManagementFactory;
32 import java.net.InetSocketAddress;
33 import java.net.Socket;
34 import java.util.Arrays;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.List;
39 import java.util.concurrent.ExecutionException;
40 import java.util.concurrent.ExecutorService;
41 import java.util.concurrent.Executors;
42 import java.util.concurrent.Future;
43 import java.util.concurrent.ThreadFactory;
44 import java.util.concurrent.atomic.AtomicLong;
45 import org.junit.After;
46 import org.junit.AfterClass;
47 import org.junit.Before;
48 import org.junit.BeforeClass;
49 import org.junit.Test;
50 import org.junit.runner.RunWith;
51 import org.junit.runners.Parameterized;
52 import org.opendaylight.controller.netconf.api.Capability;
53 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
54 import org.opendaylight.controller.netconf.api.NetconfMessage;
55 import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
56 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
57 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
58 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
59 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
60 import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
61 import org.opendaylight.controller.netconf.client.TestingNetconfClient;
62 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
63 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
64 import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
65 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
66 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
67 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
68 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
69 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
70 import org.opendaylight.controller.netconf.nettyutil.handler.exi.NetconfStartExiMessage;
71 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
72 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
73 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
74 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
75 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.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 netconfAddress = new InetSocketAddress("127.0.0.1", 8303);
91 private int nettyThreads;
92 private Class<? extends Runnable> clientRunnable;
93 private 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, 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()},
114 private EventLoopGroup nettyGroup;
115 private NetconfClientDispatcher netconfClientDispatcher;
117 private DefaultCommitNotificationProducer commitNot;
119 HashedWheelTimer hashedWheelTimer;
120 private TestingNetconfOperation testingNetconfOperation;
122 public static NetconfMonitoringService createMockedMonitoringService() {
123 NetconfMonitoringService monitoring = mock(NetconfMonitoringService.class);
124 doNothing().when(monitoring).onSessionUp(any(NetconfServerSession.class));
125 doNothing().when(monitoring).onSessionDown(any(NetconfServerSession.class));
126 doReturn(new AutoCloseable() {
128 public void close() throws Exception {
131 }).when(monitoring).registerListener(any(NetconfMonitoringService.MonitoringListener.class));
132 doNothing().when(monitoring).onCapabilitiesAdded(anySetOf(Capability.class));
133 doNothing().when(monitoring).onCapabilitiesRemoved(anySetOf(Capability.class));
134 doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(monitoring).getCapabilities();
139 public static void setUpClientExecutor() {
140 clientExecutor = Executors.newFixedThreadPool(CONCURRENCY, new ThreadFactory() {
144 public Thread newThread(final Runnable r) {
145 Thread thread = new Thread(r);
146 thread.setName("client-" + i++);
147 thread.setDaemon(true);
154 public void setUp() throws Exception {
155 hashedWheelTimer = new HashedWheelTimer();
156 nettyGroup = new NioEventLoopGroup(nettyThreads);
157 netconfClientDispatcher = new NetconfClientDispatcherImpl(nettyGroup, nettyGroup, hashedWheelTimer);
159 AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
161 testingNetconfOperation = new TestingNetconfOperation();
162 factoriesListener.onAddNetconfOperationServiceFactory(new TestingOperationServiceFactory(testingNetconfOperation));
164 SessionIdProvider idProvider = new SessionIdProvider();
166 NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
167 hashedWheelTimer, factoriesListener, idProvider, 5000, commitNot, createMockedMonitoringService(), serverCaps);
169 commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
171 NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
172 final NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer, nettyGroup, nettyGroup);
174 ChannelFuture s = dispatch.createServer(netconfAddress);
179 public void tearDown(){
181 hashedWheelTimer.stop();
183 nettyGroup.shutdownGracefully().get();
184 } catch (InterruptedException | ExecutionException e) {
185 LOG.warn("Ignoring exception while cleaning up after test", e);
190 public static void tearDownClientExecutor() {
191 clientExecutor.shutdownNow();
194 @Test(timeout = CONCURRENCY * 1000)
195 public void testConcurrentClients() throws Exception {
197 List<Future<?>> futures = Lists.newArrayListWithCapacity(CONCURRENCY);
199 for (int i = 0; i < CONCURRENCY; i++) {
200 futures.add(clientExecutor.submit(getInstanceOfClientRunnable()));
203 for (Future<?> future : futures) {
206 } catch (InterruptedException e) {
207 throw new IllegalStateException(e);
208 } catch (ExecutionException e) {
209 LOG.error("Thread for testing client failed", e);
210 fail("Client failed: " + e.getMessage());
214 assertEquals(CONCURRENCY, testingNetconfOperation.getMessageCount());
217 public static Set<String> getOnlyExiServerCaps() {
218 return Sets.newHashSet(
219 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
220 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_EXI_1_0
224 public static Set<String> getOnlyChunkServerCaps() {
225 return Sets.newHashSet(
226 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
227 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1
231 public Runnable getInstanceOfClientRunnable() throws Exception {
232 return clientRunnable.getConstructor(ConcurrentClientsTest.class).newInstance(this);
236 * Responds to all operations except start-exi and counts all requests
238 private static class TestingNetconfOperation implements NetconfOperation {
240 private final AtomicLong counter = new AtomicLong();
243 public HandlingPriority canHandle(Document message) {
244 return XmlUtil.toString(message).contains(NetconfStartExiMessage.START_EXI) ?
245 HandlingPriority.CANNOT_HANDLE :
246 HandlingPriority.HANDLE_WITH_MAX_PRIORITY;
250 public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
252 LOG.info("Handling netconf message from test {}", XmlUtil.toString(requestMessage));
253 counter.getAndIncrement();
254 return XmlUtil.readXmlToDocument("<test/>");
255 } catch (Exception e) {
256 throw new RuntimeException(e);
260 public long getMessageCount() {
261 return counter.get();
266 * Hardcoded operation service factory
268 private static class TestingOperationServiceFactory implements NetconfOperationServiceFactory {
269 private final NetconfOperation[] operations;
271 public TestingOperationServiceFactory(final NetconfOperation... operations) {
272 this.operations = operations;
276 public Set<Capability> getCapabilities() {
277 return Collections.emptySet();
281 public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
282 return new AutoCloseable(){
284 public void close() throws Exception {}
289 public NetconfOperationService createService(String netconfSessionIdForReporting) {
290 return new NetconfOperationService() {
293 public Set<NetconfOperation> getNetconfOperations() {
294 return Sets.newHashSet(operations);
298 public void close() {}
304 * Pure socket based blocking client
306 public final class BlockingClientRunnable implements Runnable {
312 } catch (Exception e) {
313 throw new IllegalStateException(Thread.currentThread().getName(), e);
317 private void run2() throws Exception {
318 InputStream clientHello = checkNotNull(XmlFileLoader
319 .getResourceAsStream("netconfMessages/client_hello.xml"));
320 InputStream getConfig = checkNotNull(XmlFileLoader.getResourceAsStream("netconfMessages/getConfig.xml"));
322 Socket clientSocket = new Socket(netconfAddress.getHostString(), netconfAddress.getPort());
323 DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
324 InputStreamReader inFromServer = new InputStreamReader(clientSocket.getInputStream());
326 StringBuffer sb = new StringBuffer();
327 while (sb.toString().endsWith("]]>]]>") == false) {
328 sb.append((char) inFromServer.read());
330 LOG.info(sb.toString());
332 outToServer.write(ByteStreams.toByteArray(clientHello));
333 outToServer.write("]]>]]>".getBytes());
335 // Thread.sleep(100);
336 outToServer.write(ByteStreams.toByteArray(getConfig));
337 outToServer.write("]]>]]>".getBytes());
340 sb = new StringBuffer();
341 while (sb.toString().endsWith("]]>]]>") == false) {
342 sb.append((char) inFromServer.read());
344 LOG.info(sb.toString());
345 clientSocket.close();
350 * TestingNetconfClient based runnable
352 public final class TestingNetconfClientRunnable implements Runnable {
357 final TestingNetconfClient netconfClient =
358 new TestingNetconfClient(Thread.currentThread().getName(), netconfClientDispatcher, getClientConfig());
359 long sessionId = netconfClient.getSessionId();
360 LOG.info("Client with session id {}: hello exchanged", sessionId);
362 final NetconfMessage getMessage = XmlFileLoader
363 .xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
364 NetconfMessage result = netconfClient.sendRequest(getMessage).get();
365 LOG.info("Client with session id {}: got result {}", sessionId, result);
367 Preconditions.checkState(NetconfMessageUtil.isErrorMessage(result) == false,
368 "Received error response: " + XmlUtil.toString(result.getDocument()) + " to request: "
369 + XmlUtil.toString(getMessage.getDocument()));
371 netconfClient.close();
372 LOG.info("Client with session id {}: ended", sessionId);
373 } catch (final Exception e) {
374 throw new IllegalStateException(Thread.currentThread().getName(), e);
378 private NetconfClientConfiguration getClientConfig() {
379 final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
380 b.withAddress(netconfAddress);
381 b.withAdditionalHeader(new NetconfHelloMessageAdditionalHeader("uname", "10.10.10.1", "830", "tcp",
383 b.withSessionListener(new SimpleNetconfClientSessionListener());
384 b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE,
385 NetconfClientConfigurationBuilder.DEFAULT_CONNECTION_TIMEOUT_MILLIS));