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
8 package org.opendaylight.netconf.test.tool.client.stress;
10 import ch.qos.logback.classic.Level;
11 import com.google.common.base.Stopwatch;
12 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
13 import io.netty.channel.nio.NioEventLoopGroup;
14 import io.netty.util.HashedWheelTimer;
15 import io.netty.util.Timer;
16 import java.io.IOException;
17 import java.nio.file.Files;
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.ExecutorService;
22 import java.util.concurrent.Executors;
23 import java.util.concurrent.Future;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.TimeoutException;
26 import net.sourceforge.argparse4j.inf.ArgumentParser;
27 import net.sourceforge.argparse4j.inf.ArgumentParserException;
28 import org.opendaylight.netconf.api.messages.NetconfMessage;
29 import org.opendaylight.netconf.api.xml.XmlUtil;
30 import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
31 import org.opendaylight.netconf.client.mdsal.NetconfDeviceCommunicator;
32 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
33 import org.opendaylight.netconf.client.mdsal.api.RemoteDevice;
34 import org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandler;
35 import org.opendaylight.netconf.test.tool.TestToolUtils;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.CommitInput;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.EditConfigInput;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.w3c.dom.Document;
42 import org.w3c.dom.Element;
43 import org.w3c.dom.Node;
44 import org.xml.sax.SAXException;
46 @SuppressFBWarnings("DM_EXIT")
47 public final class StressClient {
48 private static final Logger LOG = LoggerFactory.getLogger(StressClient.class);
50 static final QName COMMIT_QNAME = QName.create(CommitInput.QNAME, "commit");
51 public static final NetconfMessage COMMIT_MSG = new NetconfMessage(readString("""
52 <rpc message-id="commit-batch" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
56 static final QName EDIT_QNAME = QName.create(EditConfigInput.QNAME, "edit-config");
57 static final Document EDIT_CANDIDATE_BLUEPRINT = readString("""
58 <rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
63 <default-operation>none</default-operation>
67 static final Document EDIT_RUNNING_BLUEPRINT = readString("""
68 <rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
73 <default-operation>none</default-operation>
78 private static Document readString(final String str) {
80 return XmlUtil.readXmlToDocument(str);
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 private static Parameters params;
93 private StressClient() {
97 public static void main(final String[] args) {
99 params = parseArgs(args, Parameters.getParser());
102 final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
103 .getLogger(Logger.ROOT_LOGGER_NAME);
104 root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
106 final int threadAmount = params.threadAmount;
107 LOG.info("thread amount: {}", threadAmount);
108 final int requestsPerThread = params.editCount / params.threadAmount;
109 LOG.info("requestsPerThread: {}", requestsPerThread);
110 final int leftoverRequests = params.editCount % params.threadAmount;
111 LOG.info("leftoverRequests: {}", leftoverRequests);
113 LOG.info("Preparing messages");
114 // Prepare all msgs up front
115 final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount);
116 for (int i = 0; i < threadAmount; i++) {
117 if (i != threadAmount - 1) {
118 allPreparedMessages.add(new ArrayList<>(requestsPerThread));
120 allPreparedMessages.add(new ArrayList<>(requestsPerThread + leftoverRequests));
125 final String editContentString;
127 editContentString = Files.readString(params.editContent.toPath());
128 } catch (final IOException e) {
129 throw new IllegalArgumentException("Cannot read content of " + params.editContent, e);
132 for (int i = 0; i < threadAmount; i++) {
133 final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i);
135 if (i == threadAmount - 1) {
136 padding = leftoverRequests;
138 for (int j = 0; j < requestsPerThread + padding; j++) {
139 LOG.debug("id: {}", i * requestsPerThread + j);
140 preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString));
144 final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
145 final Timer timer = new HashedWheelTimer();
147 final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(nioGroup, timer);
149 final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
150 for (final List<NetconfMessage> messages : allPreparedMessages) {
151 callables.add(new StressClientCallable(params, netconfClientDispatcher, messages));
154 final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);
156 LOG.info("Starting stress test");
157 final Stopwatch started = Stopwatch.createStarted();
159 final List<Future<Boolean>> futures = executorService.invokeAll(callables);
160 for (final Future<Boolean> future : futures) {
162 future.get(4L, TimeUnit.MINUTES);
163 } catch (ExecutionException | TimeoutException e) {
164 throw new IllegalStateException(e);
167 executorService.shutdownNow();
168 } catch (final InterruptedException e) {
169 throw new IllegalStateException("Unable to execute requests", e);
173 LOG.info("FINISHED. Execution time: {}", started);
174 LOG.info("Requests per second: {}", params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS));
179 nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
180 } catch (InterruptedException | ExecutionException | TimeoutException e) {
181 LOG.warn("Unable to close executor properly", e);
183 //stop the underlying ssh thread that gets spawned if we use ssh
185 AsyncSshHandler.DEFAULT_CLIENT.stop();
189 static NetconfMessage prepareMessage(final int id, final String editContentString) {
190 final Document msg = XmlUtil.createDocumentCopy(
191 params.candidateDatastore ? EDIT_CANDIDATE_BLUEPRINT : EDIT_RUNNING_BLUEPRINT);
192 msg.getDocumentElement().setAttribute("message-id", Integer.toString(id));
193 final NetconfMessage netconfMessage = new NetconfMessage(msg);
195 final Element editContentElement;
197 // Insert message id where needed
198 String specificEditContent = editContentString.replaceAll(MSG_ID_PLACEHOLDER_REGEX, Integer.toString(id));
200 final StringBuilder stringBuilder = new StringBuilder(specificEditContent);
201 int idx = stringBuilder.indexOf(PHYS_ADDR_PLACEHOLDER);
203 stringBuilder.replace(idx, idx + PHYS_ADDR_PLACEHOLDER.length(), TestToolUtils.getMac(macStart++));
204 idx = stringBuilder.indexOf(PHYS_ADDR_PLACEHOLDER);
206 specificEditContent = stringBuilder.toString();
208 editContentElement = XmlUtil.readXmlToElement(specificEditContent);
209 final Node config = ((Element) msg.getDocumentElement().getElementsByTagName("edit-config").item(0))
210 .getElementsByTagName("config").item(0);
211 config.appendChild(msg.importNode(editContentElement, true));
212 } catch (final IOException | SAXException e) {
213 throw new IllegalArgumentException("Edit content file is unreadable", e);
216 return netconfMessage;
219 private static NetconfClientDispatcherImpl configureClientDispatcher(final NioEventLoopGroup nioGroup,
221 final NetconfClientDispatcherImpl netconfClientDispatcher;
223 if (params.legacyFraming) {
224 netconfClientDispatcher = ConfigurableClientDispatcher.createLegacyExi(nioGroup, nioGroup, timer);
226 netconfClientDispatcher = ConfigurableClientDispatcher.createChunkedExi(nioGroup, nioGroup, timer);
228 } else if (params.legacyFraming) {
229 netconfClientDispatcher = ConfigurableClientDispatcher.createLegacy(nioGroup, nioGroup, timer);
231 netconfClientDispatcher = ConfigurableClientDispatcher.createChunked(nioGroup, nioGroup, timer);
233 return netconfClientDispatcher;
236 private static Parameters parseArgs(final String[] args, final ArgumentParser parser) {
237 final Parameters opt = new Parameters();
239 parser.parseArgs(args, opt);
241 } catch (final ArgumentParserException e) {
242 parser.handleError(e);
249 static class LoggingRemoteDevice implements RemoteDevice<NetconfDeviceCommunicator> {
251 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
252 final NetconfDeviceCommunicator netconfDeviceCommunicator) {
253 LOG.info("Session established");
257 public void onRemoteSessionDown() {
258 LOG.info("Session down");
262 public void onNotification(final NetconfMessage notification) {
263 LOG.info("Notification received: {}", notification);