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