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