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