Merge "sal-remoterpc-connector: sync ch.qos.logback:logback-classic version"
[controller.git] / opendaylight / netconf / netconf-impl / src / test / java / org / opendaylight / controller / 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.controller.netconf.impl;
10
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static org.junit.Assert.fail;
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 import io.netty.channel.ChannelFuture;
18 import io.netty.channel.EventLoopGroup;
19 import io.netty.channel.nio.NioEventLoopGroup;
20 import io.netty.util.HashedWheelTimer;
21
22 import java.io.DataOutputStream;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25 import java.lang.management.ManagementFactory;
26 import java.net.InetSocketAddress;
27 import java.net.Socket;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.List;
31 import java.util.Set;
32 import java.util.concurrent.TimeUnit;
33
34 import javax.management.ObjectName;
35
36 import org.apache.commons.io.IOUtils;
37 import org.junit.After;
38 import org.junit.AfterClass;
39 import org.junit.Before;
40 import org.junit.Test;
41 import org.mockito.Mock;
42 import org.mockito.MockitoAnnotations;
43 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
44 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
45 import org.opendaylight.controller.config.yang.store.api.YangStoreService;
46 import org.opendaylight.controller.config.yang.store.api.YangStoreSnapshot;
47 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
48 import org.opendaylight.controller.netconf.api.NetconfMessage;
49 import org.opendaylight.controller.netconf.api.NetconfOperationRouter;
50 import org.opendaylight.controller.netconf.client.NetconfClient;
51 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
52 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
53 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
54 import org.opendaylight.controller.netconf.mapping.api.Capability;
55 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
56 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
57 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationFilter;
58 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
59 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
60 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
61 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64 import org.w3c.dom.Document;
65
66 import com.google.common.base.Optional;
67 import com.google.common.collect.Sets;
68
69 public class ConcurrentClientsTest {
70
71     private static final int CONCURRENCY = 16;
72     private static EventLoopGroup nettyGroup = new NioEventLoopGroup();
73     public static final NetconfClientDispatcher NETCONF_CLIENT_DISPATCHER =
74             new NetconfClientDispatcher( nettyGroup, nettyGroup);
75
76     @Mock
77     private YangStoreService yangStoreService;
78     @Mock
79     private ConfigRegistryJMXClient jmxClient;
80
81     private final InetSocketAddress netconfAddress = new InetSocketAddress("127.0.0.1", 8303);
82
83     static final Logger logger = LoggerFactory.getLogger(ConcurrentClientsTest.class);
84
85     private DefaultCommitNotificationProducer commitNot;
86     private NetconfServerDispatcher dispatch;
87
88     @Mock
89     private SessionMonitoringService monitoring;
90
91     @Before
92     public void setUp() throws Exception {
93         { // init mocks
94             MockitoAnnotations.initMocks(this);
95             final YangStoreSnapshot yStore = mock(YangStoreSnapshot.class);
96             doReturn(yStore).when(this.yangStoreService).getYangStoreSnapshot();
97             doReturn(Collections.emptyMap()).when(yStore).getModuleMXBeanEntryMap();
98
99             final ConfigTransactionJMXClient mockedTCl = mock(ConfigTransactionJMXClient.class);
100             doReturn(mockedTCl).when(this.jmxClient).getConfigTransactionClient(any(ObjectName.class));
101
102             doReturn(Collections.emptySet()).when(jmxClient).lookupConfigBeans();
103         }
104
105         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
106         factoriesListener.onAddNetconfOperationServiceFactory(mockOpF());
107
108         SessionIdProvider idProvider = new SessionIdProvider();
109         NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
110                 new HashedWheelTimer(5000, TimeUnit.MILLISECONDS), factoriesListener, idProvider);
111
112         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
113
114         doNothing().when(monitoring).onSessionUp(any(NetconfServerSession.class));
115         doNothing().when(monitoring).onSessionDown(any(NetconfServerSession.class));
116
117         NetconfServerSessionListenerFactory listenerFactory = new NetconfServerSessionListenerFactory(
118                 factoriesListener, commitNot, idProvider, monitoring);
119         NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(serverNegotiatorFactory, listenerFactory);
120         dispatch = new NetconfServerDispatcher(serverChannelInitializer, nettyGroup, nettyGroup);
121
122         ChannelFuture s = dispatch.createServer(netconfAddress);
123         s.await();
124     }
125
126     @AfterClass
127     public static void tearDownStatic() {
128         nettyGroup.shutdownGracefully();
129     }
130
131     private NetconfOperationServiceFactory mockOpF() {
132         return new NetconfOperationServiceFactory() {
133             @Override
134             public NetconfOperationService createService(long netconfSessionId, String netconfSessionIdForReporting) {
135                 return new NetconfOperationService() {
136                     @Override
137                     public Set<Capability> getCapabilities() {
138                         return Collections.emptySet();
139                     }
140
141                     @Override
142                     public Set<NetconfOperation> getNetconfOperations() {
143                         return Sets.<NetconfOperation> newHashSet(new NetconfOperation() {
144                             @Override
145                             public HandlingPriority canHandle(Document message) {
146                                 return HandlingPriority.getHandlingPriority(Integer.MAX_VALUE);
147                             }
148
149                             @Override
150                             public Document handle(Document message, NetconfOperationRouter operationRouter)
151                                     throws NetconfDocumentedException {
152                                 try {
153                                     return XmlUtil.readXmlToDocument("<test/>");
154                                 } catch (Exception e) {
155                                     throw new RuntimeException(e);
156                                 }
157                             }
158                         });
159                     }
160
161                     @Override
162                     public Set<NetconfOperationFilter> getFilters() {
163                         return Collections.emptySet();
164                     }
165
166                     @Override
167                     public void close() {
168                     }
169                 };
170             }
171         };
172     }
173
174     @After
175     public void cleanUp() throws Exception {
176         commitNot.close();
177     }
178
179     @Test
180     public void multipleClients() throws Exception {
181         List<TestingThread> threads = new ArrayList<>();
182
183         final int attempts = 5;
184         for (int i = 0; i < CONCURRENCY; i++) {
185             TestingThread thread = new TestingThread(String.valueOf(i), attempts);
186             threads.add(thread);
187             thread.start();
188         }
189
190         for (TestingThread thread : threads) {
191             thread.join();
192             if(thread.thrownException.isPresent()) {
193                 Exception exception = thread.thrownException.get();
194                 logger.error("Thread for testing client failed", exception);
195                 fail("Client thread " + thread + " failed: " + exception.getMessage());
196             }
197         }
198     }
199
200     @Test
201     public void synchronizationTest() throws Exception {
202         new BlockingThread("foo").run2();
203     }
204
205     @Test
206     public void multipleBlockingClients() throws Exception {
207         List<BlockingThread> threads = new ArrayList<>();
208         for (int i = 0; i < CONCURRENCY; i++) {
209             BlockingThread thread = new BlockingThread(String.valueOf(i));
210             threads.add(thread);
211             thread.start();
212         }
213
214         for (BlockingThread thread : threads) {
215             thread.join();
216             if(thread.thrownException.isPresent()) {
217                 Exception exception = thread.thrownException.get();
218                 logger.error("Thread for testing client failed", exception);
219                 fail("Client thread " + thread + " failed: " + exception.getMessage());
220             }
221         }
222     }
223
224     class BlockingThread extends Thread {
225         private Optional<Exception> thrownException;
226
227         public BlockingThread(String name) {
228             super("client-" + name);
229         }
230
231         @Override
232         public void run() {
233             try {
234                 run2();
235                 thrownException = Optional.absent();
236             } catch (Exception e) {
237                 thrownException = Optional.of(e);
238             }
239         }
240
241         private void run2() throws Exception {
242             InputStream clientHello = checkNotNull(XmlFileLoader
243                     .getResourceAsStream("netconfMessages/client_hello.xml"));
244             InputStream getConfig = checkNotNull(XmlFileLoader.getResourceAsStream("netconfMessages/getConfig.xml"));
245
246             Socket clientSocket = new Socket(netconfAddress.getHostString(), netconfAddress.getPort());
247             DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
248             InputStreamReader inFromServer = new InputStreamReader(clientSocket.getInputStream());
249
250             StringBuffer sb = new StringBuffer();
251             while (sb.toString().endsWith("]]>]]>") == false) {
252                 sb.append((char) inFromServer.read());
253             }
254             logger.info(sb.toString());
255
256             outToServer.write(IOUtils.toByteArray(clientHello));
257             outToServer.write("]]>]]>".getBytes());
258             outToServer.flush();
259             // Thread.sleep(100);
260             outToServer.write(IOUtils.toByteArray(getConfig));
261             outToServer.write("]]>]]>".getBytes());
262             outToServer.flush();
263             Thread.sleep(100);
264             sb = new StringBuffer();
265             while (sb.toString().endsWith("]]>]]>") == false) {
266                 sb.append((char) inFromServer.read());
267             }
268             logger.info(sb.toString());
269             clientSocket.close();
270         }
271     }
272
273     class TestingThread extends Thread {
274
275         private final String clientId;
276         private final int attempts;
277         private Optional<Exception> thrownException;
278
279         TestingThread(String clientId, int attempts) {
280             this.clientId = clientId;
281             this.attempts = attempts;
282             setName("client-" + clientId);
283         }
284
285         @Override
286         public void run() {
287             try {
288                 final NetconfClient netconfClient = new NetconfClient(clientId, netconfAddress, NETCONF_CLIENT_DISPATCHER);
289                 long sessionId = netconfClient.getSessionId();
290                 logger.info("Client with sessionid {} hello exchanged", sessionId);
291
292                 final NetconfMessage getMessage = XmlFileLoader
293                         .xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
294                 NetconfMessage result = netconfClient.sendMessage(getMessage);
295                 logger.info("Client with sessionid {} got result {}", sessionId, result);
296                 netconfClient.close();
297                 logger.info("Client with session id {} ended", sessionId);
298                 thrownException = Optional.absent();
299             } catch (final Exception e) {
300                 thrownException = Optional.of(e);
301             }
302         }
303     }
304 }