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