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