Rename tools packages to org.opendaylight.netconf
[netconf.git] / opendaylight / netconf / tools / netconf-testtool / src / main / java / org / opendaylight / netconf / test / tool / client / stress / StressClient.java
1 /*
2  * Copyright (c) 2015 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.test.tool.client.stress;
10
11 import ch.qos.logback.classic.Level;
12 import com.google.common.base.Charsets;
13 import com.google.common.base.Stopwatch;
14 import com.google.common.io.Files;
15 import io.netty.channel.nio.NioEventLoopGroup;
16 import io.netty.util.HashedWheelTimer;
17 import io.netty.util.Timer;
18 import java.io.IOException;
19 import java.util.ArrayList;
20 import java.util.List;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.ExecutorService;
23 import java.util.concurrent.Executors;
24 import java.util.concurrent.Future;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.TimeoutException;
27 import net.sourceforge.argparse4j.inf.ArgumentParser;
28 import net.sourceforge.argparse4j.inf.ArgumentParserException;
29 import org.opendaylight.controller.config.util.xml.XmlUtil;
30 import org.opendaylight.netconf.api.NetconfMessage;
31 import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
32 import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandler;
33 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
34 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
35 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
36 import org.opendaylight.netconf.test.tool.TestToolUtils;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.CommitInput;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.EditConfigInput;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.w3c.dom.Document;
43 import org.w3c.dom.Element;
44 import org.w3c.dom.Node;
45 import org.xml.sax.SAXException;
46
47 public final class StressClient {
48
49     private static final Logger LOG = LoggerFactory.getLogger(StressClient.class);
50
51     static final QName COMMIT_QNAME = QName.create(CommitInput.QNAME, "commit");
52     public static final NetconfMessage COMMIT_MSG;
53
54     static {
55         try {
56             COMMIT_MSG = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"commit-batch\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
57                     "    <commit/>\n" +
58                     "</rpc>"));
59         } catch (SAXException | IOException e) {
60             throw new ExceptionInInitializerError(e);
61         }
62     }
63
64     static final QName EDIT_QNAME = QName.create(EditConfigInput.QNAME, "edit-config");
65     static final org.w3c.dom.Document editBlueprint;
66
67     static {
68         try {
69             editBlueprint = XmlUtil.readXmlToDocument(
70                     "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
71                             "    <edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
72                             "        <target>\n" +
73                             "            <candidate/>\n" +
74                             "        </target>\n" +
75                             "        <default-operation>none</default-operation>" +
76                             "        <config/>\n" +
77                             "    </edit-config>\n" +
78                             "</rpc>");
79         } catch (SAXException | IOException e) {
80             throw new ExceptionInInitializerError(e);
81         }
82     }
83
84     private static final String MSG_ID_PLACEHOLDER_REGEX = "\\{MSG_ID\\}";
85     private static final String PHYS_ADDR_PLACEHOLDER = "{PHYS_ADDR}";
86
87     private static long macStart = 0xAABBCCDD0000L;
88
89     public static void main(final String[] args) {
90
91         final Parameters params = parseArgs(args, Parameters.getParser());
92         params.validate();
93
94         final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
95         root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
96
97         final int threadAmount = params.threadAmount;
98         LOG.info("thread amount: " + threadAmount);
99         final int requestsPerThread = params.editCount / params.threadAmount;
100         LOG.info("requestsPerThread: " + requestsPerThread);
101         final int leftoverRequests = params.editCount % params.threadAmount;
102         LOG.info("leftoverRequests: " + leftoverRequests);
103
104
105         LOG.info("Preparing messages");
106         // Prepare all msgs up front
107         final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount);
108         for (int i = 0; i < threadAmount; i++) {
109             if (i != threadAmount - 1) {
110                 allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread));
111             } else {
112                 allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests));
113             }
114         }
115
116
117         final String editContentString;
118         try {
119             editContentString = Files.toString(params.editContent, Charsets.UTF_8);
120         } catch (final IOException e) {
121             throw new IllegalArgumentException("Cannot read content of " + params.editContent);
122         }
123
124         for (int i = 0; i < threadAmount; i++) {
125             final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i);
126             int padding = 0;
127             if (i == threadAmount - 1) {
128                 padding = leftoverRequests;
129             }
130             for (int j = 0; j < requestsPerThread + padding; j++) {
131                 LOG.debug("id: " + (i * requestsPerThread + j));
132                 preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString));
133             }
134         }
135
136         final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
137         final Timer timer = new HashedWheelTimer();
138
139         final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer);
140
141         final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
142         for (final List<NetconfMessage> messages : allPreparedMessages) {
143             callables.add(new StressClientCallable(params, netconfClientDispatcher, messages));
144         }
145
146         final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);
147
148         LOG.info("Starting stress test");
149         final Stopwatch started = Stopwatch.createStarted();
150         try {
151             final List<Future<Boolean>> futures = executorService.invokeAll(callables);
152             for (final Future<Boolean> future : futures) {
153                 try {
154                     future.get(4L, TimeUnit.MINUTES);
155                 } catch (ExecutionException | TimeoutException e) {
156                     throw new RuntimeException(e);
157                 }
158             }
159             executorService.shutdownNow();
160         } catch (final InterruptedException e) {
161             throw new RuntimeException("Unable to execute requests", e);
162         }
163         started.stop();
164
165         LOG.info("FINISHED. Execution time: {}", started);
166         LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
167
168         // Cleanup
169         timer.stop();
170         try {
171             nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
172         } catch (InterruptedException | ExecutionException | TimeoutException e) {
173             LOG.warn("Unable to close executor properly", e);
174         }
175         //stop the underlying ssh thread that gets spawned if we use ssh
176         if (params.ssh) {
177             AsyncSshHandler.DEFAULT_CLIENT.stop();
178         }
179     }
180
181     static NetconfMessage prepareMessage(final int id, final String editContentString) {
182         final Document msg = XmlUtil.createDocumentCopy(editBlueprint);
183         msg.getDocumentElement().setAttribute("message-id", Integer.toString(id));
184         final NetconfMessage netconfMessage = new NetconfMessage(msg);
185
186         final Element editContentElement;
187         try {
188             // Insert message id where needed
189             String specificEditContent = editContentString.replaceAll(MSG_ID_PLACEHOLDER_REGEX, Integer.toString(id));
190
191             final StringBuilder stringBuilder = new StringBuilder(specificEditContent);
192             int idx = stringBuilder.indexOf(PHYS_ADDR_PLACEHOLDER);
193             while (idx!= -1) {
194                 stringBuilder.replace(idx, idx + PHYS_ADDR_PLACEHOLDER.length(), TestToolUtils.getMac(macStart++));
195                 idx = stringBuilder.indexOf(PHYS_ADDR_PLACEHOLDER);
196             }
197             specificEditContent = stringBuilder.toString();
198
199             editContentElement = XmlUtil.readXmlToElement(specificEditContent);
200             final Node config = ((Element) msg.getDocumentElement().getElementsByTagName("edit-config").item(0)).
201                     getElementsByTagName("config").item(0);
202             config.appendChild(msg.importNode(editContentElement, true));
203         } catch (final IOException | SAXException e) {
204             throw new IllegalArgumentException("Edit content file is unreadable", e);
205         }
206
207         return netconfMessage;
208     }
209
210     private static NetconfClientDispatcherImpl configureClientDispatcher(final Parameters params, final NioEventLoopGroup nioGroup, final Timer timer) {
211         final NetconfClientDispatcherImpl netconfClientDispatcher;
212         if(params.exi) {
213             if(params.legacyFraming) {
214                 netconfClientDispatcher= ConfigurableClientDispatcher.createLegacyExi(nioGroup, nioGroup, timer);
215             } else {
216                 netconfClientDispatcher = ConfigurableClientDispatcher.createChunkedExi(nioGroup, nioGroup, timer);
217             }
218         } else {
219             if(params.legacyFraming) {
220                 netconfClientDispatcher = ConfigurableClientDispatcher.createLegacy(nioGroup, nioGroup, timer);
221             } else {
222                 netconfClientDispatcher = ConfigurableClientDispatcher.createChunked(nioGroup, nioGroup, timer);
223             }
224         }
225         return netconfClientDispatcher;
226     }
227
228     private static Parameters parseArgs(final String[] args, final ArgumentParser parser) {
229         final Parameters opt = new Parameters();
230         try {
231             parser.parseArgs(args, opt);
232             return opt;
233         } catch (final ArgumentParserException e) {
234             parser.handleError(e);
235         }
236
237         System.exit(1);
238         return null;
239     }
240
241
242     static class LoggingRemoteDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
243         @Override
244         public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities, final NetconfDeviceCommunicator netconfDeviceCommunicator) {
245             LOG.info("Session established");
246         }
247
248         @Override
249         public void onRemoteSessionDown() {
250             LOG.info("Session down");
251         }
252
253         @Override
254         public void onRemoteSessionFailed(final Throwable throwable) {
255             LOG.info("Session failed");
256         }
257
258         @Override
259         public void onNotification(final NetconfMessage notification) {
260             LOG.info("Notification received: {}", notification.toString());
261         }
262     }
263
264 }