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;
97 @Arg(dest = "rpc-config")
98 public File rpcConfig;
100 static ArgumentParser getParser() {
101 final ArgumentParser parser = ArgumentParsers.newArgumentParser("netconf testtool");
103 parser.description("netconf testtool");
105 parser.addArgument("--edit-content")
107 .dest("edit-content");
109 parser.addArgument("--async-requests")
114 parser.addArgument("--thread-amount")
117 .dest("thread-amount")
118 .help("The number of threads to use for configuring devices.");
120 parser.addArgument("--throttle")
123 .help("Maximum amount of async requests that can be open at a time, " +
124 "with mutltiple threads this gets divided among all threads")
127 parser.addArgument("--auth")
129 .help("Username and password for HTTP basic authentication in order username password.")
132 parser.addArgument("--controller-destination")
134 .help("Ip address and port of controller. Must be in following format <ip>:<port> " +
135 "if available it will be used for spawning netconf connectors via topology configuration as " +
136 "a part of URI. Example (http://<controller destination>/restconf/config/network-topology:network-topology/topology/topology-netconf/node/<node-id>)" +
137 "otherwise it will just start simulated devices and skip the execution of PUT requests")
138 .dest("controller-destination");
140 parser.addArgument("--device-count")
143 .help("Number of simulated netconf devices to spin. This is the number of actual ports open for the devices.")
144 .dest("devices-count");
146 parser.addArgument("--devices-per-port")
149 .help("Amount of config files generated per port to spoof more devices then are actually running")
150 .dest("devices-per-port");
152 parser.addArgument("--schemas-dir")
154 .help("Directory containing yang schemas to describe simulated devices. Some schemas e.g. netconf monitoring and inet types are included by default")
155 .dest("schemas-dir");
157 parser.addArgument("--notification-file")
159 .help("Xml file containing notifications that should be sent to clients after create subscription is called")
160 .dest("notification-file");
162 parser.addArgument("--initial-config-xml-file")
164 .help("Xml file containing initial simulatted configuration to be returned via get-config rpc")
165 .dest("initial-config-xml-file");
167 parser.addArgument("--starting-port")
170 .help("First port for simulated device. Each other device will have previous+1 port number")
171 .dest("starting-port");
173 parser.addArgument("--generate-config-connection-timeout")
175 .setDefault((int) TimeUnit.MINUTES.toMillis(30))
176 .help("Timeout to be generated in initial config files")
177 .dest("generate-config-connection-timeout");
179 parser.addArgument("--generate-config-address")
181 .setDefault("127.0.0.1")
182 .help("Address to be placed in generated configs")
183 .dest("generate-config-address");
185 parser.addArgument("--generate-configs-batch-size")
188 .help("Number of connector configs per generated file")
189 .dest("generate-configs-batch-size");
191 parser.addArgument("--distribution-folder")
193 .help("Directory where the karaf distribution for controller is located")
194 .dest("distro-folder");
196 parser.addArgument("--ssh")
199 .help("Whether to use ssh for transport or just pure tcp")
202 parser.addArgument("--exi")
205 .help("Whether to use exi to transport xml content")
208 parser.addArgument("--debug")
211 .help("Whether to use debug log level instead of INFO")
214 parser.addArgument("--md-sal")
217 .help("Whether to use md-sal datastore instead of default simulated datastore.")
220 parser.addArgument("--time-out")
223 .help("the maximum time in seconds for executing each PUT request")
226 parser.addArgument("-ip")
228 .setDefault("0.0.0.0")
229 .help("Ip address which will be used for creating a socket address." +
230 "It can either be a machine name, such as " +
231 "java.sun.com, or a textual representation of its IP address.")
234 parser.addArgument("--thread-pool-size")
237 .help("The number of threads to keep in the pool, when creating a device simulator. Even if they are idle.")
238 .dest("thread-pool-size");
239 parser.addArgument("--rpc-config")
241 .help("Rpc config file. It can be used to define custom rpc behavior, or override the default one." +
242 "Usable for testing buggy device behavior.")
248 public static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) {
249 final TesttoolParameters opt = new TesttoolParameters();
251 parser.parseArgs(args, opt);
253 } catch (final ArgumentParserException e) {
254 parser.handleError(e);
261 private static String modifyMessage(final StringBuilder payloadBuilder, final int payloadPosition, final int size) {
263 return payloadBuilder.toString();
266 if (payloadPosition == 0) {
267 payloadBuilder.insert(payloadBuilder.toString().indexOf('{', 2), "[");
268 payloadBuilder.replace(payloadBuilder.length() - 1, payloadBuilder.length(), ",");
269 } else if (payloadPosition + 1 == size) {
270 payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
271 payloadBuilder.insert(payloadBuilder.toString().indexOf('}', 2) + 1, "]");
273 payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
274 payloadBuilder.replace(payloadBuilder.length() - 2, payloadBuilder.length() - 1, ",");
275 payloadBuilder.deleteCharAt(payloadBuilder.toString().lastIndexOf('}'));
277 return payloadBuilder.toString();
281 if (editContent == null) {
282 stream = TesttoolParameters.class.getResourceAsStream(RESOURCE);
284 Preconditions.checkArgument(!editContent.isDirectory(), "Edit content file is a dir");
285 Preconditions.checkArgument(editContent.canRead(), "Edit content file is unreadable");
288 if (controllerDestination != null) {
289 Preconditions.checkArgument(controllerDestination.contains(":"), "Controller Destination needs to be in a following format <ip>:<port>");
290 final String[] parts = controllerDestination.split(Pattern.quote(":"));
291 Preconditions.checkArgument(Integer.parseInt(parts[1]) > 0, "Port =< 0");
294 checkArgument(deviceCount > 0, "Device count has to be > 0");
295 checkArgument(startingPort > 1023, "Starting port has to be > 1023");
296 checkArgument(devicesPerPort > 0, "Atleast one device per port needed");
298 if (schemasDir != null) {
299 checkArgument(schemasDir.exists(), "Schemas dir has to exist");
300 checkArgument(schemasDir.isDirectory(), "Schemas dir has to be a directory");
301 checkArgument(schemasDir.canRead(), "Schemas dir has to be readable");
303 final List<File> files = Arrays.asList(schemasDir.listFiles());
304 for (final File file : files) {
305 final Matcher matcher = YANG_FILENAME_PATTERN.matcher(file.getName());
306 if (!matcher.matches()) {
307 final BufferedReader reader;
309 reader = new BufferedReader(new FileReader(file));
310 String line = reader.readLine();
311 while (!DATE_PATTERN.matcher(line).find()) {
312 line = reader.readLine();
314 final Matcher m = DATE_PATTERN.matcher(line);
317 String moduleName = file.getAbsolutePath();
318 if (file.getName().endsWith(".yang")) {
319 moduleName = moduleName.substring(0, moduleName.length() - 5);
321 final String revision = m.group(1);
322 final String correctName = moduleName + "@" + revision + ".yang";
323 final File correctNameFile = new File(correctName);
324 file.renameTo(correctNameFile);
327 } catch (final IOException e) {
333 if (rpcConfig != null) {
334 checkArgument(rpcConfig.exists(), "Rpc config file has to exist");
335 checkArgument(!rpcConfig.isDirectory(), "Rpc config file can't be a directory");
336 checkArgument(rpcConfig.canRead(), "Rpc config file to be readable");
340 public ArrayList<ArrayList<Execution.DestToPayload>> getThreadsPayloads(final List<Integer> openDevices) {
341 final String editContentString;
343 if (stream == null) {
344 editContentString = Files.toString(editContent, StandardCharsets.UTF_8);
346 editContentString = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
348 } catch (final IOException e) {
349 throw new IllegalArgumentException("Cannot read content of " + editContent);
353 Iterator<Integer> iterator;
355 final ArrayList<ArrayList<Execution.DestToPayload>> allThreadsPayloads = new ArrayList<>();
356 if (generateConfigBatchSize > 1) {
358 final int batchedRequests = openDevices.size() / generateConfigBatchSize;
359 final int batchedRequestsPerThread = batchedRequests / threadAmount;
360 final int leftoverBatchedRequests = (batchedRequests) % threadAmount;
361 final int leftoverRequests = openDevices.size() - (batchedRequests * generateConfigBatchSize);
363 final StringBuilder destBuilder = new StringBuilder(dest);
364 destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT), destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(), controllerDestination);
366 for (int l = 0; l < threadAmount; l++) {
367 from = l * (batchedRequests * batchedRequestsPerThread);
368 to = from + (batchedRequests * batchedRequestsPerThread);
369 iterator = openDevices.subList(from, to).iterator();
370 allThreadsPayloads.add(createBatchedPayloads(batchedRequestsPerThread, iterator, editContentString, destBuilder.toString()));
372 ArrayList<Execution.DestToPayload> payloads = null;
373 if (leftoverBatchedRequests > 0) {
374 from = threadAmount * (batchedRequests * batchedRequestsPerThread);
375 to = from + (batchedRequests * batchedRequestsPerThread);
376 iterator = openDevices.subList(from, to).iterator();
377 payloads = createBatchedPayloads(leftoverBatchedRequests, iterator, editContentString, destBuilder.toString());
381 for (int j = 0; j < leftoverRequests; j++) {
382 from = openDevices.size() - leftoverRequests;
383 to = openDevices.size();
384 iterator = openDevices.subList(from, to).iterator();
385 final StringBuilder payloadBuilder = new StringBuilder(prepareMessage(iterator.next(), editContentString));
386 payload += modifyMessage(payloadBuilder, j, leftoverRequests);
388 if (leftoverRequests > 0 || leftoverBatchedRequests > 0) {
390 if (payloads != null) {
391 payloads.add(new Execution.DestToPayload(destBuilder.toString(), payload));
393 allThreadsPayloads.add(payloads);
396 final int requestPerThreads = openDevices.size() / threadAmount;
397 final int leftoverRequests = openDevices.size() % threadAmount;
399 for (int i = 0; i < threadAmount; i++) {
400 from = i * requestPerThreads;
401 to = from + requestPerThreads;
402 iterator = openDevices.subList(from, to).iterator();
403 allThreadsPayloads.add(createPayloads(iterator, editContentString));
406 if (leftoverRequests > 0) {
407 from = (threadAmount) * requestPerThreads;
408 to = from + leftoverRequests;
409 iterator = openDevices.subList(from, to).iterator();
410 allThreadsPayloads.add(createPayloads(iterator, editContentString));
413 return allThreadsPayloads;
416 private String prepareMessage(final int openDevice, final String editContentString) {
417 final StringBuilder messageBuilder = new StringBuilder(editContentString);
419 if (editContentString.contains(HOST_KEY)) {
420 messageBuilder.replace(messageBuilder.indexOf(HOST_KEY), messageBuilder.indexOf(HOST_KEY) + HOST_KEY.length(), generateConfigsAddress);
422 if (editContentString.contains(PORT_KEY)) {
423 while (messageBuilder.indexOf(PORT_KEY) != -1)
424 messageBuilder.replace(messageBuilder.indexOf(PORT_KEY), messageBuilder.indexOf(PORT_KEY) + PORT_KEY.length(), Integer.toString(openDevice));
426 if (editContentString.contains(TCP_ONLY)) {
427 messageBuilder.replace(messageBuilder.indexOf(TCP_ONLY), messageBuilder.indexOf(TCP_ONLY) + TCP_ONLY.length(), Boolean.toString(!ssh));
429 return messageBuilder.toString();
432 private ArrayList<Execution.DestToPayload> createPayloads(final Iterator<Integer> openDevices, final String editContentString) {
433 final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
435 while (openDevices.hasNext()) {
436 final StringBuilder destBuilder = new StringBuilder(dest);
437 destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT), destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(), controllerDestination);
438 payloads.add(new Execution.DestToPayload(destBuilder.toString(), prepareMessage(openDevices.next(), editContentString)));
443 private ArrayList<Execution.DestToPayload> createBatchedPayloads(final int batchedRequestsCount, final Iterator<Integer> openDevices, final String editContentString,
444 final String destination) {
445 final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
447 for (int i = 0; i < batchedRequestsCount; i++) {
449 for (int j = 0; j < generateConfigBatchSize; j++) {
450 final StringBuilder payloadBuilder = new StringBuilder(prepareMessage(openDevices.next(), editContentString));
451 payload += modifyMessage(payloadBuilder, j, generateConfigBatchSize);
453 payloads.add(new Execution.DestToPayload(destination, payload));
459 public String toString() {
460 final List<Field> fields = Arrays.asList(this.getClass().getDeclaredFields());
461 final StringJoiner joiner = new StringJoiner(", \n", "TesttoolParameters{", "}\n");
463 .filter(field -> field.getAnnotation(Arg.class) != null)
464 .map(this::getFieldString)
465 .forEach(joiner::add);
466 return joiner.toString();
469 private String getFieldString(final Field field) {
471 return field.getName() + "='" + field.get(this) + "'";
472 } catch (final IllegalAccessException e) {
473 return field.getName() + "= UNKNOWN";