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.Function;
14 import com.google.common.base.Joiner;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Stopwatch;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Lists;
19 import com.google.common.io.Files;
20 import io.netty.channel.nio.NioEventLoopGroup;
21 import io.netty.util.HashedWheelTimer;
22 import io.netty.util.Timer;
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.Future;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.TimeoutException;
32 import net.sourceforge.argparse4j.inf.ArgumentParser;
33 import net.sourceforge.argparse4j.inf.ArgumentParserException;
34 import org.opendaylight.controller.netconf.api.NetconfMessage;
35 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
36 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
37 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
38 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
39 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.CommitInput;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.EditConfigInput;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.w3c.dom.Document;
46 import org.w3c.dom.Element;
47 import org.w3c.dom.Node;
48 import org.xml.sax.SAXException;
50 public final class StressClient {
52 private static final Logger LOG = LoggerFactory.getLogger(StressClient.class);
54 static final QName COMMIT_QNAME = QName.create(CommitInput.QNAME, "commit");
55 public static final NetconfMessage COMMIT_MSG;
59 COMMIT_MSG = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"commit-batch\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
62 } catch (SAXException | IOException e) {
63 throw new ExceptionInInitializerError(e);
67 static final QName EDIT_QNAME = QName.create(EditConfigInput.QNAME, "edit-config");
68 static final org.w3c.dom.Document editBlueprint;
72 editBlueprint = XmlUtil.readXmlToDocument(
73 "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
74 " <edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
78 " <default-operation>none</default-operation>" +
82 } catch (SAXException | IOException e) {
83 throw new ExceptionInInitializerError(e);
87 private static final String MSG_ID_PLACEHOLDER_REGEX = "\\{MSG_ID\\}";
88 private static final String PHYS_ADDR_PLACEHOLDER_REGEX = "\\{PHYS_ADDR\\}";
90 public static void main(final String[] args) {
91 final Parameters params = parseArgs(args, Parameters.getParser());
96 // Thread.sleep(10000);
97 // } catch (final InterruptedException e) {
98 // e.printStackTrace();
101 final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
102 root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
104 int threadAmount = params.threadAmount;
105 LOG.info("thread amount: " + threadAmount);
106 int requestsPerThread = params.editCount / params.threadAmount;
107 LOG.info("requestsPerThread: " + requestsPerThread);
108 int leftoverRequests = params.editCount % params.threadAmount;
109 LOG.info("leftoverRequests: " + leftoverRequests);
112 LOG.info("Preparing messages");
113 // Prepare all msgs up front
114 final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount);
115 for (int i = 0; i < threadAmount; i++) {
116 if (i != threadAmount - 1) {
117 allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread));
119 allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests));
124 final String editContentString;
126 editContentString = Files.toString(params.editContent, Charsets.UTF_8);
127 } catch (IOException e) {
128 throw new IllegalArgumentException("Cannot read content of " + params.editContent);
131 for (int i = 0; i < threadAmount; i++) {
132 final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i);
134 if (i == threadAmount - 1) {
135 padding = leftoverRequests;
137 for (int j = 0; j < requestsPerThread + padding; j++) {
138 LOG.debug("id: " + (i * requestsPerThread + j));
139 preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString));
143 final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
144 final Timer timer = new HashedWheelTimer();
146 final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer);
148 final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
149 for (List<NetconfMessage> messages : allPreparedMessages) {
150 callables.add(new StressClientCallable(params, netconfClientDispatcher, messages));
153 final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);
155 LOG.info("Starting stress test");
156 final Stopwatch started = Stopwatch.createStarted();
158 final List<Future<Boolean>> futures = executorService.invokeAll(callables);
159 for (Future<Boolean> future : futures) {
161 future.get(4L, TimeUnit.MINUTES);
162 } catch (ExecutionException | TimeoutException e) {
163 throw new RuntimeException(e);
166 executorService.shutdownNow();
167 } catch (InterruptedException e) {
168 throw new RuntimeException("Unable to execute requests", e);
172 LOG.info("FINISHED. Execution time: {}", started);
173 LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
178 nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
179 } catch (InterruptedException | ExecutionException | TimeoutException e) {
180 LOG.warn("Unable to close executor properly", e);
184 private static NetconfMessage prepareMessage(final int id, final String editContentString) {
185 final Document msg = XmlUtil.createDocumentCopy(editBlueprint);
186 msg.getDocumentElement().setAttribute("message-id", Integer.toString(id));
187 final NetconfMessage netconfMessage = new NetconfMessage(msg);
189 final Element editContentElement;
191 // Insert message id where needed
192 String specificEditContent = editContentString.replaceAll(MSG_ID_PLACEHOLDER_REGEX, Integer.toString(id));
194 specificEditContent =
195 specificEditContent.replaceAll(PHYS_ADDR_PLACEHOLDER_REGEX, getMac(id));
197 editContentElement = XmlUtil.readXmlToElement(specificEditContent);
198 final Node config = ((Element) msg.getDocumentElement().getElementsByTagName("edit-config").item(0)).
199 getElementsByTagName("config").item(0);
200 config.appendChild(msg.importNode(editContentElement, true));
201 } catch (final IOException | SAXException e) {
202 throw new IllegalArgumentException("Edit content file is unreadable", e);
205 return netconfMessage;
208 private static NetconfClientDispatcherImpl configureClientDispatcher(final Parameters params, final NioEventLoopGroup nioGroup, final Timer timer) {
209 final NetconfClientDispatcherImpl netconfClientDispatcher;
211 if(params.legacyFraming) {
212 netconfClientDispatcher= ConfigurableClientDispatcher.createLegacyExi(nioGroup, nioGroup, timer);
214 netconfClientDispatcher = ConfigurableClientDispatcher.createChunkedExi(nioGroup, nioGroup, timer);
217 if(params.legacyFraming) {
218 netconfClientDispatcher = ConfigurableClientDispatcher.createLegacy(nioGroup, nioGroup, timer);
220 netconfClientDispatcher = ConfigurableClientDispatcher.createChunked(nioGroup, nioGroup, timer);
223 return netconfClientDispatcher;
226 private static String getMac(final int i) {
227 final String hex = Integer.toHexString(i);
228 final Iterable<String> macGroups = Splitter.fixedLength(2).split(hex);
230 final int additional = 6 - Iterables.size(macGroups);
231 final ArrayList<String> additionalGroups = Lists.newArrayListWithCapacity(additional);
232 for (int j = 0; j < additional; j++) {
233 additionalGroups.add("00");
235 return Joiner.on(':').join(Iterables.concat(Iterables.transform(macGroups, new Function<String, String>() {
237 public String apply(final String input) {
238 return input.length() == 1 ? input + "0" : input;
240 }), additionalGroups));
243 private static Parameters parseArgs(final String[] args, final ArgumentParser parser) {
244 final Parameters opt = new Parameters();
246 parser.parseArgs(args, opt);
248 } catch (final ArgumentParserException e) {
249 parser.handleError(e);
257 static class LoggingRemoteDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
259 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities, final NetconfDeviceCommunicator netconfDeviceCommunicator) {
260 LOG.info("Session established");
264 public void onRemoteSessionDown() {
265 LOG.info("Session down");
269 public void onRemoteSessionFailed(final Throwable throwable) {
270 LOG.info("Session failed");
274 public void onNotification(final NetconfMessage notification) {
275 LOG.info("Notification received: {}", notification.toString());