2 * Copyright (c) 2015 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.test.tool.client.stress;
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.security.Provider;
20 import java.security.Security;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.ExecutorService;
25 import java.util.concurrent.Executors;
26 import java.util.concurrent.Future;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.TimeoutException;
29 import net.sourceforge.argparse4j.inf.ArgumentParser;
30 import net.sourceforge.argparse4j.inf.ArgumentParserException;
31 import org.bouncycastle.jce.provider.BouncyCastleProvider;
32 import org.opendaylight.controller.netconf.api.NetconfMessage;
33 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
34 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandler;
35 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
36 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
37 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
38 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.CommitInput;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.EditConfigInput;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Document;
45 import org.w3c.dom.Element;
46 import org.w3c.dom.Node;
47 import org.xml.sax.SAXException;
49 public final class StressClient {
51 private static final Logger LOG = LoggerFactory.getLogger(StressClient.class);
53 static final QName COMMIT_QNAME = QName.create(CommitInput.QNAME, "commit");
54 public static final NetconfMessage COMMIT_MSG;
58 COMMIT_MSG = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"commit-batch\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
61 } catch (SAXException | IOException e) {
62 throw new ExceptionInInitializerError(e);
66 static final QName EDIT_QNAME = QName.create(EditConfigInput.QNAME, "edit-config");
67 static final org.w3c.dom.Document editBlueprint;
71 editBlueprint = XmlUtil.readXmlToDocument(
72 "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
73 " <edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
77 " <default-operation>none</default-operation>" +
81 } catch (SAXException | IOException e) {
82 throw new ExceptionInInitializerError(e);
86 private static final String MSG_ID_PLACEHOLDER_REGEX = "\\{MSG_ID\\}";
87 private static final String PHYS_ADDR_PLACEHOLDER = "{PHYS_ADDR}";
89 private static long macStart = 0xAABBCCDD0000L;
91 public static void main(final String[] args) {
93 final Parameters params = parseArgs(args, Parameters.getParser());
96 final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
97 root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
99 final int threadAmount = params.threadAmount;
100 LOG.info("thread amount: " + threadAmount);
101 final int requestsPerThread = params.editCount / params.threadAmount;
102 LOG.info("requestsPerThread: " + requestsPerThread);
103 final int leftoverRequests = params.editCount % params.threadAmount;
104 LOG.info("leftoverRequests: " + leftoverRequests);
107 LOG.info("Preparing messages");
108 // Prepare all msgs up front
109 final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount);
110 for (int i = 0; i < threadAmount; i++) {
111 if (i != threadAmount - 1) {
112 allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread));
114 allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests));
119 final String editContentString;
121 editContentString = Files.toString(params.editContent, Charsets.UTF_8);
122 } catch (final IOException e) {
123 throw new IllegalArgumentException("Cannot read content of " + params.editContent);
126 for (int i = 0; i < threadAmount; i++) {
127 final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i);
129 if (i == threadAmount - 1) {
130 padding = leftoverRequests;
132 for (int j = 0; j < requestsPerThread + padding; j++) {
133 LOG.debug("id: " + (i * requestsPerThread + j));
134 preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString));
138 final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
139 final Timer timer = new HashedWheelTimer();
141 final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer);
143 final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
144 for (final List<NetconfMessage> messages : allPreparedMessages) {
145 callables.add(new StressClientCallable(params, netconfClientDispatcher, messages));
148 final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);
150 LOG.info("Starting stress test");
151 final Stopwatch started = Stopwatch.createStarted();
153 final List<Future<Boolean>> futures = executorService.invokeAll(callables);
154 for (final Future<Boolean> future : futures) {
156 future.get(4L, TimeUnit.MINUTES);
157 } catch (ExecutionException | TimeoutException e) {
158 throw new RuntimeException(e);
161 executorService.shutdownNow();
162 } catch (final InterruptedException e) {
163 throw new RuntimeException("Unable to execute requests", e);
167 LOG.info("FINISHED. Execution time: {}", started);
168 LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
173 nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
174 } catch (InterruptedException | ExecutionException | TimeoutException e) {
175 LOG.warn("Unable to close executor properly", e);
177 //stop the underlying ssh thread that gets spawned if we use ssh
179 AsyncSshHandler.DEFAULT_CLIENT.stop();
183 static NetconfMessage prepareMessage(final int id, final String editContentString) {
184 final Document msg = XmlUtil.createDocumentCopy(editBlueprint);
185 msg.getDocumentElement().setAttribute("message-id", Integer.toString(id));
186 final NetconfMessage netconfMessage = new NetconfMessage(msg);
188 final Element editContentElement;
190 // Insert message id where needed
191 String specificEditContent = editContentString.replaceAll(MSG_ID_PLACEHOLDER_REGEX, Integer.toString(id));
193 final StringBuilder stringBuilder = new StringBuilder(specificEditContent);
194 int idx = stringBuilder.indexOf(PHYS_ADDR_PLACEHOLDER);
196 stringBuilder.replace(idx, idx + PHYS_ADDR_PLACEHOLDER.length(), getMac(macStart++));
197 idx = stringBuilder.indexOf(PHYS_ADDR_PLACEHOLDER);
199 specificEditContent = stringBuilder.toString();
201 editContentElement = XmlUtil.readXmlToElement(specificEditContent);
202 final Node config = ((Element) msg.getDocumentElement().getElementsByTagName("edit-config").item(0)).
203 getElementsByTagName("config").item(0);
204 config.appendChild(msg.importNode(editContentElement, true));
205 } catch (final IOException | SAXException e) {
206 throw new IllegalArgumentException("Edit content file is unreadable", e);
209 return netconfMessage;
212 private static NetconfClientDispatcherImpl configureClientDispatcher(final Parameters params, final NioEventLoopGroup nioGroup, final Timer timer) {
213 final NetconfClientDispatcherImpl netconfClientDispatcher;
215 if(params.legacyFraming) {
216 netconfClientDispatcher= ConfigurableClientDispatcher.createLegacyExi(nioGroup, nioGroup, timer);
218 netconfClientDispatcher = ConfigurableClientDispatcher.createChunkedExi(nioGroup, nioGroup, timer);
221 if(params.legacyFraming) {
222 netconfClientDispatcher = ConfigurableClientDispatcher.createLegacy(nioGroup, nioGroup, timer);
224 netconfClientDispatcher = ConfigurableClientDispatcher.createChunked(nioGroup, nioGroup, timer);
227 return netconfClientDispatcher;
230 public static String getMac(long mac) {
231 StringBuilder m = new StringBuilder(Long.toString(mac, 16));
233 for (int i = m.length(); i < 12; i++) {
237 for (int j = m.length() - 2; j >= 2; j-=2) {
244 private static Parameters parseArgs(final String[] args, final ArgumentParser parser) {
245 final Parameters opt = new Parameters();
247 parser.parseArgs(args, opt);
249 } catch (final ArgumentParserException e) {
250 parser.handleError(e);
258 static class LoggingRemoteDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
260 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities, final NetconfDeviceCommunicator netconfDeviceCommunicator) {
261 LOG.info("Session established");
265 public void onRemoteSessionDown() {
266 LOG.info("Session down");
270 public void onRemoteSessionFailed(final Throwable throwable) {
271 LOG.info("Session failed");
275 public void onNotification(final NetconfMessage notification) {
276 LOG.info("Notification received: {}", notification.toString());