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