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
8 package org.opendaylight.netconf.test.tool;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
13 import com.google.common.io.CharStreams;
14 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15 import java.io.BufferedReader;
17 import java.io.FileReader;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.InputStreamReader;
21 import java.lang.reflect.Field;
22 import java.nio.charset.StandardCharsets;
23 import java.nio.file.Files;
24 import java.nio.file.Paths;
25 import java.nio.file.StandardCopyOption;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collections;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.StringJoiner;
32 import java.util.concurrent.TimeUnit;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35 import net.sourceforge.argparse4j.ArgumentParsers;
36 import net.sourceforge.argparse4j.annotation.Arg;
37 import net.sourceforge.argparse4j.inf.ArgumentParser;
38 import net.sourceforge.argparse4j.inf.ArgumentParserException;
39 import org.opendaylight.yangtools.yang.common.YangConstants;
41 @SuppressFBWarnings({"DM_EXIT", "DM_DEFAULT_ENCODING"})
42 public class TesttoolParameters {
44 private static final String HOST_KEY = "{HOST}";
45 private static final String PORT_KEY = "{PORT}";
46 private static final String TCP_ONLY = "{TCP_ONLY}";
47 private static final String ADDRESS_PORT = "{ADDRESS:PORT}";
48 private static final String DEST =
49 "http://{ADDRESS:PORT}/restconf/config/network-topology:network-topology/topology/topology-netconf/";
50 private static final Pattern YANG_FILENAME_PATTERN = Pattern
51 .compile("(?<name>.*)@(?<revision>\\d{4}-\\d{2}-\\d{2})\\.yang");
52 private static final Pattern REVISION_DATE_PATTERN = Pattern.compile("revision\\s+\"?(\\d{4}-\\d{2}-\\d{2})\"?");
54 private static final String RESOURCE = "/config-template.json";
55 @Arg(dest = "edit-content")
56 public File editContent;
59 @Arg(dest = "thread-amount")
60 public int threadAmount;
61 @Arg(dest = "throttle")
64 public ArrayList<String> auth;
65 @Arg(dest = "controller-destination")
66 public String controllerDestination;
67 @Arg(dest = "schemas-dir")
68 public File schemasDir;
69 @Arg(dest = "devices-count")
70 public int deviceCount;
71 @Arg(dest = "devices-per-port")
72 public int devicesPerPort;
73 @Arg(dest = "starting-port")
74 public int startingPort;
75 @Arg(dest = "generate-config-connection-timeout")
76 public int generateConfigsTimeout;
77 @Arg(dest = "generate-config-address")
78 public String generateConfigsAddress;
79 @Arg(dest = "distro-folder")
80 public File distroFolder;
81 @Arg(dest = "generate-configs-batch-size")
82 public int generateConfigBatchSize;
86 public boolean exi = true;
89 @Arg(dest = "notification-file")
90 public File notificationFile;
93 @Arg(dest = "initial-config-xml-file")
94 public File initialConfigXMLFile;
95 @Arg(dest = "time-out")
97 private InputStream stream;
100 @Arg(dest = "thread-pool-size")
101 public int threadPoolSize;
102 @Arg(dest = "rpc-config")
103 public File rpcConfig;
105 @SuppressWarnings("checkstyle:lineLength")
106 static ArgumentParser getParser() {
107 final ArgumentParser parser = ArgumentParsers.newArgumentParser("netconf testtool");
109 parser.description("netconf testtool");
111 parser.addArgument("--edit-content")
113 .dest("edit-content");
115 parser.addArgument("--async-requests")
117 .setDefault(Boolean.FALSE)
120 parser.addArgument("--thread-amount")
123 .dest("thread-amount")
124 .help("The number of threads to use for configuring devices.");
126 parser.addArgument("--throttle")
129 .help("Maximum amount of async requests that can be open at a time, "
130 + "with mutltiple threads this gets divided among all threads")
133 parser.addArgument("--auth")
135 .help("Username and password for HTTP basic authentication in order username password.")
138 parser.addArgument("--controller-destination")
140 .help("Ip address and port of controller. Must be in following format <ip>:<port> "
141 + "if available it will be used for spawning netconf connectors via topology configuration as "
142 + "a part of URI. Example (http://<controller destination>/restconf/config/network-topology:network-topology/topology/topology-netconf/node/<node-id>)"
143 + "otherwise it will just start simulated devices and skip the execution of PUT requests")
144 .dest("controller-destination");
146 parser.addArgument("--device-count")
149 .help("Number of simulated netconf devices to spin. This is the number of actual ports open for the devices.")
150 .dest("devices-count");
152 parser.addArgument("--devices-per-port")
155 .help("Amount of config files generated per port to spoof more devices than are actually running")
156 .dest("devices-per-port");
158 parser.addArgument("--schemas-dir")
160 .help("Directory containing yang schemas to describe simulated devices. Some schemas e.g. netconf monitoring and inet types are included by default")
161 .dest("schemas-dir");
163 parser.addArgument("--notification-file")
165 .help("Xml file containing notifications that should be sent to clients after create subscription is called")
166 .dest("notification-file");
168 parser.addArgument("--initial-config-xml-file")
170 .help("Xml file containing initial simulatted configuration to be returned via get-config rpc")
171 .dest("initial-config-xml-file");
173 parser.addArgument("--starting-port")
176 .help("First port for simulated device. Each other device will have previous+1 port number")
177 .dest("starting-port");
179 parser.addArgument("--generate-config-connection-timeout")
181 .setDefault((int) TimeUnit.MINUTES.toMillis(30))
182 .help("Timeout to be generated in initial config files")
183 .dest("generate-config-connection-timeout");
185 parser.addArgument("--generate-config-address")
187 .setDefault("127.0.0.1")
188 .help("Address to be placed in generated configs")
189 .dest("generate-config-address");
191 parser.addArgument("--generate-configs-batch-size")
194 .help("Number of connector configs per generated file")
195 .dest("generate-configs-batch-size");
197 parser.addArgument("--distribution-folder")
199 .help("Directory where the karaf distribution for controller is located")
200 .dest("distro-folder");
202 parser.addArgument("--ssh")
204 .setDefault(Boolean.TRUE)
205 .help("Whether to use ssh for transport or just pure tcp")
208 parser.addArgument("--exi")
210 .setDefault(Boolean.TRUE)
211 .help("Whether to use exi to transport xml content")
214 parser.addArgument("--debug")
216 .setDefault(Boolean.FALSE)
217 .help("Whether to use debug log level instead of INFO")
220 parser.addArgument("--md-sal")
222 .setDefault(Boolean.FALSE)
223 .help("Whether to use md-sal datastore instead of default simulated datastore.")
226 parser.addArgument("--time-out")
229 .help("the maximum time in seconds for executing each PUT request")
232 parser.addArgument("-ip")
234 .setDefault("0.0.0.0")
235 .help("Ip address which will be used for creating a socket address."
236 + "It can either be a machine name, such as "
237 + "java.sun.com, or a textual representation of its IP address.")
240 parser.addArgument("--thread-pool-size")
243 .help("The number of threads to keep in the pool, when creating a device simulator. Even if they are idle.")
244 .dest("thread-pool-size");
245 parser.addArgument("--rpc-config")
247 .help("Rpc config file. It can be used to define custom rpc behavior, or override the default one."
248 + "Usable for testing buggy device behavior.")
254 public static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) {
255 final TesttoolParameters opt = new TesttoolParameters();
257 parser.parseArgs(args, opt);
259 } catch (final ArgumentParserException e) {
260 parser.handleError(e);
267 private static String modifyMessage(final StringBuilder payloadBuilder, final int payloadPosition, final int size) {
269 return payloadBuilder.toString();
272 if (payloadPosition == 0) {
273 payloadBuilder.insert(payloadBuilder.toString().indexOf('{', 2), "[");
274 payloadBuilder.replace(payloadBuilder.length() - 1, payloadBuilder.length(), ",");
275 } else if (payloadPosition + 1 == size) {
276 payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
277 payloadBuilder.insert(payloadBuilder.toString().indexOf('}', 2) + 1, "]");
279 payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
280 payloadBuilder.replace(payloadBuilder.length() - 2, payloadBuilder.length() - 1, ",");
281 payloadBuilder.deleteCharAt(payloadBuilder.toString().lastIndexOf('}'));
283 return payloadBuilder.toString();
286 @SuppressWarnings("checkstyle:regexpSinglelineJava")
288 if (editContent == null) {
289 stream = TesttoolParameters.class.getResourceAsStream(RESOURCE);
291 checkArgument(!editContent.isDirectory(), "Edit content file is a dir");
292 checkArgument(editContent.canRead(), "Edit content file is unreadable");
295 if (controllerDestination != null) {
296 checkArgument(controllerDestination.contains(":"),
297 "Controller Destination needs to be in a following format <ip>:<port>");
298 final String[] parts = controllerDestination.split(Pattern.quote(":"));
299 checkArgument(Integer.parseInt(parts[1]) > 0, "Port =< 0");
302 checkArgument(deviceCount > 0, "Device count has to be > 0");
303 checkArgument(startingPort > 1023, "Starting port has to be > 1023");
304 checkArgument(devicesPerPort > 0, "Atleast one device per port needed");
306 if (schemasDir != null) {
307 checkArgument(schemasDir.exists(), "Schemas dir has to exist");
308 checkArgument(schemasDir.isDirectory(), "Schemas dir has to be a directory");
309 checkArgument(schemasDir.canRead(), "Schemas dir has to be readable");
311 final File[] filesArray = schemasDir.listFiles();
312 final List<File> files = filesArray != null ? Arrays.asList(filesArray) : Collections.emptyList();
313 for (final File file : files) {
314 final Matcher matcher = YANG_FILENAME_PATTERN.matcher(file.getName());
315 if (!matcher.matches()) {
317 final String correctName = correctedName(file);
318 if (correctName != null) {
319 Files.move(file.toPath(), Paths.get(correctName), StandardCopyOption.ATOMIC_MOVE);
321 } catch (final IOException e) {
322 // print error to console (test tool is running from console)
328 if (rpcConfig != null) {
329 checkArgument(rpcConfig.exists(), "Rpc config file has to exist");
330 checkArgument(!rpcConfig.isDirectory(), "Rpc config file can't be a directory");
331 checkArgument(rpcConfig.canRead(), "Rpc config file to be readable");
335 private static String correctedName(final File file) throws IOException {
336 try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
337 String line = reader.readLine();
338 while (line != null && !REVISION_DATE_PATTERN.matcher(line).find()) {
339 line = reader.readLine();
342 final Matcher m = REVISION_DATE_PATTERN.matcher(line);
343 checkState(m.find(), "Revision pattern %s did not match line %s", REVISION_DATE_PATTERN, line);
344 String moduleName = file.getAbsolutePath();
345 if (file.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)) {
346 moduleName = moduleName.substring(0, moduleName.length() - 5);
349 return moduleName + "@" + m.group(1) + YangConstants.RFC6020_YANG_FILE_EXTENSION;
356 public ArrayList<ArrayList<Execution.DestToPayload>> getThreadsPayloads(final List<Integer> openDevices) {
357 final String editContentString;
359 if (stream == null) {
360 editContentString = Files.readString(editContent.toPath());
362 editContentString = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
364 } catch (final IOException e) {
365 throw new IllegalArgumentException("Cannot read content of " + editContent, e);
370 Iterator<Integer> iterator;
372 final ArrayList<ArrayList<Execution.DestToPayload>> allThreadsPayloads = new ArrayList<>();
373 if (generateConfigBatchSize > 1) {
375 final int batchedRequests = openDevices.size() / generateConfigBatchSize;
376 final int batchedRequestsPerThread = batchedRequests / threadAmount;
377 final int leftoverBatchedRequests = batchedRequests % threadAmount;
378 final int leftoverRequests = openDevices.size() - batchedRequests * generateConfigBatchSize;
380 final StringBuilder destBuilder = new StringBuilder(DEST);
381 destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT),
382 destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(),
383 controllerDestination);
385 for (int l = 0; l < threadAmount; l++) {
386 from = l * batchedRequests * batchedRequestsPerThread;
387 to = from + batchedRequests * batchedRequestsPerThread;
388 iterator = openDevices.subList(from, to).iterator();
389 allThreadsPayloads.add(createBatchedPayloads(batchedRequestsPerThread, iterator, editContentString,
390 destBuilder.toString()));
392 ArrayList<Execution.DestToPayload> payloads = null;
393 if (leftoverBatchedRequests > 0) {
394 from = threadAmount * batchedRequests * batchedRequestsPerThread;
395 to = from + batchedRequests * batchedRequestsPerThread;
396 iterator = openDevices.subList(from, to).iterator();
397 payloads = createBatchedPayloads(leftoverBatchedRequests, iterator, editContentString,
398 destBuilder.toString());
402 for (int j = 0; j < leftoverRequests; j++) {
403 from = openDevices.size() - leftoverRequests;
404 to = openDevices.size();
405 iterator = openDevices.subList(from, to).iterator();
406 final StringBuilder payloadBuilder = new StringBuilder(
407 prepareMessage(iterator.next(), editContentString));
408 payload += modifyMessage(payloadBuilder, j, leftoverRequests);
410 if (leftoverRequests > 0 || leftoverBatchedRequests > 0) {
412 if (payloads != null) {
413 payloads.add(new Execution.DestToPayload(destBuilder.toString(), payload));
415 allThreadsPayloads.add(payloads);
418 final int requestPerThreads = openDevices.size() / threadAmount;
419 final int leftoverRequests = openDevices.size() % threadAmount;
421 for (int i = 0; i < threadAmount; i++) {
422 from = i * requestPerThreads;
423 to = from + requestPerThreads;
424 iterator = openDevices.subList(from, to).iterator();
425 allThreadsPayloads.add(createPayloads(iterator, editContentString));
428 if (leftoverRequests > 0) {
429 from = threadAmount * requestPerThreads;
430 to = from + leftoverRequests;
431 iterator = openDevices.subList(from, to).iterator();
432 allThreadsPayloads.add(createPayloads(iterator, editContentString));
435 return allThreadsPayloads;
438 private String prepareMessage(final int openDevice, final String editContentString) {
439 final StringBuilder messageBuilder = new StringBuilder(editContentString);
441 if (editContentString.contains(HOST_KEY)) {
442 messageBuilder.replace(messageBuilder.indexOf(HOST_KEY),
443 messageBuilder.indexOf(HOST_KEY) + HOST_KEY.length(),
444 generateConfigsAddress);
446 if (editContentString.contains(PORT_KEY)) {
447 while (messageBuilder.indexOf(PORT_KEY) != -1) {
448 messageBuilder.replace(messageBuilder.indexOf(PORT_KEY),
449 messageBuilder.indexOf(PORT_KEY) + PORT_KEY.length(),
450 Integer.toString(openDevice));
453 if (editContentString.contains(TCP_ONLY)) {
454 messageBuilder.replace(messageBuilder.indexOf(TCP_ONLY),
455 messageBuilder.indexOf(TCP_ONLY) + TCP_ONLY.length(),
456 Boolean.toString(!ssh));
458 return messageBuilder.toString();
461 private ArrayList<Execution.DestToPayload> createPayloads(final Iterator<Integer> openDevices,
462 final String editContentString) {
463 final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
465 while (openDevices.hasNext()) {
466 final StringBuilder destBuilder = new StringBuilder(DEST);
467 destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT),
468 destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(), controllerDestination);
469 payloads.add(new Execution.DestToPayload(
470 destBuilder.toString(), prepareMessage(openDevices.next(), editContentString)));
475 private ArrayList<Execution.DestToPayload> createBatchedPayloads(final int batchedRequestsCount,
476 final Iterator<Integer> openDevices, final String editContentString, final String destination) {
477 final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
479 for (int i = 0; i < batchedRequestsCount; i++) {
480 StringBuilder payload = new StringBuilder();
481 for (int j = 0; j < generateConfigBatchSize; j++) {
482 final StringBuilder payloadBuilder = new StringBuilder(
483 prepareMessage(openDevices.next(), editContentString));
484 payload.append(modifyMessage(payloadBuilder, j, generateConfigBatchSize));
486 payloads.add(new Execution.DestToPayload(destination, payload.toString()));
492 public String toString() {
493 final List<Field> fields = Arrays.asList(this.getClass().getDeclaredFields());
494 final StringJoiner joiner = new StringJoiner(", \n", "TesttoolParameters{", "}\n");
496 .filter(field -> field.getAnnotation(Arg.class) != null)
497 .map(this::getFieldString)
498 .forEach(joiner::add);
499 return joiner.toString();
502 private String getFieldString(final Field field) {
504 return field.getName() + "='" + field.get(this) + "'";
505 } catch (final IllegalAccessException e) {
506 return field.getName() + "= UNKNOWN";