2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.test.tool;
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;
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;
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;
45 public final class Main {
47 private static final Logger LOG = LoggerFactory.getLogger(Main.class);
51 @Arg(dest = "schemas-dir")
52 public File schemasDir;
54 @Arg(dest = "devices-count")
55 public int deviceCount;
57 @Arg(dest = "starting-port")
58 public int startingPort;
60 @Arg(dest = "generate-config-connection-timeout")
61 public int generateConfigsTimeout;
63 @Arg(dest = "generate-config-address")
64 public String generateConfigsAddress;
66 @Arg(dest = "distro-folder")
67 public File distroFolder;
69 @Arg(dest = "generate-configs-batch-size")
70 public int generateConfigBatchSize;
81 static ArgumentParser getParser() {
82 final ArgumentParser parser = ArgumentParsers.newArgumentParser("netconf testool");
84 parser.description("Netconf device simulator. Detailed info can be found at https://wiki.opendaylight.org/view/OpenDaylight_Controller:Netconf:Testtool#Building_testtool");
86 parser.addArgument("--device-count")
90 .help("Number of simulated netconf devices to spin")
91 .dest("devices-count");
93 parser.addArgument("--schemas-dir")
95 .help("Directory containing yang schemas to describe simulated devices. Some schemas e.g. netconf monitoring and inet types are included by default")
98 parser.addArgument("--starting-port")
101 .help("First port for simulated device. Each other device will have previous+1 port number")
102 .dest("starting-port");
104 parser.addArgument("--generate-config-connection-timeout")
106 .setDefault((int)TimeUnit.MINUTES.toMillis(30))
107 .help("Timeout to be generated in initial config files")
108 .dest("generate-config-connection-timeout");
110 parser.addArgument("--generate-config-address")
112 .setDefault("127.0.0.1")
113 .help("Address to be placed in generated configs")
114 .dest("generate-config-address");
116 parser.addArgument("--generate-configs-batch-size")
119 .help("Number of connector configs per generated file")
120 .dest("generate-configs-batch-size");
122 parser.addArgument("--distribution-folder")
124 .help("Directory where the karaf distribution for controller is located")
125 .dest("distro-folder");
127 parser.addArgument("--ssh")
130 .help("Whether to use ssh for transport or just pure tcp")
133 parser.addArgument("--exi")
136 .help("Whether to use exi to transport xml content")
139 parser.addArgument("--debug")
142 .help("Whether to use debug log level instead of INFO")
149 checkArgument(deviceCount > 0, "Device count has to be > 0");
150 checkArgument(startingPort > 1024, "Starting port has to be > 1024");
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");
160 public static void main(final String[] args) {
161 final Params params = parseArgs(args, Params.getParser());
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);
167 final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator();
169 final List<Integer> openDevices = netconfDeviceSimulator.start(params);
170 if(params.distroFolder != null) {
171 final ConfigGenerator configGenerator = new ConfigGenerator(params.distroFolder, openDevices);
172 final List<File> generated = configGenerator.generate(params.ssh, params.generateConfigBatchSize, params.generateConfigsTimeout, params.generateConfigsAddress);
173 configGenerator.updateFeatureFile(generated);
174 configGenerator.changeLoadOrder();
176 } catch (final Exception e) {
177 LOG.error("Unhandled exception", e);
178 netconfDeviceSimulator.close();
183 synchronized (netconfDeviceSimulator) {
185 netconfDeviceSimulator.wait();
186 } catch (final InterruptedException e) {
187 throw new RuntimeException(e);
192 private static Params parseArgs(final String[] args, final ArgumentParser parser) {
193 final Params opt = new Params();
195 parser.parseArgs(args, opt);
197 } catch (final ArgumentParserException e) {
198 parser.handleError(e);
205 private static class ConfigGenerator {
206 public static final String NETCONF_CONNECTOR_XML = "/initial/99-netconf-connector.xml";
207 public static final String NETCONF_CONNECTOR_NAME = "controller-config";
208 public static final String NETCONF_CONNECTOR_PORT = "1830";
209 public static final String NETCONF_CONNECTOR_ADDRESS = "127.0.0.1";
210 public static final String NETCONF_USE_SSH = "false";
211 public static final String SIM_DEVICE_SUFFIX = "-sim-device";
213 private static final String SIM_DEVICE_CFG_PREFIX = "simulated-devices_";
214 private static final String ETC_KARAF_PATH = "etc/";
215 private static final String ETC_OPENDAYLIGHT_KARAF_PATH = ETC_KARAF_PATH + "opendaylight/karaf/";
217 public static final String NETCONF_CONNECTOR_ALL_FEATURE = "odl-netconf-connector-all";
218 private static final String ORG_OPS4J_PAX_URL_MVN_CFG = "org.ops4j.pax.url.mvn.cfg";
220 private final File configDir;
221 private final List<Integer> openDevices;
222 private final List<File> ncFeatureFiles;
223 private final File etcDir;
224 private final File loadOrderCfgFile;
226 public ConfigGenerator(final File directory, final List<Integer> openDevices) {
227 this.configDir = new File(directory, ETC_OPENDAYLIGHT_KARAF_PATH);
228 this.etcDir = new File(directory, ETC_KARAF_PATH);
229 this.loadOrderCfgFile = new File(etcDir, ORG_OPS4J_PAX_URL_MVN_CFG);
230 this.ncFeatureFiles = getFeatureFile(directory, "features-netconf-connector", "xml");
231 this.openDevices = openDevices;
234 public List<File> generate(final boolean useSsh, final int batchSize, final int generateConfigsTimeout, final String address) {
235 if(configDir.exists() == false) {
236 Preconditions.checkState(configDir.mkdirs(), "Unable to create directory " + configDir);
239 for (final File file : configDir.listFiles(new FileFilter() {
241 public boolean accept(final File pathname) {
242 return !pathname.isDirectory() && pathname.getName().startsWith(SIM_DEVICE_CFG_PREFIX);
245 Preconditions.checkState(file.delete(), "Unable to clean previous generated file %s", file);
248 try(InputStream stream = Main.class.getResourceAsStream(NETCONF_CONNECTOR_XML)) {
249 checkNotNull(stream, "Cannot load %s", NETCONF_CONNECTOR_XML);
250 String configBlueprint = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
252 checkState(configBlueprint.contains(NETCONF_CONNECTOR_NAME));
253 checkState(configBlueprint.contains(NETCONF_CONNECTOR_PORT));
254 checkState(configBlueprint.contains(NETCONF_USE_SSH));
255 checkState(configBlueprint.contains(NETCONF_CONNECTOR_ADDRESS));
256 configBlueprint = configBlueprint.replace(NETCONF_CONNECTOR_NAME, "%s");
257 configBlueprint = configBlueprint.replace(NETCONF_CONNECTOR_ADDRESS, "%s");
258 configBlueprint = configBlueprint.replace(NETCONF_CONNECTOR_PORT, "%s");
259 configBlueprint = configBlueprint.replace(NETCONF_USE_SSH, "%s");
261 final String before = configBlueprint.substring(0, configBlueprint.indexOf("<module>"));
262 final String middleBlueprint = configBlueprint.substring(configBlueprint.indexOf("<module>"), configBlueprint.indexOf("</module>"));
263 final String after = configBlueprint.substring(configBlueprint.indexOf("</module>") + "</module>".length());
265 int connectorCount = 0;
266 Integer batchStart = null;
267 StringBuilder b = new StringBuilder();
270 final List<File> generatedConfigs = Lists.newArrayList();
272 for (final Integer openDevice : openDevices) {
273 if(batchStart == null) {
274 batchStart = openDevice;
277 final String name = String.valueOf(openDevice) + SIM_DEVICE_SUFFIX;
278 String configContent = String.format(middleBlueprint, name, address, String.valueOf(openDevice), String.valueOf(!useSsh));
279 configContent = String.format("%s%s%d%s\n%s\n", configContent, "<connection-timeout-millis>", generateConfigsTimeout, "</connection-timeout-millis>", "</module>");
281 b.append(configContent);
283 if(connectorCount == batchSize) {
285 final File to = new File(configDir, String.format(SIM_DEVICE_CFG_PREFIX + "%d-%d.xml", batchStart, openDevice));
286 generatedConfigs.add(to);
287 Files.write(b.toString(), to, Charsets.UTF_8);
289 b = new StringBuilder();
296 if(connectorCount != 0) {
298 final File to = new File(configDir, String.format(SIM_DEVICE_CFG_PREFIX + "%d-%d.xml", batchStart, openDevices.get(openDevices.size() - 1)));
299 generatedConfigs.add(to);
300 Files.write(b.toString(), to, Charsets.UTF_8);
303 LOG.info("Config files generated in {}", configDir);
304 return generatedConfigs;
305 } catch (final IOException e) {
306 throw new RuntimeException("Unable to generate config files", e);
311 public void updateFeatureFile(final List<File> generated) {
312 // TODO karaf core contains jaxb for feature files, use that for
315 for (final File featureFile : ncFeatureFiles) {
316 final Document document = XmlUtil.readXmlToDocument(Files
317 .toString(featureFile, Charsets.UTF_8));
318 final NodeList childNodes = document.getDocumentElement().getChildNodes();
320 for (int i = 0; i < childNodes.getLength(); i++) {
321 final Node item = childNodes.item(i);
322 if (item instanceof Element == false) {
325 if (item.getLocalName().equals("feature") == false) {
329 if (NETCONF_CONNECTOR_ALL_FEATURE
330 .equals(((Element) item).getAttribute("name"))) {
331 final Element ncAllFeatureDefinition = (Element) item;
332 // Clean previous generated files
333 for (final XmlElement configfile : XmlElement
334 .fromDomElement(ncAllFeatureDefinition)
335 .getChildElements("configfile")) {
336 ncAllFeatureDefinition.removeChild(configfile.getDomElement());
338 for (final File file : generated) {
339 final Element configfile = document.createElement("configfile");
340 configfile.setTextContent("file:"
341 + ETC_OPENDAYLIGHT_KARAF_PATH
343 configfile.setAttribute(
345 ETC_OPENDAYLIGHT_KARAF_PATH
347 ncAllFeatureDefinition.appendChild(configfile);
352 Files.write(XmlUtil.toString(document), featureFile,Charsets.UTF_8);
353 LOG.info("Feature file {} updated", featureFile);
355 } catch (final IOException e) {
356 throw new RuntimeException("Unable to load features file as a resource");
357 } catch (final SAXException e) {
358 throw new RuntimeException("Unable to parse features file");
363 private static List<File> getFeatureFile(final File distroFolder, final String featureName, final String suffix) {
364 checkExistingDir(distroFolder, String.format("Folder %s does not exist", distroFolder));
366 final File systemDir = checkExistingDir(new File(distroFolder, "system"), String.format("Folder %s does not contain a karaf distro, folder system is missing", distroFolder));
367 final File netconfConnectorFeaturesParentDir = checkExistingDir(new File(systemDir, "org/opendaylight/controller/" + featureName), String.format("Karaf distro in %s does not contain netconf-connector features", distroFolder));
369 // Find newest version for features
370 final File newestVersionDir = Collections.max(
371 Lists.newArrayList(netconfConnectorFeaturesParentDir.listFiles(new FileFilter() {
373 public boolean accept(final File pathname) {
374 return pathname.isDirectory();
376 })), new Comparator<File>() {
378 public int compare(final File o1, final File o2) {
379 return o1.getName().compareTo(o2.getName());
383 return Lists.newArrayList(newestVersionDir.listFiles(new FileFilter() {
385 public boolean accept(final File pathname) {
386 return pathname.getName().contains(featureName)
387 && Files.getFileExtension(pathname.getName()).equals(suffix);
392 private static File checkExistingDir(final File folder, final String msg) {
393 Preconditions.checkArgument(folder.exists(), msg);
394 Preconditions.checkArgument(folder.isDirectory(), msg);
398 public void changeLoadOrder() {
400 Files.write(ByteStreams.toByteArray(getClass().getResourceAsStream("/" +ORG_OPS4J_PAX_URL_MVN_CFG)), loadOrderCfgFile);
401 LOG.info("Load order changed to prefer local bundles/features by rewriting file {}", loadOrderCfgFile);
402 } catch (IOException e) {
403 throw new RuntimeException("Unable to rewrite features file " + loadOrderCfgFile, e);