22aa014bb2d426b4d9e853007695bdf7a6e863aa
[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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15 import java.io.BufferedReader;
16 import java.io.File;
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;
40
41 @SuppressFBWarnings({"DM_EXIT", "DM_DEFAULT_ENCODING"})
42 public class TesttoolParameters {
43
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})\"?");
53
54     private static final String RESOURCE = "/config-template.json";
55     @Arg(dest = "edit-content")
56     public File editContent;
57     @Arg(dest = "async")
58     public boolean async;
59     @Arg(dest = "thread-amount")
60     public int threadAmount;
61     @Arg(dest = "throttle")
62     public int throttle;
63     @Arg(dest = "auth")
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;
83     @Arg(dest = "ssh")
84     public boolean ssh;
85     @Arg(dest = "exi")
86     public boolean exi = true;
87     @Arg(dest = "debug")
88     public boolean debug;
89     @Arg(dest = "notification-file")
90     public File notificationFile;
91     @Arg(dest = "md-sal")
92     public boolean mdSal;
93     @Arg(dest = "initial-config-xml-file")
94     public File initialConfigXMLFile;
95     @Arg(dest = "time-out")
96     public long timeOut;
97     private InputStream stream;
98     @Arg(dest = "ip")
99     public String ip;
100     @Arg(dest = "thread-pool-size")
101     public int threadPoolSize;
102     @Arg(dest = "rpc-config")
103     public File rpcConfig;
104
105     @SuppressWarnings("checkstyle:lineLength")
106     static ArgumentParser getParser() {
107         final ArgumentParser parser = ArgumentParsers.newArgumentParser("netconf testtool");
108
109         parser.description("netconf testtool");
110
111         parser.addArgument("--edit-content")
112                 .type(String.class)
113                 .dest("edit-content");
114
115         parser.addArgument("--async-requests")
116                 .type(Boolean.class)
117                 .setDefault(Boolean.FALSE)
118                 .dest("async");
119
120         parser.addArgument("--thread-amount")
121                 .type(Integer.class)
122                 .setDefault(1)
123                 .dest("thread-amount")
124                 .help("The number of threads to use for configuring devices.");
125
126         parser.addArgument("--throttle")
127                 .type(Integer.class)
128                 .setDefault(5000)
129                 .help("Maximum amount of async requests that can be open at a time, "
130                         + "with mutltiple threads this gets divided among all threads")
131                 .dest("throttle");
132
133         parser.addArgument("--auth")
134                 .nargs(2)
135                 .help("Username and password for HTTP basic authentication in order username password.")
136                 .dest("auth");
137
138         parser.addArgument("--controller-destination")
139                 .type(String.class)
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");
145
146         parser.addArgument("--device-count")
147                 .type(Integer.class)
148                 .setDefault(1)
149                 .help("Number of simulated netconf devices to spin. This is the number of actual ports open for the devices.")
150                 .dest("devices-count");
151
152         parser.addArgument("--devices-per-port")
153                 .type(Integer.class)
154                 .setDefault(1)
155                 .help("Amount of config files generated per port to spoof more devices than are actually running")
156                 .dest("devices-per-port");
157
158         parser.addArgument("--schemas-dir")
159                 .type(File.class)
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");
162
163         parser.addArgument("--notification-file")
164                 .type(File.class)
165                 .help("Xml file containing notifications that should be sent to clients after create subscription is called")
166                 .dest("notification-file");
167
168         parser.addArgument("--initial-config-xml-file")
169                 .type(File.class)
170                 .help("Xml file containing initial simulatted configuration to be returned via get-config rpc")
171                 .dest("initial-config-xml-file");
172
173         parser.addArgument("--starting-port")
174                 .type(Integer.class)
175                 .setDefault(17830)
176                 .help("First port for simulated device. Each other device will have previous+1 port number")
177                 .dest("starting-port");
178
179         parser.addArgument("--generate-config-connection-timeout")
180                 .type(Integer.class)
181                 .setDefault((int) TimeUnit.MINUTES.toMillis(30))
182                 .help("Timeout to be generated in initial config files")
183                 .dest("generate-config-connection-timeout");
184
185         parser.addArgument("--generate-config-address")
186                 .type(String.class)
187                 .setDefault("127.0.0.1")
188                 .help("Address to be placed in generated configs")
189                 .dest("generate-config-address");
190
191         parser.addArgument("--generate-configs-batch-size")
192                 .type(Integer.class)
193                 .setDefault(1)
194                 .help("Number of connector configs per generated file")
195                 .dest("generate-configs-batch-size");
196
197         parser.addArgument("--distribution-folder")
198                 .type(File.class)
199                 .help("Directory where the karaf distribution for controller is located")
200                 .dest("distro-folder");
201
202         parser.addArgument("--ssh")
203                 .type(Boolean.class)
204                 .setDefault(Boolean.TRUE)
205                 .help("Whether to use ssh for transport or just pure tcp")
206                 .dest("ssh");
207
208         parser.addArgument("--exi")
209                 .type(Boolean.class)
210                 .setDefault(Boolean.TRUE)
211                 .help("Whether to use exi to transport xml content")
212                 .dest("exi");
213
214         parser.addArgument("--debug")
215                 .type(Boolean.class)
216                 .setDefault(Boolean.FALSE)
217                 .help("Whether to use debug log level instead of INFO")
218                 .dest("debug");
219
220         parser.addArgument("--md-sal")
221                 .type(Boolean.class)
222                 .setDefault(Boolean.FALSE)
223                 .help("Whether to use md-sal datastore instead of default simulated datastore.")
224                 .dest("md-sal");
225
226         parser.addArgument("--time-out")
227                 .type(long.class)
228                 .setDefault(20)
229                 .help("the maximum time in seconds for executing each PUT request")
230                 .dest("time-out");
231
232         parser.addArgument("-ip")
233                 .type(String.class)
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.")
238                 .dest("ip");
239
240         parser.addArgument("--thread-pool-size")
241                 .type(Integer.class)
242                 .setDefault(8)
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")
246                 .type(File.class)
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.")
249                 .dest("rpc-config");
250
251         return parser;
252     }
253
254     public static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) {
255         final TesttoolParameters opt = new TesttoolParameters();
256         try {
257             parser.parseArgs(args, opt);
258             return opt;
259         } catch (final ArgumentParserException e) {
260             parser.handleError(e);
261         }
262
263         System.exit(1);
264         return null;
265     }
266
267     private static String modifyMessage(final StringBuilder payloadBuilder, final int payloadPosition, final int size) {
268         if (size == 1) {
269             return payloadBuilder.toString();
270         }
271
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, "]");
278         } else {
279             payloadBuilder.delete(0, payloadBuilder.toString().indexOf(':') + 1);
280             payloadBuilder.replace(payloadBuilder.length() - 2, payloadBuilder.length() - 1, ",");
281             payloadBuilder.deleteCharAt(payloadBuilder.toString().lastIndexOf('}'));
282         }
283         return payloadBuilder.toString();
284     }
285
286     @SuppressWarnings("checkstyle:regexpSinglelineJava")
287     void validate() {
288         if (editContent == null) {
289             stream = TesttoolParameters.class.getResourceAsStream(RESOURCE);
290         } else {
291             checkArgument(!editContent.isDirectory(), "Edit content file is a dir");
292             checkArgument(editContent.canRead(), "Edit content file is unreadable");
293         }
294
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");
300         }
301
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");
305
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");
310
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()) {
316                     try {
317                         final String correctName = correctedName(file);
318                         if (correctName != null) {
319                             Files.move(file.toPath(), Paths.get(correctName), StandardCopyOption.ATOMIC_MOVE);
320                         }
321                     } catch (final IOException e) {
322                         // print error to console (test tool is running from console)
323                         e.printStackTrace();
324                     }
325                 }
326             }
327         }
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");
332         }
333     }
334
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();
340             }
341             if (line != null) {
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);
347                 }
348
349                 return moduleName + "@" + m.group(1) + YangConstants.RFC6020_YANG_FILE_EXTENSION;
350             }
351         }
352         return null;
353     }
354
355
356     public ArrayList<ArrayList<Execution.DestToPayload>> getThreadsPayloads(final List<Integer> openDevices) {
357         final String editContentString;
358         try {
359             if (stream == null) {
360                 editContentString = Files.readString(editContent.toPath());
361             } else {
362                 editContentString = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
363             }
364         } catch (final IOException e) {
365             throw new IllegalArgumentException("Cannot read content of " + editContent, e);
366         }
367
368         int from;
369         int to;
370         Iterator<Integer> iterator;
371
372         final ArrayList<ArrayList<Execution.DestToPayload>> allThreadsPayloads = new ArrayList<>();
373         if (generateConfigBatchSize > 1) {
374
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;
379
380             final StringBuilder destBuilder = new StringBuilder(DEST);
381             destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT),
382                 destBuilder.indexOf(ADDRESS_PORT) + ADDRESS_PORT.length(),
383                 controllerDestination);
384
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()));
391             }
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());
399             }
400             String payload = "";
401
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);
409             }
410             if (leftoverRequests > 0 || leftoverBatchedRequests > 0) {
411
412                 if (payloads != null) {
413                     payloads.add(new Execution.DestToPayload(destBuilder.toString(), payload));
414                 }
415                 allThreadsPayloads.add(payloads);
416             }
417         } else {
418             final int requestPerThreads = openDevices.size() / threadAmount;
419             final int leftoverRequests = openDevices.size() % threadAmount;
420
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));
426             }
427
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));
433             }
434         }
435         return allThreadsPayloads;
436     }
437
438     private String prepareMessage(final int openDevice, final String editContentString) {
439         final StringBuilder messageBuilder = new StringBuilder(editContentString);
440
441         if (editContentString.contains(HOST_KEY)) {
442             messageBuilder.replace(messageBuilder.indexOf(HOST_KEY),
443                 messageBuilder.indexOf(HOST_KEY) + HOST_KEY.length(),
444                 generateConfigsAddress);
445         }
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));
451             }
452         }
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));
457         }
458         return messageBuilder.toString();
459     }
460
461     private ArrayList<Execution.DestToPayload> createPayloads(final Iterator<Integer> openDevices,
462                                                               final String editContentString) {
463         final ArrayList<Execution.DestToPayload> payloads = new ArrayList<>();
464
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)));
471         }
472         return payloads;
473     }
474
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<>();
478
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));
485             }
486             payloads.add(new Execution.DestToPayload(destination, payload.toString()));
487         }
488         return payloads;
489     }
490
491     @Override
492     public String toString() {
493         final List<Field> fields = Arrays.asList(this.getClass().getDeclaredFields());
494         final StringJoiner joiner = new StringJoiner(", \n", "TesttoolParameters{", "}\n");
495         fields.stream()
496                 .filter(field -> field.getAnnotation(Arg.class) != null)
497                 .map(this::getFieldString)
498                 .forEach(joiner::add);
499         return joiner.toString();
500     }
501
502     private String getFieldString(final Field field) {
503         try {
504             return field.getName() + "='" + field.get(this) + "'";
505         } catch (final IllegalAccessException e) {
506             return field.getName() + "= UNKNOWN";
507         }
508     }
509 }