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