def348e33b33137ab3599ff350728f88b84cbe1c
[netconf.git] / netconf / tools / netconf-testtool / src / main / java / org / opendaylight / netconf / test / tool / TesttoolParameters.java
1 /*
2  * Copyright (c) 2016 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 package org.opendaylight.netconf.test.tool;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12
13 import com.google.common.io.CharStreams;
14 import com.google.common.io.Files;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.io.BufferedReader;
17 import java.io.File;
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.Collections;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.StringJoiner;
30 import java.util.concurrent.TimeUnit;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import net.sourceforge.argparse4j.ArgumentParsers;
34 import net.sourceforge.argparse4j.annotation.Arg;
35 import net.sourceforge.argparse4j.inf.ArgumentParser;
36 import net.sourceforge.argparse4j.inf.ArgumentParserException;
37
38 @SuppressFBWarnings({"DM_EXIT", "DM_DEFAULT_ENCODING"})
39 public class TesttoolParameters {
40
41     private static final String HOST_KEY = "{HOST}";
42     private static final String PORT_KEY = "{PORT}";
43     private static final String TCP_ONLY = "{TCP_ONLY}";
44     private static final String ADDRESS_PORT = "{ADDRESS:PORT}";
45     private static final String DEST =
46         "http://{ADDRESS:PORT}/restconf/config/network-topology:network-topology/topology/topology-netconf/";
47     private static final Pattern YANG_FILENAME_PATTERN = Pattern
48         .compile("(?<name>.*)@(?<revision>\\d{4}-\\d{2}-\\d{2})\\.yang");
49     private static final Pattern REVISION_DATE_PATTERN = Pattern.compile("revision\\s+\"?(\\d{4}-\\d{2}-\\d{2})\"?");
50
51     private static final String RESOURCE = "/config-template.json";
52     @Arg(dest = "edit-content")
53     public File editContent;
54     @Arg(dest = "async")
55     public boolean async;
56     @Arg(dest = "thread-amount")
57     public int threadAmount;
58     @Arg(dest = "throttle")
59     public int throttle;
60     @Arg(dest = "auth")
61     public ArrayList<String> auth;
62     @Arg(dest = "controller-destination")
63     public String controllerDestination;
64     @Arg(dest = "schemas-dir")
65     public File schemasDir;
66     @Arg(dest = "devices-count")
67     public int deviceCount;
68     @Arg(dest = "devices-per-port")
69     public int devicesPerPort;
70     @Arg(dest = "starting-port")
71     public int startingPort;
72     @Arg(dest = "generate-config-connection-timeout")
73     public int generateConfigsTimeout;
74     @Arg(dest = "generate-config-address")
75     public String generateConfigsAddress;
76     @Arg(dest = "distro-folder")
77     public File distroFolder;
78     @Arg(dest = "generate-configs-batch-size")
79     public int generateConfigBatchSize;
80     @Arg(dest = "ssh")
81     public boolean ssh;
82     @Arg(dest = "exi")
83     public boolean exi = true;
84     @Arg(dest = "debug")
85     public boolean debug;
86     @Arg(dest = "notification-file")
87     public File notificationFile;
88     @Arg(dest = "md-sal")
89     public boolean mdSal;
90     @Arg(dest = "initial-config-xml-file")
91     public File initialConfigXMLFile;
92     @Arg(dest = "time-out")
93     public long timeOut;
94     private InputStream stream;
95     @Arg(dest = "ip")
96     public String ip;
97     @Arg(dest = "thread-pool-size")
98     public int threadPoolSize;
99     @Arg(dest = "rpc-config")
100     public File rpcConfig;
101
102     @SuppressWarnings("checkstyle:lineLength")
103     static ArgumentParser getParser() {
104         final ArgumentParser parser = ArgumentParsers.newArgumentParser("netconf testtool");
105
106         parser.description("netconf testtool");
107
108         parser.addArgument("--edit-content")
109                 .type(String.class)
110                 .dest("edit-content");
111
112         parser.addArgument("--async-requests")
113                 .type(Boolean.class)
114                 .setDefault(Boolean.FALSE)
115                 .dest("async");
116
117         parser.addArgument("--thread-amount")
118                 .type(Integer.class)
119                 .setDefault(1)
120                 .dest("thread-amount")
121                 .help("The number of threads to use for configuring devices.");
122
123         parser.addArgument("--throttle")
124                 .type(Integer.class)
125                 .setDefault(5000)
126                 .help("Maximum amount of async requests that can be open at a time, "
127                         + "with mutltiple threads this gets divided among all threads")
128                 .dest("throttle");
129
130         parser.addArgument("--auth")
131                 .nargs(2)
132                 .help("Username and password for HTTP basic authentication in order username password.")
133                 .dest("auth");
134
135         parser.addArgument("--controller-destination")
136                 .type(String.class)
137                 .help("Ip address and port of controller. Must be in following format <ip>:<port> "
138                         + "if available it will be used for spawning netconf connectors via topology configuration as "
139                         + "a part of URI. Example (http://<controller destination>/restconf/config/network-topology:network-topology/topology/topology-netconf/node/<node-id>)"
140                         + "otherwise it will just start simulated devices and skip the execution of PUT requests")
141                 .dest("controller-destination");
142
143         parser.addArgument("--device-count")
144                 .type(Integer.class)
145                 .setDefault(1)
146                 .help("Number of simulated netconf devices to spin. This is the number of actual ports open for the devices.")
147                 .dest("devices-count");
148
149         parser.addArgument("--devices-per-port")
150                 .type(Integer.class)
151                 .setDefault(1)
152                 .help("Amount of config files generated per port to spoof more devices than are actually running")
153                 .dest("devices-per-port");
154
155         parser.addArgument("--schemas-dir")
156                 .type(File.class)
157                 .help("Directory containing yang schemas to describe simulated devices. Some schemas e.g. netconf monitoring and inet types are included by default")
158                 .dest("schemas-dir");
159
160         parser.addArgument("--notification-file")
161                 .type(File.class)
162                 .help("Xml file containing notifications that should be sent to clients after create subscription is called")
163                 .dest("notification-file");
164
165         parser.addArgument("--initial-config-xml-file")
166                 .type(File.class)
167                 .help("Xml file containing initial simulatted configuration to be returned via get-config rpc")
168                 .dest("initial-config-xml-file");
169
170         parser.addArgument("--starting-port")
171                 .type(Integer.class)
172                 .setDefault(17830)
173                 .help("First port for simulated device. Each other device will have previous+1 port number")
174                 .dest("starting-port");
175
176         parser.addArgument("--generate-config-connection-timeout")
177                 .type(Integer.class)
178                 .setDefault((int) TimeUnit.MINUTES.toMillis(30))
179                 .help("Timeout to be generated in initial config files")
180                 .dest("generate-config-connection-timeout");
181
182         parser.addArgument("--generate-config-address")
183                 .type(String.class)
184                 .setDefault("127.0.0.1")
185                 .help("Address to be placed in generated configs")
186                 .dest("generate-config-address");
187
188         parser.addArgument("--generate-configs-batch-size")
189                 .type(Integer.class)
190                 .setDefault(1)
191                 .help("Number of connector configs per generated file")
192                 .dest("generate-configs-batch-size");
193
194         parser.addArgument("--distribution-folder")
195                 .type(File.class)
196                 .help("Directory where the karaf distribution for controller is located")
197                 .dest("distro-folder");
198
199         parser.addArgument("--ssh")
200                 .type(Boolean.class)
201                 .setDefault(Boolean.TRUE)
202                 .help("Whether to use ssh for transport or just pure tcp")
203                 .dest("ssh");
204
205         parser.addArgument("--exi")
206                 .type(Boolean.class)
207                 .setDefault(Boolean.TRUE)
208                 .help("Whether to use exi to transport xml content")
209                 .dest("exi");
210
211         parser.addArgument("--debug")
212                 .type(Boolean.class)
213                 .setDefault(Boolean.FALSE)
214                 .help("Whether to use debug log level instead of INFO")
215                 .dest("debug");
216
217         parser.addArgument("--md-sal")
218                 .type(Boolean.class)
219                 .setDefault(Boolean.FALSE)
220                 .help("Whether to use md-sal datastore instead of default simulated datastore.")
221                 .dest("md-sal");
222
223         parser.addArgument("--time-out")
224                 .type(long.class)
225                 .setDefault(20)
226                 .help("the maximum time in seconds for executing each PUT request")
227                 .dest("time-out");
228
229         parser.addArgument("-ip")
230                 .type(String.class)
231                 .setDefault("0.0.0.0")
232                 .help("Ip address which will be used for creating a socket address."
233                         + "It can either be a machine name, such as "
234                         + "java.sun.com, or a textual representation of its IP address.")
235                 .dest("ip");
236
237         parser.addArgument("--thread-pool-size")
238                 .type(Integer.class)
239                 .setDefault(8)
240                 .help("The number of threads to keep in the pool, when creating a device simulator. Even if they are idle.")
241                 .dest("thread-pool-size");
242         parser.addArgument("--rpc-config")
243                 .type(File.class)
244                 .help("Rpc config file. It can be used to define custom rpc behavior, or override the default one."
245                     + "Usable for testing buggy device behavior.")
246                 .dest("rpc-config");
247
248         return parser;
249     }
250
251     public static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) {
252         final TesttoolParameters opt = new TesttoolParameters();
253         try {
254             parser.parseArgs(args, opt);
255             return opt;
256         } catch (final ArgumentParserException e) {
257             parser.handleError(e);
258         }
259
260         System.exit(1);
261         return null;
262     }
263
264     private static String modifyMessage(final StringBuilder payloadBuilder, final int payloadPosition, final int size) {
265         if (size == 1) {
266             return payloadBuilder.toString();
267         }
268
269         if (payloadPosition == 0) {
270             payloadBuilder.insert(payloadBuilder.toString().indexOf('{', 2), "[");
271             payloadBuilder.replace(payloadBuilder.length() - 1, payloadBuilder.length(), ",");
272         } else if (payloadPosition + 1 == size) {
273             payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
274             payloadBuilder.insert(payloadBuilder.toString().indexOf('}', 2) + 1, "]");
275         } else {
276             payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
277             payloadBuilder.replace(payloadBuilder.length() - 2, payloadBuilder.length() - 1, ",");
278             payloadBuilder.deleteCharAt(payloadBuilder.toString().lastIndexOf('}'));
279         }
280         return payloadBuilder.toString();
281     }
282
283     @SuppressWarnings("checkstyle:regexpSinglelineJava")
284     void validate() {
285         if (editContent == null) {
286             stream = TesttoolParameters.class.getResourceAsStream(RESOURCE);
287         } else {
288             checkArgument(!editContent.isDirectory(), "Edit content file is a dir");
289             checkArgument(editContent.canRead(), "Edit content file is unreadable");
290         }
291
292         if (controllerDestination != null) {
293             checkArgument(controllerDestination.contains(":"),
294                 "Controller Destination needs to be in a following format <ip>:<port>");
295             final String[] parts = controllerDestination.split(Pattern.quote(":"));
296             checkArgument(Integer.parseInt(parts[1]) > 0, "Port =< 0");
297         }
298
299         checkArgument(deviceCount > 0, "Device count has to be > 0");
300         checkArgument(startingPort > 1023, "Starting port has to be > 1023");
301         checkArgument(devicesPerPort > 0, "Atleast one device per port needed");
302
303         if (schemasDir != null) {
304             checkArgument(schemasDir.exists(), "Schemas dir has to exist");
305             checkArgument(schemasDir.isDirectory(), "Schemas dir has to be a directory");
306             checkArgument(schemasDir.canRead(), "Schemas dir has to be readable");
307
308             final File[] filesArray = schemasDir.listFiles();
309             final List<File> files = filesArray != null ? Arrays.asList(filesArray) : Collections.emptyList();
310             for (final File file : files) {
311                 final Matcher matcher = YANG_FILENAME_PATTERN.matcher(file.getName());
312                 if (!matcher.matches()) {
313                     try {
314                         final String correctName = correctedName(file);
315                         if (correctName != null) {
316                             Files.move(file, new File(correctName));
317                         }
318                     } catch (final IOException e) {
319                         // print error to console (test tool is running from console)
320                         e.printStackTrace();
321                     }
322                 }
323             }
324         }
325         if (rpcConfig != null) {
326             checkArgument(rpcConfig.exists(), "Rpc config file has to exist");
327             checkArgument(!rpcConfig.isDirectory(), "Rpc config file can't be a directory");
328             checkArgument(rpcConfig.canRead(), "Rpc config file to be readable");
329         }
330     }
331
332     private static String correctedName(final File file) throws IOException {
333         try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
334             String line = reader.readLine();
335             while (line != null && !REVISION_DATE_PATTERN.matcher(line).find()) {
336                 line = reader.readLine();
337             }
338             if (line != null) {
339                 final Matcher m = REVISION_DATE_PATTERN.matcher(line);
340                 checkState(m.find());
341                 String moduleName = file.getAbsolutePath();
342                 if (file.getName().endsWith(".yang")) {
343                     moduleName = moduleName.substring(0, moduleName.length() - 5);
344                 }
345                 final String revision = m.group(1);
346                 return moduleName + "@" + revision + ".yang";
347             }
348         }
349         return null;
350     }
351
352
353     public ArrayList<ArrayList<Execution.DestToPayload>> getThreadsPayloads(final List<Integer> openDevices) {
354         final String editContentString;
355         try {
356             if (stream == null) {
357                 editContentString = Files.asCharSource(editContent, StandardCharsets.UTF_8).read();
358             } else {
359                 editContentString = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
360             }
361         } catch (final IOException e) {
362             throw new IllegalArgumentException("Cannot read content of " + editContent, e);
363         }
364
365         int from;
366         int to;
367         Iterator<Integer> iterator;
368
369         final ArrayList<ArrayList<Execution.DestToPayload>> allThreadsPayloads = new ArrayList<>();
370         if (generateConfigBatchSize > 1) {
371
372             final int batchedRequests = openDevices.size() / generateConfigBatchSize;
373             final int batchedRequestsPerThread = batchedRequests / threadAmount;
374             final int leftoverBatchedRequests = batchedRequests % threadAmount;
375             final int leftoverRequests = openDevices.size() - batchedRequests * generateConfigBatchSize;
376
377             final StringBuilder destBuilder = new StringBuilder(DEST);
378             destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT),
379                 destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(),
380                 controllerDestination);
381
382             for (int l = 0; l < threadAmount; l++) {
383                 from = l * batchedRequests * batchedRequestsPerThread;
384                 to = from + batchedRequests * batchedRequestsPerThread;
385                 iterator = openDevices.subList(from, to).iterator();
386                 allThreadsPayloads.add(createBatchedPayloads(batchedRequestsPerThread, iterator, editContentString,
387                     destBuilder.toString()));
388             }
389             ArrayList<Execution.DestToPayload> payloads = null;
390             if (leftoverBatchedRequests > 0) {
391                 from = threadAmount * batchedRequests * batchedRequestsPerThread;
392                 to = from + batchedRequests * batchedRequestsPerThread;
393                 iterator = openDevices.subList(from, to).iterator();
394                 payloads = createBatchedPayloads(leftoverBatchedRequests, iterator, editContentString,
395                     destBuilder.toString());
396             }
397             String payload = "";
398
399             for (int j = 0; j < leftoverRequests; j++) {
400                 from = openDevices.size() - leftoverRequests;
401                 to = openDevices.size();
402                 iterator = openDevices.subList(from, to).iterator();
403                 final StringBuilder payloadBuilder = new StringBuilder(
404                     prepareMessage(iterator.next(), editContentString));
405                 payload += modifyMessage(payloadBuilder, j, leftoverRequests);
406             }
407             if (leftoverRequests > 0 || leftoverBatchedRequests > 0) {
408
409                 if (payloads != null) {
410                     payloads.add(new Execution.DestToPayload(destBuilder.toString(), payload));
411                 }
412                 allThreadsPayloads.add(payloads);
413             }
414         } else {
415             final int requestPerThreads = openDevices.size() / threadAmount;
416             final int leftoverRequests = openDevices.size() % threadAmount;
417
418             for (int i = 0; i < threadAmount; i++) {
419                 from = i * requestPerThreads;
420                 to = from + requestPerThreads;
421                 iterator = openDevices.subList(from, to).iterator();
422                 allThreadsPayloads.add(createPayloads(iterator, editContentString));
423             }
424
425             if (leftoverRequests > 0) {
426                 from = threadAmount * requestPerThreads;
427                 to = from + leftoverRequests;
428                 iterator = openDevices.subList(from, to).iterator();
429                 allThreadsPayloads.add(createPayloads(iterator, editContentString));
430             }
431         }
432         return allThreadsPayloads;
433     }
434
435     private String prepareMessage(final int openDevice, final String editContentString) {
436         final StringBuilder messageBuilder = new StringBuilder(editContentString);
437
438         if (editContentString.contains(HOST_KEY)) {
439             messageBuilder.replace(messageBuilder.indexOf(HOST_KEY),
440                 messageBuilder.indexOf(HOST_KEY) + HOST_KEY.length(),
441                 generateConfigsAddress);
442         }
443         if (editContentString.contains(PORT_KEY)) {
444             while (messageBuilder.indexOf(PORT_KEY) != -1) {
445                 messageBuilder.replace(messageBuilder.indexOf(PORT_KEY),
446                     messageBuilder.indexOf(PORT_KEY) + PORT_KEY.length(),
447                     Integer.toString(openDevice));
448             }
449         }
450         if (editContentString.contains(TCP_ONLY)) {
451             messageBuilder.replace(messageBuilder.indexOf(TCP_ONLY),
452                 messageBuilder.indexOf(TCP_ONLY) + TCP_ONLY.length(),
453                 Boolean.toString(!ssh));
454         }
455         return messageBuilder.toString();
456     }
457
458     private ArrayList<Execution.DestToPayload> createPayloads(final Iterator<Integer> openDevices,
459                                                               final String editContentString) {
460         final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
461
462         while (openDevices.hasNext()) {
463             final StringBuilder destBuilder = new StringBuilder(DEST);
464             destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT),
465                 destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(), controllerDestination);
466             payloads.add(new Execution.DestToPayload(
467                 destBuilder.toString(), prepareMessage(openDevices.next(), editContentString)));
468         }
469         return payloads;
470     }
471
472     private ArrayList<Execution.DestToPayload> createBatchedPayloads(final int batchedRequestsCount,
473             final Iterator<Integer> openDevices, final String editContentString, final String destination) {
474         final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
475
476         for (int i = 0; i < batchedRequestsCount; i++) {
477             StringBuilder payload = new StringBuilder();
478             for (int j = 0; j < generateConfigBatchSize; j++) {
479                 final StringBuilder payloadBuilder = new StringBuilder(
480                     prepareMessage(openDevices.next(), editContentString));
481                 payload.append(modifyMessage(payloadBuilder, j, generateConfigBatchSize));
482             }
483             payloads.add(new Execution.DestToPayload(destination, payload.toString()));
484         }
485         return payloads;
486     }
487
488     @Override
489     public String toString() {
490         final List<Field> fields = Arrays.asList(this.getClass().getDeclaredFields());
491         final StringJoiner joiner = new StringJoiner(", \n", "TesttoolParameters{", "}\n");
492         fields.stream()
493                 .filter(field -> field.getAnnotation(Arg.class) != null)
494                 .map(this::getFieldString)
495                 .forEach(joiner::add);
496         return joiner.toString();
497     }
498
499     private String getFieldString(final Field field) {
500         try {
501             return field.getName() + "='" + field.get(this) + "'";
502         } catch (final IllegalAccessException e) {
503             return field.getName() + "= UNKNOWN";
504         }
505     }
506 }