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.netconf.test.tool;
11 import static com.google.common.base.Preconditions.checkNotNull;
13 import ch.qos.logback.classic.Level;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Stopwatch;
16 import com.google.common.collect.Lists;
17 import com.google.common.io.ByteStreams;
18 import com.google.common.io.CharStreams;
19 import com.google.common.io.Files;
21 import java.io.FileFilter;
22 import java.io.FileInputStream;
23 import java.io.FileWriter;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.nio.charset.StandardCharsets;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.Comparator;
31 import java.util.List;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.Future;
36 import java.util.concurrent.TimeUnit;
37 import javax.xml.bind.JAXBException;
38 import org.apache.karaf.features.internal.model.ConfigFile;
39 import org.apache.karaf.features.internal.model.Feature;
40 import org.apache.karaf.features.internal.model.Features;
41 import org.apache.karaf.features.internal.model.JaxbUtil;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 public final class Main {
48 private static final Logger LOG = LoggerFactory.getLogger(Main.class);
50 public static void main(final String[] args) {
51 final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser());
53 final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
54 root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
56 final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator(params.threadPoolSize);
58 LOG.debug("Trying to start netconf test-tool with parameters {}", params);
59 final List<Integer> openDevices = netconfDeviceSimulator.start(params);
60 if (openDevices.size() == 0) {
61 LOG.error("Failed to start any simulated devices, exiting...");
64 if (params.controllerDestination != null) {
65 final ArrayList<ArrayList<Execution.DestToPayload>> allThreadsPayloads = params.getThreadsPayloads(openDevices);
66 final ArrayList<Execution> executions = new ArrayList<>();
67 for (ArrayList<Execution.DestToPayload> payloads : allThreadsPayloads) {
68 executions.add(new Execution(params, payloads));
70 final ExecutorService executorService = Executors.newFixedThreadPool(params.threadAmount);
71 final Stopwatch time = Stopwatch.createStarted();
72 List<Future<Void>> futures = executorService.invokeAll(executions, params.timeOut, TimeUnit.SECONDS);
74 for(Future<Void> future : futures){
76 if (future.isCancelled()) {
77 LOG.info("{}. thread timed out.",threadNum);
81 } catch (final ExecutionException e) {
82 LOG.info("{}. thread failed.", threadNum, e);
87 LOG.info("Time spent with configuration of devices: {}.",time);
90 if (params.distroFolder != null) {
91 final ConfigGenerator configGenerator = new ConfigGenerator(params.distroFolder, openDevices);
92 final List<File> generated = configGenerator.generate(
93 params.ssh, params.generateConfigBatchSize,
94 params.generateConfigsTimeout, params.generateConfigsAddress,
95 params.devicesPerPort);
96 configGenerator.updateFeatureFile(generated);
97 configGenerator.changeLoadOrder();
99 } catch (final Exception e) {
100 LOG.error("Unhandled exception", e);
101 netconfDeviceSimulator.close();
106 synchronized (netconfDeviceSimulator) {
108 netconfDeviceSimulator.wait();
109 } catch (final InterruptedException e) {
110 throw new RuntimeException(e);
115 static class ConfigGenerator {
116 public static final String NETCONF_CONNECTOR_XML = "/99-netconf-connector-simulated.xml";
117 public static final String SIM_DEVICE_SUFFIX = "-sim-device";
119 private static final String SIM_DEVICE_CFG_PREFIX = "simulated-devices_";
120 private static final String ETC_KARAF_PATH = "etc/";
121 private static final String ETC_OPENDAYLIGHT_KARAF_PATH = ETC_KARAF_PATH + "opendaylight/karaf/";
123 public static final String NETCONF_CONNECTOR_ALL_FEATURE = "odl-netconf-connector-all";
124 private static final String ORG_OPS4J_PAX_URL_MVN_CFG = "org.ops4j.pax.url.mvn.cfg";
126 private final File configDir;
127 private final List<Integer> openDevices;
128 private final List<File> ncFeatureFiles;
129 private final File etcDir;
130 private final File loadOrderCfgFile;
132 public ConfigGenerator(final File directory, final List<Integer> openDevices) {
133 this.configDir = new File(directory, ETC_OPENDAYLIGHT_KARAF_PATH);
134 this.etcDir = new File(directory, ETC_KARAF_PATH);
135 this.loadOrderCfgFile = new File(etcDir, ORG_OPS4J_PAX_URL_MVN_CFG);
136 this.ncFeatureFiles = getFeatureFile(directory, "features-netconf-connector", "xml");
137 this.openDevices = openDevices;
140 public List<File> generate(final boolean useSsh, final int batchSize,
141 final int generateConfigsTimeout, final String address,
142 final int devicesPerPort) {
143 if (configDir.exists() == false) {
144 Preconditions.checkState(configDir.mkdirs(), "Unable to create directory " + configDir);
147 for (final File file : configDir.listFiles(new FileFilter() {
149 public boolean accept(final File pathname) {
150 return !pathname.isDirectory() && pathname.getName().startsWith(SIM_DEVICE_CFG_PREFIX);
153 Preconditions.checkState(file.delete(), "Unable to clean previous generated file %s", file);
156 try (InputStream stream = Main.class.getResourceAsStream(NETCONF_CONNECTOR_XML)) {
157 checkNotNull(stream, "Cannot load %s", NETCONF_CONNECTOR_XML);
158 String configBlueprint = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8));
160 final String before = configBlueprint.substring(0, configBlueprint.indexOf("<module>"));
161 final String middleBlueprint = configBlueprint.substring(configBlueprint.indexOf("<module>"), configBlueprint.indexOf("</module>"));
162 final String after = configBlueprint.substring(configBlueprint.indexOf("</module>") + "</module>".length());
164 int connectorCount = 0;
165 Integer batchStart = null;
166 StringBuilder b = new StringBuilder();
169 final List<File> generatedConfigs = Lists.newArrayList();
171 for (final Integer openDevice : openDevices) {
172 if (batchStart == null) {
173 batchStart = openDevice;
176 for (int i = 0; i < devicesPerPort; i++) {
177 final String name = String.valueOf(openDevice) + SIM_DEVICE_SUFFIX + (i == 0 ? "" : "-" + String.valueOf(i));
178 String configContent = String.format(middleBlueprint, name, address, String.valueOf(openDevice), String.valueOf(!useSsh));
179 configContent = String.format("%s%s%d%s\n%s\n", configContent, "<connection-timeout-millis>", generateConfigsTimeout, "</connection-timeout-millis>", "</module>");
181 b.append(configContent);
183 if (connectorCount == batchSize) {
185 final File to = new File(configDir, String.format(SIM_DEVICE_CFG_PREFIX + "%d-%d.xml", batchStart, openDevice));
186 generatedConfigs.add(to);
187 Files.write(b.toString(), to, StandardCharsets.UTF_8);
189 b = new StringBuilder();
197 if (connectorCount != 0) {
199 final File to = new File(configDir, String.format(SIM_DEVICE_CFG_PREFIX + "%d-%d.xml", batchStart, openDevices.get(openDevices.size() - 1)));
200 generatedConfigs.add(to);
201 Files.write(b.toString(), to, StandardCharsets.UTF_8);
204 LOG.info("Config files generated in {}", configDir);
205 return generatedConfigs;
206 } catch (final IOException e) {
207 throw new RuntimeException("Unable to generate config files", e);
212 public void updateFeatureFile(final List<File> generated) {
213 for (final File fileFeatures : ncFeatureFiles) {
215 final Features f = JaxbUtil.unmarshal(new FileInputStream(fileFeatures), false);
217 for (final Feature feature : f.getFeature()) {
218 if (NETCONF_CONNECTOR_ALL_FEATURE.equals(feature.getName())) {
219 //Clean all previously generated configFiles
220 feature.getConfigfile().clear();
222 //Create new configFiles
223 for (final File gen : generated) {
224 final ConfigFile cf = new ConfigFile();
226 final String generatedName = ETC_OPENDAYLIGHT_KARAF_PATH + gen.getName();
228 cf.setFinalname(generatedName);
229 cf.setLocation("file:" + generatedName);
231 feature.getConfigfile().add(cf);
235 JaxbUtil.marshal(f, new FileWriter(fileFeatures));
236 LOG.info("Feature file {} updated", fileFeatures);
237 } catch (JAXBException | IOException e) {
238 throw new RuntimeException(e);
244 private static List<File> getFeatureFile(final File distroFolder, final String featureName, final String suffix) {
245 checkExistingDir(distroFolder, String.format("Folder %s does not exist", distroFolder));
247 final File systemDir = checkExistingDir(new File(distroFolder, "system"), String.format("Folder %s does not contain a karaf distro, folder system is missing", distroFolder));
249 //check if beryllium path exists, if it doesnt check for lithium and fail/succeed after
250 File netconfConnectorFeaturesParentDir = new File(systemDir, "org/opendaylight/netconf/" + featureName);
251 if (!netconfConnectorFeaturesParentDir.exists() || !netconfConnectorFeaturesParentDir.isDirectory()) {
252 netconfConnectorFeaturesParentDir = checkExistingDir(new File(systemDir, "org/opendaylight/controller/" + featureName), String.format("Karaf distro in %s does not contain netconf-connector features", distroFolder));
255 // Find newest version for features
256 final File newestVersionDir = Collections.max(
257 Lists.newArrayList(netconfConnectorFeaturesParentDir.listFiles(new FileFilter() {
259 public boolean accept(final File pathname) {
260 return pathname.isDirectory();
262 })), new Comparator<File>() {
264 public int compare(final File o1, final File o2) {
265 return o1.getName().compareTo(o2.getName());
269 return Lists.newArrayList(newestVersionDir.listFiles(new FileFilter() {
271 public boolean accept(final File pathname) {
272 return pathname.getName().contains(featureName)
273 && Files.getFileExtension(pathname.getName()).equals(suffix);
278 private static File checkExistingDir(final File folder, final String msg) {
279 Preconditions.checkArgument(folder.exists(), msg);
280 Preconditions.checkArgument(folder.isDirectory(), msg);
284 public void changeLoadOrder() {
286 Files.write(ByteStreams.toByteArray(getClass().getResourceAsStream("/" + ORG_OPS4J_PAX_URL_MVN_CFG)), loadOrderCfgFile);
287 LOG.info("Load order changed to prefer local bundles/features by rewriting file {}", loadOrderCfgFile);
288 } catch (IOException e) {
289 throw new RuntimeException("Unable to rewrite features file " + loadOrderCfgFile, e);