Improve logging in netconf test tool
[netconf.git] / netconf / tools / netconf-testtool / src / main / java / org / opendaylight / 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.netconf.test.tool;
10
11 import static com.google.common.base.Preconditions.checkNotNull;
12
13 import ch.qos.logback.classic.Level;
14 import com.google.common.base.Charsets;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Stopwatch;
17 import com.google.common.collect.Lists;
18 import com.google.common.io.ByteStreams;
19 import com.google.common.io.CharStreams;
20 import com.google.common.io.Files;
21 import java.io.File;
22 import java.io.FileFilter;
23 import java.io.FileInputStream;
24 import java.io.FileNotFoundException;
25 import java.io.FileWriter;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.util.ArrayList;
30 import java.util.Collections;
31 import java.util.Comparator;
32 import java.util.List;
33 import java.util.concurrent.ExecutionException;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import java.util.concurrent.Future;
37 import java.util.concurrent.TimeUnit;
38 import javax.xml.bind.JAXBException;
39 import org.apache.karaf.features.internal.model.ConfigFile;
40 import org.apache.karaf.features.internal.model.Feature;
41 import org.apache.karaf.features.internal.model.Features;
42 import org.apache.karaf.features.internal.model.JaxbUtil;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46
47 public final class Main {
48
49     private static final Logger LOG = LoggerFactory.getLogger(Main.class);
50     
51     public static void main(final String[] args) {
52         final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser());
53         params.validate();
54         final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
55         root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
56
57         final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator(params.threadPoolSize);
58         try {
59             LOG.debug("Trying to start netconf test-tool with parameters {}", params);
60             final List<Integer> openDevices = netconfDeviceSimulator.start(params);
61             if (openDevices.size() == 0) {
62                 LOG.error("Failed to start any simulated devices, exiting...");
63                 System.exit(1);
64             }
65             if (params.controllerDestination != null) {
66                 final ArrayList<ArrayList<Execution.DestToPayload>> allThreadsPayloads = params.getThreadsPayloads(openDevices);
67                 final ArrayList<Execution> executions = new ArrayList<>();
68                 for (ArrayList<Execution.DestToPayload> payloads : allThreadsPayloads) {
69                     executions.add(new Execution(params, payloads));
70                 }
71                 final ExecutorService executorService = Executors.newFixedThreadPool(params.threadAmount);
72                 final Stopwatch time = Stopwatch.createStarted();
73                 List<Future<Void>> futures = executorService.invokeAll(executions, params.timeOut, TimeUnit.SECONDS);
74                 int threadNum = 0;
75                 for(Future<Void> future : futures){
76                     threadNum++;
77                     if (future.isCancelled()) {
78                         LOG.info("{}. thread timed out.",threadNum);
79                     } else {
80                         try {
81                             future.get();
82                         } catch (final ExecutionException e) {
83                             LOG.info("{}. thread failed.", threadNum, e);
84                         }
85                     }
86                 }
87                 time.stop();
88                 LOG.info("Time spent with configuration of devices: {}.",time);
89             }
90
91             if (params.distroFolder != null) {
92                 final ConfigGenerator configGenerator = new ConfigGenerator(params.distroFolder, openDevices);
93                 final List<File> generated = configGenerator.generate(
94                         params.ssh, params.generateConfigBatchSize,
95                         params.generateConfigsTimeout, params.generateConfigsAddress,
96                         params.devicesPerPort);
97                 configGenerator.updateFeatureFile(generated);
98                 configGenerator.changeLoadOrder();
99             }
100         } catch (final Exception e) {
101             LOG.error("Unhandled exception", e);
102             netconfDeviceSimulator.close();
103             System.exit(1);
104         }
105
106         // Block main thread
107         synchronized (netconfDeviceSimulator) {
108             try {
109                 netconfDeviceSimulator.wait();
110             } catch (final InterruptedException e) {
111                 throw new RuntimeException(e);
112             }
113         }
114     }
115
116     static class ConfigGenerator {
117         public static final String NETCONF_CONNECTOR_XML = "/99-netconf-connector-simulated.xml";
118         public static final String SIM_DEVICE_SUFFIX = "-sim-device";
119
120         private static final String SIM_DEVICE_CFG_PREFIX = "simulated-devices_";
121         private static final String ETC_KARAF_PATH = "etc/";
122         private static final String ETC_OPENDAYLIGHT_KARAF_PATH = ETC_KARAF_PATH + "opendaylight/karaf/";
123
124         public static final String NETCONF_CONNECTOR_ALL_FEATURE = "odl-netconf-connector-all";
125         private static final String ORG_OPS4J_PAX_URL_MVN_CFG = "org.ops4j.pax.url.mvn.cfg";
126
127         private final File configDir;
128         private final List<Integer> openDevices;
129         private final List<File> ncFeatureFiles;
130         private final File etcDir;
131         private final File loadOrderCfgFile;
132
133         public ConfigGenerator(final File directory, final List<Integer> openDevices) {
134             this.configDir = new File(directory, ETC_OPENDAYLIGHT_KARAF_PATH);
135             this.etcDir = new File(directory, ETC_KARAF_PATH);
136             this.loadOrderCfgFile = new File(etcDir, ORG_OPS4J_PAX_URL_MVN_CFG);
137             this.ncFeatureFiles = getFeatureFile(directory, "features-netconf-connector", "xml");
138             this.openDevices = openDevices;
139         }
140
141         public List<File> generate(final boolean useSsh, final int batchSize,
142                                    final int generateConfigsTimeout, final String address,
143                                    final int devicesPerPort) {
144             if (configDir.exists() == false) {
145                 Preconditions.checkState(configDir.mkdirs(), "Unable to create directory " + configDir);
146             }
147
148             for (final File file : configDir.listFiles(new FileFilter() {
149                 @Override
150                 public boolean accept(final File pathname) {
151                     return !pathname.isDirectory() && pathname.getName().startsWith(SIM_DEVICE_CFG_PREFIX);
152                 }
153             })) {
154                 Preconditions.checkState(file.delete(), "Unable to clean previous generated file %s", file);
155             }
156
157             try (InputStream stream = Main.class.getResourceAsStream(NETCONF_CONNECTOR_XML)) {
158                 checkNotNull(stream, "Cannot load %s", NETCONF_CONNECTOR_XML);
159                 String configBlueprint = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
160
161                 final String before = configBlueprint.substring(0, configBlueprint.indexOf("<module>"));
162                 final String middleBlueprint = configBlueprint.substring(configBlueprint.indexOf("<module>"), configBlueprint.indexOf("</module>"));
163                 final String after = configBlueprint.substring(configBlueprint.indexOf("</module>") + "</module>".length());
164
165                 int connectorCount = 0;
166                 Integer batchStart = null;
167                 StringBuilder b = new StringBuilder();
168                 b.append(before);
169
170                 final List<File> generatedConfigs = Lists.newArrayList();
171
172                 for (final Integer openDevice : openDevices) {
173                     if (batchStart == null) {
174                         batchStart = openDevice;
175                     }
176
177                     for (int i = 0; i < devicesPerPort; i++) {
178                         final String name = String.valueOf(openDevice) + SIM_DEVICE_SUFFIX + (i == 0 ? "" : "-" + String.valueOf(i));
179                         String configContent = String.format(middleBlueprint, name, address, String.valueOf(openDevice), String.valueOf(!useSsh));
180                         configContent = String.format("%s%s%d%s\n%s\n", configContent, "<connection-timeout-millis>", generateConfigsTimeout, "</connection-timeout-millis>", "</module>");
181
182                         b.append(configContent);
183                         connectorCount++;
184                         if (connectorCount == batchSize) {
185                             b.append(after);
186                             final File to = new File(configDir, String.format(SIM_DEVICE_CFG_PREFIX + "%d-%d.xml", batchStart, openDevice));
187                             generatedConfigs.add(to);
188                             Files.write(b.toString(), to, Charsets.UTF_8);
189                             connectorCount = 0;
190                             b = new StringBuilder();
191                             b.append(before);
192                             batchStart = null;
193                         }
194                     }
195                 }
196
197                 // Write remaining
198                 if (connectorCount != 0) {
199                     b.append(after);
200                     final File to = new File(configDir, String.format(SIM_DEVICE_CFG_PREFIX + "%d-%d.xml", batchStart, openDevices.get(openDevices.size() - 1)));
201                     generatedConfigs.add(to);
202                     Files.write(b.toString(), to, Charsets.UTF_8);
203                 }
204
205                 LOG.info("Config files generated in {}", configDir);
206                 return generatedConfigs;
207             } catch (final IOException e) {
208                 throw new RuntimeException("Unable to generate config files", e);
209             }
210         }
211
212
213         public void updateFeatureFile(final List<File> generated) {
214             for (final File fileFeatures : ncFeatureFiles) {
215                 try {
216                     final Features f =  JaxbUtil.unmarshal(new FileInputStream(fileFeatures), false);
217
218                     for (final Feature feature : f.getFeature()) {
219                         if (NETCONF_CONNECTOR_ALL_FEATURE.equals(feature.getName())) {
220                             //Clean all previously generated configFiles
221                             feature.getConfigfile().clear();
222
223                             //Create new configFiles
224                             for (final File gen : generated) {
225                                 final ConfigFile cf = new ConfigFile();
226
227                                 final String generatedName = ETC_OPENDAYLIGHT_KARAF_PATH + gen.getName();
228
229                                 cf.setFinalname(generatedName);
230                                 cf.setLocation("file:" + generatedName);
231
232                                 feature.getConfigfile().add(cf);
233                                 }
234                             }
235                         }
236                     JaxbUtil.marshal(f, new FileWriter(fileFeatures));
237                     LOG.info("Feature file {} updated", fileFeatures);
238                 } catch (JAXBException | IOException e) {
239                     throw new RuntimeException(e);
240                 }
241             }
242         }
243
244
245         private static List<File> getFeatureFile(final File distroFolder, final String featureName, final String suffix) {
246             checkExistingDir(distroFolder, String.format("Folder %s does not exist", distroFolder));
247
248             final File systemDir = checkExistingDir(new File(distroFolder, "system"), String.format("Folder %s does not contain a karaf distro, folder system is missing", distroFolder));
249
250             //check if beryllium path exists, if it doesnt check for lithium and fail/succeed after
251             File netconfConnectorFeaturesParentDir = new File(systemDir, "org/opendaylight/netconf/" + featureName);
252             if (!netconfConnectorFeaturesParentDir.exists() || !netconfConnectorFeaturesParentDir.isDirectory()) {
253                 netconfConnectorFeaturesParentDir = checkExistingDir(new File(systemDir, "org/opendaylight/controller/" + featureName), String.format("Karaf distro in %s does not contain netconf-connector features", distroFolder));
254             }
255
256             // Find newest version for features
257             final File newestVersionDir = Collections.max(
258                     Lists.newArrayList(netconfConnectorFeaturesParentDir.listFiles(new FileFilter() {
259                         @Override
260                         public boolean accept(final File pathname) {
261                             return pathname.isDirectory();
262                         }
263                     })), new Comparator<File>() {
264                         @Override
265                         public int compare(final File o1, final File o2) {
266                             return o1.getName().compareTo(o2.getName());
267                         }
268                     });
269
270             return Lists.newArrayList(newestVersionDir.listFiles(new FileFilter() {
271                 @Override
272                 public boolean accept(final File pathname) {
273                     return pathname.getName().contains(featureName)
274                             && Files.getFileExtension(pathname.getName()).equals(suffix);
275                 }
276             }));
277         }
278
279         private static File checkExistingDir(final File folder, final String msg) {
280             Preconditions.checkArgument(folder.exists(), msg);
281             Preconditions.checkArgument(folder.isDirectory(), msg);
282             return folder;
283         }
284
285         public void changeLoadOrder() {
286             try {
287                 Files.write(ByteStreams.toByteArray(getClass().getResourceAsStream("/" + ORG_OPS4J_PAX_URL_MVN_CFG)), loadOrderCfgFile);
288                 LOG.info("Load order changed to prefer local bundles/features by rewriting file {}", loadOrderCfgFile);
289             } catch (IOException e) {
290                 throw new RuntimeException("Unable to rewrite features file " + loadOrderCfgFile, e);
291             }
292         }
293     }
294 }