Bring features/neutron into the same parent dir as everything else
[controller.git] / opendaylight / netconf / netconf-testtool / src / main / java / org / opendaylight / controller / netconf / test / tool / Main.java
1 /*
2  * Copyright (c) 2014 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.controller.netconf.test.tool;
10
11 import static com.google.common.base.Preconditions.checkArgument;
12 import static com.google.common.base.Preconditions.checkNotNull;
13 import static com.google.common.base.Preconditions.checkState;
14
15 import ch.qos.logback.classic.Level;
16 import com.google.common.base.Charsets;
17 import com.google.common.base.Preconditions;
18 import com.google.common.collect.Lists;
19 import com.google.common.io.ByteStreams;
20 import com.google.common.io.CharStreams;
21 import com.google.common.io.Files;
22 import java.io.File;
23 import java.io.FileFilter;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.util.Collections;
28 import java.util.Comparator;
29 import java.util.List;
30 import java.util.concurrent.TimeUnit;
31 import net.sourceforge.argparse4j.ArgumentParsers;
32 import net.sourceforge.argparse4j.annotation.Arg;
33 import net.sourceforge.argparse4j.inf.ArgumentParser;
34 import net.sourceforge.argparse4j.inf.ArgumentParserException;
35 import org.opendaylight.controller.netconf.util.xml.XmlElement;
36 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.w3c.dom.Document;
40 import org.w3c.dom.Element;
41 import org.w3c.dom.Node;
42 import org.w3c.dom.NodeList;
43 import org.xml.sax.SAXException;
44
45 public final class Main {
46
47     private static final Logger LOG = LoggerFactory.getLogger(Main.class);
48
49     public static class Params {
50
51         @Arg(dest = "schemas-dir")
52         public File schemasDir;
53
54         @Arg(dest = "devices-count")
55         public int deviceCount;
56
57         @Arg(dest = "starting-port")
58         public int startingPort;
59
60         @Arg(dest = "generate-config-connection-timeout")
61         public int generateConfigsTimeout;
62
63         @Arg(dest = "generate-config-address")
64         public String generateConfigsAddress;
65
66         @Arg(dest = "distro-folder")
67         public File distroFolder;
68
69         @Arg(dest = "generate-configs-batch-size")
70         public int generateConfigBatchSize;
71
72         @Arg(dest = "ssh")
73         public boolean ssh;
74
75         @Arg(dest = "exi")
76         public boolean exi;
77
78         @Arg(dest = "debug")
79         public boolean debug;
80
81         static ArgumentParser getParser() {
82             final ArgumentParser parser = ArgumentParsers.newArgumentParser("netconf testool");
83
84             parser.description("Netconf device simulator. Detailed info can be found at https://wiki.opendaylight.org/view/OpenDaylight_Controller:Netconf:Testtool#Building_testtool");
85
86             parser.addArgument("--device-count")
87                     .type(Integer.class)
88                     .setDefault(1)
89                     .type(Integer.class)
90                     .help("Number of simulated netconf devices to spin")
91                     .dest("devices-count");
92
93             parser.addArgument("--schemas-dir")
94                     .type(File.class)
95                     .help("Directory containing yang schemas to describe simulated devices. Some schemas e.g. netconf monitoring and inet types are included by default")
96                     .dest("schemas-dir");
97
98             parser.addArgument("--starting-port")
99                     .type(Integer.class)
100                     .setDefault(17830)
101                     .help("First port for simulated device. Each other device will have previous+1 port number")
102                     .dest("starting-port");
103
104             parser.addArgument("--generate-config-connection-timeout")
105                     .type(Integer.class)
106                     .setDefault((int)TimeUnit.MINUTES.toMillis(30))
107                     .help("Timeout to be generated in initial config files")
108                     .dest("generate-config-connection-timeout");
109
110             parser.addArgument("--generate-config-address")
111                     .type(String.class)
112                     .setDefault("127.0.0.1")
113                     .help("Address to be placed in generated configs")
114                     .dest("generate-config-address");
115
116             parser.addArgument("--generate-configs-batch-size")
117                     .type(Integer.class)
118                     .setDefault(4000)
119                     .help("Number of connector configs per generated file")
120                     .dest("generate-configs-batch-size");
121
122             parser.addArgument("--distribution-folder")
123                     .type(File.class)
124                     .help("Directory where the karaf distribution for controller is located")
125                     .dest("distro-folder");
126
127             parser.addArgument("--ssh")
128                     .type(Boolean.class)
129                     .setDefault(true)
130                     .help("Whether to use ssh for transport or just pure tcp")
131                     .dest("ssh");
132
133             parser.addArgument("--exi")
134                     .type(Boolean.class)
135                     .setDefault(true)
136                     .help("Whether to use exi to transport xml content")
137                     .dest("exi");
138
139             parser.addArgument("--debug")
140                     .type(Boolean.class)
141                     .setDefault(false)
142                     .help("Whether to use debug log level instead of INFO")
143                     .dest("debug");
144
145             return parser;
146         }
147
148         void validate() {
149             checkArgument(deviceCount > 0, "Device count has to be > 0");
150             checkArgument(startingPort > 1023, "Starting port has to be > 1023");
151
152             if(schemasDir != null) {
153                 checkArgument(schemasDir.exists(), "Schemas dir has to exist");
154                 checkArgument(schemasDir.isDirectory(), "Schemas dir has to be a directory");
155                 checkArgument(schemasDir.canRead(), "Schemas dir has to be readable");
156             }
157         }
158     }
159
160     public static void main(final String[] args) {
161         final Params params = parseArgs(args, Params.getParser());
162         params.validate();
163
164         final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
165         root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
166
167         final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator();
168         try {
169             final List<Integer> openDevices = netconfDeviceSimulator.start(params);
170             if (openDevices.size() == 0) {
171                 LOG.error("Failed to start any simulated devices, exiting...");
172                 System.exit(1);
173             }
174             if(params.distroFolder != null) {
175                 final ConfigGenerator configGenerator = new ConfigGenerator(params.distroFolder, openDevices);
176                 final List<File> generated = configGenerator.generate(params.ssh, params.generateConfigBatchSize, params.generateConfigsTimeout, params.generateConfigsAddress);
177                 configGenerator.updateFeatureFile(generated);
178                 configGenerator.changeLoadOrder();
179             }
180         } catch (final Exception e) {
181             LOG.error("Unhandled exception", e);
182             netconfDeviceSimulator.close();
183             System.exit(1);
184         }
185
186         // Block main thread
187         synchronized (netconfDeviceSimulator) {
188             try {
189                 netconfDeviceSimulator.wait();
190             } catch (final InterruptedException e) {
191                 throw new RuntimeException(e);
192             }
193         }
194     }
195
196     private static Params parseArgs(final String[] args, final ArgumentParser parser) {
197         final Params opt = new Params();
198         try {
199             parser.parseArgs(args, opt);
200             return opt;
201         } catch (final ArgumentParserException e) {
202             parser.handleError(e);
203         }
204
205         System.exit(1);
206         return null;
207     }
208
209     private static class ConfigGenerator {
210         public static final String NETCONF_CONNECTOR_XML = "/initial/99-netconf-connector.xml";
211         public static final String NETCONF_CONNECTOR_NAME = "controller-config";
212         public static final String NETCONF_CONNECTOR_PORT = "1830";
213         public static final String NETCONF_CONNECTOR_ADDRESS = "127.0.0.1";
214         public static final String NETCONF_USE_SSH = "false";
215         public static final String SIM_DEVICE_SUFFIX = "-sim-device";
216
217         private static final String SIM_DEVICE_CFG_PREFIX = "simulated-devices_";
218         private static final String ETC_KARAF_PATH = "etc/";
219         private static final String ETC_OPENDAYLIGHT_KARAF_PATH = ETC_KARAF_PATH + "opendaylight/karaf/";
220
221         public static final String NETCONF_CONNECTOR_ALL_FEATURE = "odl-netconf-connector-all";
222         private static final String ORG_OPS4J_PAX_URL_MVN_CFG = "org.ops4j.pax.url.mvn.cfg";
223
224         private final File configDir;
225         private final List<Integer> openDevices;
226         private final List<File> ncFeatureFiles;
227         private final File etcDir;
228         private final File loadOrderCfgFile;
229
230         public ConfigGenerator(final File directory, final List<Integer> openDevices) {
231             this.configDir = new File(directory, ETC_OPENDAYLIGHT_KARAF_PATH);
232             this.etcDir = new File(directory, ETC_KARAF_PATH);
233             this.loadOrderCfgFile = new File(etcDir, ORG_OPS4J_PAX_URL_MVN_CFG);
234             this.ncFeatureFiles = getFeatureFile(directory, "features-netconf-connector", "xml");
235             this.openDevices = openDevices;
236         }
237
238         public List<File> generate(final boolean useSsh, final int batchSize, final int generateConfigsTimeout, final String address) {
239             if(configDir.exists() == false) {
240                 Preconditions.checkState(configDir.mkdirs(), "Unable to create directory " + configDir);
241             }
242
243             for (final File file : configDir.listFiles(new FileFilter() {
244                 @Override
245                 public boolean accept(final File pathname) {
246                     return !pathname.isDirectory() && pathname.getName().startsWith(SIM_DEVICE_CFG_PREFIX);
247                 }
248             })) {
249                 Preconditions.checkState(file.delete(), "Unable to clean previous generated file %s", file);
250             }
251
252             try(InputStream stream = Main.class.getResourceAsStream(NETCONF_CONNECTOR_XML)) {
253                 checkNotNull(stream, "Cannot load %s", NETCONF_CONNECTOR_XML);
254                 String configBlueprint = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
255
256                 checkState(configBlueprint.contains(NETCONF_CONNECTOR_NAME));
257                 checkState(configBlueprint.contains(NETCONF_CONNECTOR_PORT));
258                 checkState(configBlueprint.contains(NETCONF_USE_SSH));
259                 checkState(configBlueprint.contains(NETCONF_CONNECTOR_ADDRESS));
260                 configBlueprint = configBlueprint.replace(NETCONF_CONNECTOR_NAME, "%s");
261                 configBlueprint = configBlueprint.replace(NETCONF_CONNECTOR_ADDRESS, "%s");
262                 configBlueprint = configBlueprint.replace(NETCONF_CONNECTOR_PORT, "%s");
263                 configBlueprint = configBlueprint.replace(NETCONF_USE_SSH, "%s");
264
265                 final String before = configBlueprint.substring(0, configBlueprint.indexOf("<module>"));
266                 final String middleBlueprint = configBlueprint.substring(configBlueprint.indexOf("<module>"), configBlueprint.indexOf("</module>"));
267                 final String after = configBlueprint.substring(configBlueprint.indexOf("</module>") + "</module>".length());
268
269                 int connectorCount = 0;
270                 Integer batchStart = null;
271                 StringBuilder b = new StringBuilder();
272                 b.append(before);
273
274                 final List<File> generatedConfigs = Lists.newArrayList();
275
276                 for (final Integer openDevice : openDevices) {
277                     if(batchStart == null) {
278                         batchStart = openDevice;
279                     }
280
281                     final String name = String.valueOf(openDevice) + SIM_DEVICE_SUFFIX;
282                     String configContent = String.format(middleBlueprint, name, address, String.valueOf(openDevice), String.valueOf(!useSsh));
283                     configContent = String.format("%s%s%d%s\n%s\n", configContent, "<connection-timeout-millis>", generateConfigsTimeout, "</connection-timeout-millis>", "</module>");
284
285                     b.append(configContent);
286                     connectorCount++;
287                     if(connectorCount == batchSize) {
288                         b.append(after);
289                         final File to = new File(configDir, String.format(SIM_DEVICE_CFG_PREFIX + "%d-%d.xml", batchStart, openDevice));
290                         generatedConfigs.add(to);
291                         Files.write(b.toString(), to, Charsets.UTF_8);
292                         connectorCount = 0;
293                         b = new StringBuilder();
294                         b.append(before);
295                         batchStart = null;
296                     }
297                 }
298
299                 // Write remaining
300                 if(connectorCount != 0) {
301                     b.append(after);
302                     final File to = new File(configDir, String.format(SIM_DEVICE_CFG_PREFIX + "%d-%d.xml", batchStart, openDevices.get(openDevices.size() - 1)));
303                     generatedConfigs.add(to);
304                     Files.write(b.toString(), to, Charsets.UTF_8);
305                 }
306
307                 LOG.info("Config files generated in {}", configDir);
308                 return generatedConfigs;
309             } catch (final IOException e) {
310                 throw new RuntimeException("Unable to generate config files", e);
311             }
312         }
313
314
315         public void updateFeatureFile(final List<File> generated) {
316             // TODO karaf core contains jaxb for feature files, use that for
317             // modification
318             try {
319                 for (final File featureFile : ncFeatureFiles) {
320                     final Document document = XmlUtil.readXmlToDocument(Files
321                             .toString(featureFile, Charsets.UTF_8));
322                     final NodeList childNodes = document.getDocumentElement().getChildNodes();
323
324                     for (int i = 0; i < childNodes.getLength(); i++) {
325                         final Node item = childNodes.item(i);
326                         if (item instanceof Element == false) {
327                             continue;
328                         }
329                         if (item.getLocalName().equals("feature") == false) {
330                             continue;
331                         }
332
333                         if (NETCONF_CONNECTOR_ALL_FEATURE
334                                 .equals(((Element) item).getAttribute("name"))) {
335                             final Element ncAllFeatureDefinition = (Element) item;
336                             // Clean previous generated files
337                             for (final XmlElement configfile : XmlElement
338                                     .fromDomElement(ncAllFeatureDefinition)
339                                     .getChildElements("configfile")) {
340                                 ncAllFeatureDefinition.removeChild(configfile.getDomElement());
341                             }
342                             for (final File file : generated) {
343                                 final Element configfile = document.createElement("configfile");
344                                 configfile.setTextContent("file:"
345                                         + ETC_OPENDAYLIGHT_KARAF_PATH
346                                         + file.getName());
347                                 configfile.setAttribute(
348                                         "finalname",
349                                         ETC_OPENDAYLIGHT_KARAF_PATH
350                                                 + file.getName());
351                                 ncAllFeatureDefinition.appendChild(configfile);
352                             }
353                         }
354                     }
355
356                     Files.write(XmlUtil.toString(document), featureFile,Charsets.UTF_8);
357                     LOG.info("Feature file {} updated", featureFile);
358                 }
359             } catch (final IOException e) {
360                 throw new RuntimeException("Unable to load features file as a resource");
361             } catch (final SAXException e) {
362                 throw new RuntimeException("Unable to parse features file");
363             }
364         }
365
366
367         private static List<File> getFeatureFile(final File distroFolder, final String featureName, final String suffix) {
368             checkExistingDir(distroFolder, String.format("Folder %s does not exist", distroFolder));
369
370             final File systemDir = checkExistingDir(new File(distroFolder, "system"), String.format("Folder %s does not contain a karaf distro, folder system is missing", distroFolder));
371             final File netconfConnectorFeaturesParentDir = checkExistingDir(new File(systemDir, "org/opendaylight/controller/" + featureName), String.format("Karaf distro in %s does not contain netconf-connector features", distroFolder));
372
373             // Find newest version for features
374             final File newestVersionDir = Collections.max(
375                     Lists.newArrayList(netconfConnectorFeaturesParentDir.listFiles(new FileFilter() {
376                         @Override
377                         public boolean accept(final File pathname) {
378                             return pathname.isDirectory();
379                         }
380                     })), new Comparator<File>() {
381                         @Override
382                         public int compare(final File o1, final File o2) {
383                             return o1.getName().compareTo(o2.getName());
384                         }
385                     });
386
387             return Lists.newArrayList(newestVersionDir.listFiles(new FileFilter() {
388                 @Override
389                 public boolean accept(final File pathname) {
390                     return pathname.getName().contains(featureName)
391                             && Files.getFileExtension(pathname.getName()).equals(suffix);
392                 }
393             }));
394         }
395
396         private static File checkExistingDir(final File folder, final String msg) {
397             Preconditions.checkArgument(folder.exists(), msg);
398             Preconditions.checkArgument(folder.isDirectory(), msg);
399             return folder;
400         }
401
402         public void changeLoadOrder() {
403             try {
404                 Files.write(ByteStreams.toByteArray(getClass().getResourceAsStream("/" +ORG_OPS4J_PAX_URL_MVN_CFG)), loadOrderCfgFile);
405                 LOG.info("Load order changed to prefer local bundles/features by rewriting file {}", loadOrderCfgFile);
406             } catch (IOException e) {
407                 throw new RuntimeException("Unable to rewrite features file " + loadOrderCfgFile, e);
408             }
409         }
410     }
411 }