2 * Copyright (c) 2016 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.netconf.test.tool;
11 import static com.google.common.base.Preconditions.checkArgument;
13 import com.google.common.base.Preconditions;
14 import com.google.common.io.CharStreams;
15 import com.google.common.io.Files;
16 import java.io.BufferedReader;
18 import java.io.FileReader;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22 import java.lang.reflect.Field;
23 import java.nio.charset.StandardCharsets;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.StringJoiner;
29 import java.util.concurrent.TimeUnit;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32 import net.sourceforge.argparse4j.ArgumentParsers;
33 import net.sourceforge.argparse4j.annotation.Arg;
34 import net.sourceforge.argparse4j.inf.ArgumentParser;
35 import net.sourceforge.argparse4j.inf.ArgumentParserException;
37 public class TesttoolParameters {
39 private static final String HOST_KEY = "{HOST}";
40 private static final String PORT_KEY = "{PORT}";
41 private static final String TCP_ONLY = "{TCP_ONLY}";
42 private static final String ADDRESS_PORT = "{ADDRESS:PORT}";
43 private static final String dest = "http://{ADDRESS:PORT}/restconf/config/network-topology:network-topology/topology/topology-netconf/";
44 private static final Pattern YANG_FILENAME_PATTERN = Pattern.compile("(?<name>.*)@(?<revision>\\d{4}-\\d{2}-\\d{2})\\.yang");
45 private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
47 private static final String RESOURCE = "/config-template.json";
48 @Arg(dest = "edit-content")
49 public File editContent;
52 @Arg(dest = "thread-amount")
53 public int threadAmount;
54 @Arg(dest = "throttle")
57 public ArrayList<String> auth;
58 @Arg(dest = "controller-destination")
59 public String controllerDestination;
60 @Arg(dest = "schemas-dir")
61 public File schemasDir;
62 @Arg(dest = "devices-count")
63 public int deviceCount;
64 @Arg(dest = "devices-per-port")
65 public int devicesPerPort;
66 @Arg(dest = "starting-port")
67 public int startingPort;
68 @Arg(dest = "generate-config-connection-timeout")
69 public int generateConfigsTimeout;
70 @Arg(dest = "generate-config-address")
71 public String generateConfigsAddress;
72 @Arg(dest = "distro-folder")
73 public File distroFolder;
74 @Arg(dest = "generate-configs-batch-size")
75 public int generateConfigBatchSize;
82 @Arg(dest = "notification-file")
83 public File notificationFile;
86 @Arg(dest = "initial-config-xml-file")
87 public File initialConfigXMLFile;
88 @Arg(dest = "time-out")
90 private InputStream stream;
95 @Arg(dest = "thread-pool-size")
96 public int threadPoolSize;
98 static ArgumentParser getParser() {
99 final ArgumentParser parser = ArgumentParsers.newArgumentParser("netconf testtool");
101 parser.description("netconf testtool");
103 parser.addArgument("--edit-content")
105 .dest("edit-content");
107 parser.addArgument("--async-requests")
112 parser.addArgument("--thread-amount")
115 .dest("thread-amount")
116 .help("The number of threads to use for configuring devices.");
118 parser.addArgument("--throttle")
121 .help("Maximum amount of async requests that can be open at a time, " +
122 "with mutltiple threads this gets divided among all threads")
125 parser.addArgument("--auth")
127 .help("Username and password for HTTP basic authentication in order username password.")
130 parser.addArgument("--controller-destination")
132 .help("Ip address and port of controller. Must be in following format <ip>:<port> " +
133 "if available it will be used for spawning netconf connectors via topology configuration as " +
134 "a part of URI. Example (http://<controller destination>/restconf/config/network-topology:network-topology/topology/topology-netconf/node/<node-id>)" +
135 "otherwise it will just start simulated devices and skip the execution of PUT requests")
136 .dest("controller-destination");
138 parser.addArgument("--device-count")
141 .help("Number of simulated netconf devices to spin. This is the number of actual ports open for the devices.")
142 .dest("devices-count");
144 parser.addArgument("--devices-per-port")
147 .help("Amount of config files generated per port to spoof more devices then are actually running")
148 .dest("devices-per-port");
150 parser.addArgument("--schemas-dir")
152 .help("Directory containing yang schemas to describe simulated devices. Some schemas e.g. netconf monitoring and inet types are included by default")
153 .dest("schemas-dir");
155 parser.addArgument("--notification-file")
157 .help("Xml file containing notifications that should be sent to clients after create subscription is called")
158 .dest("notification-file");
160 parser.addArgument("--initial-config-xml-file")
162 .help("Xml file containing initial simulatted configuration to be returned via get-config rpc")
163 .dest("initial-config-xml-file");
165 parser.addArgument("--starting-port")
168 .help("First port for simulated device. Each other device will have previous+1 port number")
169 .dest("starting-port");
171 parser.addArgument("--generate-config-connection-timeout")
173 .setDefault((int) TimeUnit.MINUTES.toMillis(30))
174 .help("Timeout to be generated in initial config files")
175 .dest("generate-config-connection-timeout");
177 parser.addArgument("--generate-config-address")
179 .setDefault("127.0.0.1")
180 .help("Address to be placed in generated configs")
181 .dest("generate-config-address");
183 parser.addArgument("--generate-configs-batch-size")
186 .help("Number of connector configs per generated file")
187 .dest("generate-configs-batch-size");
189 parser.addArgument("--distribution-folder")
191 .help("Directory where the karaf distribution for controller is located")
192 .dest("distro-folder");
194 parser.addArgument("--ssh")
197 .help("Whether to use ssh for transport or just pure tcp")
200 parser.addArgument("--exi")
203 .help("Whether to use exi to transport xml content")
206 parser.addArgument("--debug")
209 .help("Whether to use debug log level instead of INFO")
212 parser.addArgument("--md-sal")
215 .help("Whether to use md-sal datastore instead of default simulated datastore.")
218 parser.addArgument("--time-out")
221 .help("the maximum time in seconds for executing each PUT request")
224 parser.addArgument("-ip")
226 .setDefault("0.0.0.0")
227 .help("Ip address which will be used for creating a socket address." +
228 "It can either be a machine name, such as " +
229 "java.sun.com, or a textual representation of its IP address.")
232 parser.addArgument("--thread-pool-size")
235 .help("The number of threads to keep in the pool, when creating a device simulator. Even if they are idle.")
236 .dest("thread-pool-size");
241 public static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) {
242 final TesttoolParameters opt = new TesttoolParameters();
244 parser.parseArgs(args, opt);
246 } catch (final ArgumentParserException e) {
247 parser.handleError(e);
254 private static String modifyMessage(final StringBuilder payloadBuilder, final int payloadPosition, final int size) {
256 return payloadBuilder.toString();
259 if (payloadPosition == 0) {
260 payloadBuilder.insert(payloadBuilder.toString().indexOf('{', 2), "[");
261 payloadBuilder.replace(payloadBuilder.length() - 1, payloadBuilder.length(), ",");
262 } else if (payloadPosition + 1 == size) {
263 payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
264 payloadBuilder.insert(payloadBuilder.toString().indexOf('}', 2) + 1, "]");
266 payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
267 payloadBuilder.replace(payloadBuilder.length() - 2, payloadBuilder.length() - 1, ",");
268 payloadBuilder.deleteCharAt(payloadBuilder.toString().lastIndexOf('}'));
270 return payloadBuilder.toString();
274 if (editContent == null) {
275 stream = TesttoolParameters.class.getResourceAsStream(RESOURCE);
277 Preconditions.checkArgument(!editContent.isDirectory(), "Edit content file is a dir");
278 Preconditions.checkArgument(editContent.canRead(), "Edit content file is unreadable");
281 if (controllerDestination != null) {
282 Preconditions.checkArgument(controllerDestination.contains(":"), "Controller Destination needs to be in a following format <ip>:<port>");
283 final String[] parts = controllerDestination.split(Pattern.quote(":"));
284 Preconditions.checkArgument(Integer.parseInt(parts[1]) > 0, "Port =< 0");
287 checkArgument(deviceCount > 0, "Device count has to be > 0");
288 checkArgument(startingPort > 1023, "Starting port has to be > 1023");
289 checkArgument(devicesPerPort > 0, "Atleast one device per port needed");
291 if (schemasDir != null) {
292 checkArgument(schemasDir.exists(), "Schemas dir has to exist");
293 checkArgument(schemasDir.isDirectory(), "Schemas dir has to be a directory");
294 checkArgument(schemasDir.canRead(), "Schemas dir has to be readable");
296 final List<File> files = Arrays.asList(schemasDir.listFiles());
297 for (final File file : files) {
298 final Matcher matcher = YANG_FILENAME_PATTERN.matcher(file.getName());
299 if (!matcher.matches()) {
300 final BufferedReader reader;
302 reader = new BufferedReader(new FileReader(file));
303 String line = reader.readLine();
304 while (!DATE_PATTERN.matcher(line).find()) {
305 line = reader.readLine();
307 final Matcher m = DATE_PATTERN.matcher(line);
310 String moduleName = file.getAbsolutePath();
311 if (file.getName().endsWith(".yang")) {
312 moduleName = moduleName.substring(0, moduleName.length() - 5);
314 final String revision = m.group(1);
315 final String correctName = moduleName + "@" + revision + ".yang";
316 final File correctNameFile = new File(correctName);
317 file.renameTo(correctNameFile);
320 } catch (final IOException e) {
328 public ArrayList<ArrayList<Execution.DestToPayload>> getThreadsPayloads(final List<Integer> openDevices) {
329 final String editContentString;
331 if (stream == null) {
332 editContentString = Files.toString(editContent, StandardCharsets.UTF_8);
334 editContentString = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
336 } catch (final IOException e) {
337 throw new IllegalArgumentException("Cannot read content of " + editContent);
341 Iterator<Integer> iterator;
343 final ArrayList<ArrayList<Execution.DestToPayload>> allThreadsPayloads = new ArrayList<>();
344 if (generateConfigBatchSize > 1) {
346 final int batchedRequests = openDevices.size() / generateConfigBatchSize;
347 final int batchedRequestsPerThread = batchedRequests / threadAmount;
348 final int leftoverBatchedRequests = (batchedRequests) % threadAmount;
349 final int leftoverRequests = openDevices.size() - (batchedRequests * generateConfigBatchSize);
351 final StringBuilder destBuilder = new StringBuilder(dest);
352 destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT), destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(), controllerDestination);
354 for (int l = 0; l < threadAmount; l++) {
355 from = l * (batchedRequests * batchedRequestsPerThread);
356 to = from + (batchedRequests * batchedRequestsPerThread);
357 iterator = openDevices.subList(from, to).iterator();
358 allThreadsPayloads.add(createBatchedPayloads(batchedRequestsPerThread, iterator, editContentString, destBuilder.toString()));
360 ArrayList<Execution.DestToPayload> payloads = null;
361 if (leftoverBatchedRequests > 0) {
362 from = threadAmount * (batchedRequests * batchedRequestsPerThread);
363 to = from + (batchedRequests * batchedRequestsPerThread);
364 iterator = openDevices.subList(from, to).iterator();
365 payloads = createBatchedPayloads(leftoverBatchedRequests, iterator, editContentString, destBuilder.toString());
369 for (int j = 0; j < leftoverRequests; j++) {
370 from = openDevices.size() - leftoverRequests;
371 to = openDevices.size();
372 iterator = openDevices.subList(from, to).iterator();
373 final StringBuilder payloadBuilder = new StringBuilder(prepareMessage(iterator.next(), editContentString));
374 payload += modifyMessage(payloadBuilder, j, leftoverRequests);
376 if (leftoverRequests > 0 || leftoverBatchedRequests > 0) {
378 if (payloads != null) {
379 payloads.add(new Execution.DestToPayload(destBuilder.toString(), payload));
381 allThreadsPayloads.add(payloads);
384 final int requestPerThreads = openDevices.size() / threadAmount;
385 final int leftoverRequests = openDevices.size() % threadAmount;
387 for (int i = 0; i < threadAmount; i++) {
388 from = i * requestPerThreads;
389 to = from + requestPerThreads;
390 iterator = openDevices.subList(from, to).iterator();
391 allThreadsPayloads.add(createPayloads(iterator, editContentString));
394 if (leftoverRequests > 0) {
395 from = (threadAmount) * requestPerThreads;
396 to = from + leftoverRequests;
397 iterator = openDevices.subList(from, to).iterator();
398 allThreadsPayloads.add(createPayloads(iterator, editContentString));
401 return allThreadsPayloads;
404 private String prepareMessage(final int openDevice, final String editContentString) {
405 final StringBuilder messageBuilder = new StringBuilder(editContentString);
407 if (editContentString.contains(HOST_KEY)) {
408 messageBuilder.replace(messageBuilder.indexOf(HOST_KEY), messageBuilder.indexOf(HOST_KEY) + HOST_KEY.length(), generateConfigsAddress);
410 if (editContentString.contains(PORT_KEY)) {
411 while (messageBuilder.indexOf(PORT_KEY) != -1)
412 messageBuilder.replace(messageBuilder.indexOf(PORT_KEY), messageBuilder.indexOf(PORT_KEY) + PORT_KEY.length(), Integer.toString(openDevice));
414 if (editContentString.contains(TCP_ONLY)) {
415 messageBuilder.replace(messageBuilder.indexOf(TCP_ONLY), messageBuilder.indexOf(TCP_ONLY) + TCP_ONLY.length(), Boolean.toString(!ssh));
417 return messageBuilder.toString();
420 private ArrayList<Execution.DestToPayload> createPayloads(final Iterator<Integer> openDevices, final String editContentString) {
421 final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
423 while (openDevices.hasNext()) {
424 final StringBuilder destBuilder = new StringBuilder(dest);
425 destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT), destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(), controllerDestination);
426 payloads.add(new Execution.DestToPayload(destBuilder.toString(), prepareMessage(openDevices.next(), editContentString)));
431 private ArrayList<Execution.DestToPayload> createBatchedPayloads(final int batchedRequestsCount, final Iterator<Integer> openDevices, final String editContentString,
432 final String destination) {
433 final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
435 for (int i = 0; i < batchedRequestsCount; i++) {
437 for (int j = 0; j < generateConfigBatchSize; j++) {
438 final StringBuilder payloadBuilder = new StringBuilder(prepareMessage(openDevices.next(), editContentString));
439 payload += modifyMessage(payloadBuilder, j, generateConfigBatchSize);
441 payloads.add(new Execution.DestToPayload(destination, payload));
447 public String toString() {
448 final List<Field> fields = Arrays.asList(this.getClass().getDeclaredFields());
449 final StringJoiner joiner = new StringJoiner(", \n", "TesttoolParameters{", "}\n");
451 .filter(field -> field.getAnnotation(Arg.class) != null)
452 .map(this::getFieldString)
453 .forEach(joiner::add);
454 return joiner.toString();
457 private String getFieldString(final Field field) {
459 return field.getName() + "='" + field.get(this) + "'";
460 } catch (final IllegalAccessException e) {
461 return field.getName() + "= UNKNOWN";