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 =
44 "http://{ADDRESS:PORT}/restconf/config/network-topology:network-topology/topology/topology-netconf/";
45 private static final Pattern YANG_FILENAME_PATTERN = Pattern
46 .compile("(?<name>.*)@(?<revision>\\d{4}-\\d{2}-\\d{2})\\.yang");
47 private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
49 private static final String RESOURCE = "/config-template.json";
50 @Arg(dest = "edit-content")
51 public File editContent;
54 @Arg(dest = "thread-amount")
55 public int threadAmount;
56 @Arg(dest = "throttle")
59 public ArrayList<String> auth;
60 @Arg(dest = "controller-destination")
61 public String controllerDestination;
62 @Arg(dest = "schemas-dir")
63 public File schemasDir;
64 @Arg(dest = "devices-count")
65 public int deviceCount;
66 @Arg(dest = "devices-per-port")
67 public int devicesPerPort;
68 @Arg(dest = "starting-port")
69 public int startingPort;
70 @Arg(dest = "generate-config-connection-timeout")
71 public int generateConfigsTimeout;
72 @Arg(dest = "generate-config-address")
73 public String generateConfigsAddress;
74 @Arg(dest = "distro-folder")
75 public File distroFolder;
76 @Arg(dest = "generate-configs-batch-size")
77 public int generateConfigBatchSize;
84 @Arg(dest = "notification-file")
85 public File notificationFile;
88 @Arg(dest = "initial-config-xml-file")
89 public File initialConfigXMLFile;
90 @Arg(dest = "time-out")
92 private InputStream stream;
95 @Arg(dest = "thread-pool-size")
96 public int threadPoolSize;
97 @Arg(dest = "rpc-config")
98 public File rpcConfig;
100 @SuppressWarnings("checkstyle:lineLength")
101 static ArgumentParser getParser() {
102 final ArgumentParser parser = ArgumentParsers.newArgumentParser("netconf testtool");
104 parser.description("netconf testtool");
106 parser.addArgument("--edit-content")
108 .dest("edit-content");
110 parser.addArgument("--async-requests")
115 parser.addArgument("--thread-amount")
118 .dest("thread-amount")
119 .help("The number of threads to use for configuring devices.");
121 parser.addArgument("--throttle")
124 .help("Maximum amount of async requests that can be open at a time, "
125 + "with mutltiple threads this gets divided among all threads")
128 parser.addArgument("--auth")
130 .help("Username and password for HTTP basic authentication in order username password.")
133 parser.addArgument("--controller-destination")
135 .help("Ip address and port of controller. Must be in following format <ip>:<port> "
136 + "if available it will be used for spawning netconf connectors via topology configuration as "
137 + "a part of URI. Example (http://<controller destination>/restconf/config/network-topology:network-topology/topology/topology-netconf/node/<node-id>)"
138 + "otherwise it will just start simulated devices and skip the execution of PUT requests")
139 .dest("controller-destination");
141 parser.addArgument("--device-count")
144 .help("Number of simulated netconf devices to spin. This is the number of actual ports open for the devices.")
145 .dest("devices-count");
147 parser.addArgument("--devices-per-port")
150 .help("Amount of config files generated per port to spoof more devices then are actually running")
151 .dest("devices-per-port");
153 parser.addArgument("--schemas-dir")
155 .help("Directory containing yang schemas to describe simulated devices. Some schemas e.g. netconf monitoring and inet types are included by default")
156 .dest("schemas-dir");
158 parser.addArgument("--notification-file")
160 .help("Xml file containing notifications that should be sent to clients after create subscription is called")
161 .dest("notification-file");
163 parser.addArgument("--initial-config-xml-file")
165 .help("Xml file containing initial simulatted configuration to be returned via get-config rpc")
166 .dest("initial-config-xml-file");
168 parser.addArgument("--starting-port")
171 .help("First port for simulated device. Each other device will have previous+1 port number")
172 .dest("starting-port");
174 parser.addArgument("--generate-config-connection-timeout")
176 .setDefault((int) TimeUnit.MINUTES.toMillis(30))
177 .help("Timeout to be generated in initial config files")
178 .dest("generate-config-connection-timeout");
180 parser.addArgument("--generate-config-address")
182 .setDefault("127.0.0.1")
183 .help("Address to be placed in generated configs")
184 .dest("generate-config-address");
186 parser.addArgument("--generate-configs-batch-size")
189 .help("Number of connector configs per generated file")
190 .dest("generate-configs-batch-size");
192 parser.addArgument("--distribution-folder")
194 .help("Directory where the karaf distribution for controller is located")
195 .dest("distro-folder");
197 parser.addArgument("--ssh")
200 .help("Whether to use ssh for transport or just pure tcp")
203 parser.addArgument("--exi")
206 .help("Whether to use exi to transport xml content")
209 parser.addArgument("--debug")
212 .help("Whether to use debug log level instead of INFO")
215 parser.addArgument("--md-sal")
218 .help("Whether to use md-sal datastore instead of default simulated datastore.")
221 parser.addArgument("--time-out")
224 .help("the maximum time in seconds for executing each PUT request")
227 parser.addArgument("-ip")
229 .setDefault("0.0.0.0")
230 .help("Ip address which will be used for creating a socket address."
231 + "It can either be a machine name, such as "
232 + "java.sun.com, or a textual representation of its IP address.")
235 parser.addArgument("--thread-pool-size")
238 .help("The number of threads to keep in the pool, when creating a device simulator. Even if they are idle.")
239 .dest("thread-pool-size");
240 parser.addArgument("--rpc-config")
242 .help("Rpc config file. It can be used to define custom rpc behavior, or override the default one."
243 + "Usable for testing buggy device behavior.")
249 public static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) {
250 final TesttoolParameters opt = new TesttoolParameters();
252 parser.parseArgs(args, opt);
254 } catch (final ArgumentParserException e) {
255 parser.handleError(e);
262 private static String modifyMessage(final StringBuilder payloadBuilder, final int payloadPosition, final int size) {
264 return payloadBuilder.toString();
267 if (payloadPosition == 0) {
268 payloadBuilder.insert(payloadBuilder.toString().indexOf('{', 2), "[");
269 payloadBuilder.replace(payloadBuilder.length() - 1, payloadBuilder.length(), ",");
270 } else if (payloadPosition + 1 == size) {
271 payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
272 payloadBuilder.insert(payloadBuilder.toString().indexOf('}', 2) + 1, "]");
274 payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
275 payloadBuilder.replace(payloadBuilder.length() - 2, payloadBuilder.length() - 1, ",");
276 payloadBuilder.deleteCharAt(payloadBuilder.toString().lastIndexOf('}'));
278 return payloadBuilder.toString();
281 @SuppressWarnings("checkstyle:regexpSinglelineJava")
283 if (editContent == null) {
284 stream = TesttoolParameters.class.getResourceAsStream(RESOURCE);
286 Preconditions.checkArgument(!editContent.isDirectory(), "Edit content file is a dir");
287 Preconditions.checkArgument(editContent.canRead(), "Edit content file is unreadable");
290 if (controllerDestination != null) {
291 Preconditions.checkArgument(controllerDestination.contains(":"),
292 "Controller Destination needs to be in a following format <ip>:<port>");
293 final String[] parts = controllerDestination.split(Pattern.quote(":"));
294 Preconditions.checkArgument(Integer.parseInt(parts[1]) > 0, "Port =< 0");
297 checkArgument(deviceCount > 0, "Device count has to be > 0");
298 checkArgument(startingPort > 1023, "Starting port has to be > 1023");
299 checkArgument(devicesPerPort > 0, "Atleast one device per port needed");
301 if (schemasDir != null) {
302 checkArgument(schemasDir.exists(), "Schemas dir has to exist");
303 checkArgument(schemasDir.isDirectory(), "Schemas dir has to be a directory");
304 checkArgument(schemasDir.canRead(), "Schemas dir has to be readable");
306 final List<File> files = Arrays.asList(schemasDir.listFiles());
307 for (final File file : files) {
308 final Matcher matcher = YANG_FILENAME_PATTERN.matcher(file.getName());
309 if (!matcher.matches()) {
310 final BufferedReader reader;
312 reader = new BufferedReader(new FileReader(file));
313 String line = reader.readLine();
314 while (!DATE_PATTERN.matcher(line).find()) {
315 line = reader.readLine();
317 final Matcher m = DATE_PATTERN.matcher(line);
320 String moduleName = file.getAbsolutePath();
321 if (file.getName().endsWith(".yang")) {
322 moduleName = moduleName.substring(0, moduleName.length() - 5);
324 final String revision = m.group(1);
325 final String correctName = moduleName + "@" + revision + ".yang";
326 final File correctNameFile = new File(correctName);
327 file.renameTo(correctNameFile);
329 } catch (final IOException e) {
330 // print error to console (test tool is running from console)
336 if (rpcConfig != null) {
337 checkArgument(rpcConfig.exists(), "Rpc config file has to exist");
338 checkArgument(!rpcConfig.isDirectory(), "Rpc config file can't be a directory");
339 checkArgument(rpcConfig.canRead(), "Rpc config file to be readable");
343 public ArrayList<ArrayList<Execution.DestToPayload>> getThreadsPayloads(final List<Integer> openDevices) {
344 final String editContentString;
346 if (stream == null) {
347 editContentString = Files.toString(editContent, StandardCharsets.UTF_8);
349 editContentString = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
351 } catch (final IOException e) {
352 throw new IllegalArgumentException("Cannot read content of " + editContent);
357 Iterator<Integer> iterator;
359 final ArrayList<ArrayList<Execution.DestToPayload>> allThreadsPayloads = new ArrayList<>();
360 if (generateConfigBatchSize > 1) {
362 final int batchedRequests = openDevices.size() / generateConfigBatchSize;
363 final int batchedRequestsPerThread = batchedRequests / threadAmount;
364 final int leftoverBatchedRequests = (batchedRequests) % threadAmount;
365 final int leftoverRequests = openDevices.size() - (batchedRequests * generateConfigBatchSize);
367 final StringBuilder destBuilder = new StringBuilder(DEST);
368 destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT),
369 destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(),
370 controllerDestination);
372 for (int l = 0; l < threadAmount; l++) {
373 from = l * (batchedRequests * batchedRequestsPerThread);
374 to = from + (batchedRequests * batchedRequestsPerThread);
375 iterator = openDevices.subList(from, to).iterator();
376 allThreadsPayloads.add(createBatchedPayloads(batchedRequestsPerThread, iterator, editContentString,
377 destBuilder.toString()));
379 ArrayList<Execution.DestToPayload> payloads = null;
380 if (leftoverBatchedRequests > 0) {
381 from = threadAmount * (batchedRequests * batchedRequestsPerThread);
382 to = from + (batchedRequests * batchedRequestsPerThread);
383 iterator = openDevices.subList(from, to).iterator();
384 payloads = createBatchedPayloads(leftoverBatchedRequests, iterator, editContentString,
385 destBuilder.toString());
389 for (int j = 0; j < leftoverRequests; j++) {
390 from = openDevices.size() - leftoverRequests;
391 to = openDevices.size();
392 iterator = openDevices.subList(from, to).iterator();
393 final StringBuilder payloadBuilder = new StringBuilder(
394 prepareMessage(iterator.next(), editContentString));
395 payload += modifyMessage(payloadBuilder, j, leftoverRequests);
397 if (leftoverRequests > 0 || leftoverBatchedRequests > 0) {
399 if (payloads != null) {
400 payloads.add(new Execution.DestToPayload(destBuilder.toString(), payload));
402 allThreadsPayloads.add(payloads);
405 final int requestPerThreads = openDevices.size() / threadAmount;
406 final int leftoverRequests = openDevices.size() % threadAmount;
408 for (int i = 0; i < threadAmount; i++) {
409 from = i * requestPerThreads;
410 to = from + requestPerThreads;
411 iterator = openDevices.subList(from, to).iterator();
412 allThreadsPayloads.add(createPayloads(iterator, editContentString));
415 if (leftoverRequests > 0) {
416 from = (threadAmount) * requestPerThreads;
417 to = from + leftoverRequests;
418 iterator = openDevices.subList(from, to).iterator();
419 allThreadsPayloads.add(createPayloads(iterator, editContentString));
422 return allThreadsPayloads;
425 private String prepareMessage(final int openDevice, final String editContentString) {
426 final StringBuilder messageBuilder = new StringBuilder(editContentString);
428 if (editContentString.contains(HOST_KEY)) {
429 messageBuilder.replace(messageBuilder.indexOf(HOST_KEY),
430 messageBuilder.indexOf(HOST_KEY) + HOST_KEY.length(),
431 generateConfigsAddress);
433 if (editContentString.contains(PORT_KEY)) {
434 while (messageBuilder.indexOf(PORT_KEY) != -1) {
435 messageBuilder.replace(messageBuilder.indexOf(PORT_KEY),
436 messageBuilder.indexOf(PORT_KEY) + PORT_KEY.length(),
437 Integer.toString(openDevice));
440 if (editContentString.contains(TCP_ONLY)) {
441 messageBuilder.replace(messageBuilder.indexOf(TCP_ONLY),
442 messageBuilder.indexOf(TCP_ONLY) + TCP_ONLY.length(),
443 Boolean.toString(!ssh));
445 return messageBuilder.toString();
448 private ArrayList<Execution.DestToPayload> createPayloads(final Iterator<Integer> openDevices,
449 final String editContentString) {
450 final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
452 while (openDevices.hasNext()) {
453 final StringBuilder destBuilder = new StringBuilder(DEST);
454 destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT),
455 destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(), controllerDestination);
456 payloads.add(new Execution.DestToPayload(
457 destBuilder.toString(), prepareMessage(openDevices.next(), editContentString)));
462 private ArrayList<Execution.DestToPayload> createBatchedPayloads(final int batchedRequestsCount,
463 final Iterator<Integer> openDevices, final String editContentString, final String destination) {
464 final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
466 for (int i = 0; i < batchedRequestsCount; i++) {
468 for (int j = 0; j < generateConfigBatchSize; j++) {
469 final StringBuilder payloadBuilder = new StringBuilder(
470 prepareMessage(openDevices.next(), editContentString));
471 payload += modifyMessage(payloadBuilder, j, generateConfigBatchSize);
473 payloads.add(new Execution.DestToPayload(destination, payload));
479 public String toString() {
480 final List<Field> fields = Arrays.asList(this.getClass().getDeclaredFields());
481 final StringJoiner joiner = new StringJoiner(", \n", "TesttoolParameters{", "}\n");
483 .filter(field -> field.getAnnotation(Arg.class) != null)
484 .map(this::getFieldString)
485 .forEach(joiner::add);
486 return joiner.toString();
489 private String getFieldString(final Field field) {
491 return field.getName() + "='" + field.get(this) + "'";
492 } catch (final IllegalAccessException e) {
493 return field.getName() + "= UNKNOWN";