2 * Copyright (c) 2016 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 ch.qos.logback.classic.Level;
12 import com.google.common.base.Stopwatch;
13 import com.google.common.io.CharStreams;
14 import com.ning.http.client.AsyncHttpClient;
15 import com.ning.http.client.AsyncHttpClientConfig.Builder;
16 import com.ning.http.client.Request;
17 import com.ning.http.client.Response;
18 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.InputStreamReader;
23 import java.net.ConnectException;
24 import java.util.List;
25 import java.util.concurrent.Callable;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.concurrent.ScheduledFuture;
29 import java.util.concurrent.ScheduledThreadPoolExecutor;
30 import java.util.concurrent.Semaphore;
31 import java.util.concurrent.TimeUnit;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import org.opendaylight.netconf.test.tool.config.Configuration;
35 import org.opendaylight.netconf.test.tool.config.ConfigurationBuilder;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
39 @SuppressFBWarnings({"DM_EXIT", "DM_DEFAULT_ENCODING", "SLF4J_LOGGER_SHOULD_BE_FINAL"})
40 public final class ScaleUtil {
41 private static final ScheduledExecutorService EXECUTOR = new LoggingWrapperExecutor(4);
42 private static final Semaphore SEMAPHORE = new Semaphore(0);
43 private static final Stopwatch STOPWATCH = Stopwatch.createUnstarted();
45 private static final long TIMEOUT = 20L;
46 private static final long RETRY_DELAY = 10L;
47 private static final int DEVICE_STEP = 1000;
49 private static ch.qos.logback.classic.Logger root;
50 private static Logger resultsLog;
55 @SuppressWarnings("checkstyle:illegalCatch")
56 public static void main(final String[] args) {
57 final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser());
61 // cleanup at the start in case controller was already running
62 final Runtime runtime = Runtime.getRuntime();
63 cleanup(runtime, params);
66 root.warn("Starting scale test with {} devices", params.deviceCount);
67 final ScheduledFuture<?> timeoutGuardFuture = EXECUTOR.schedule(new TimeoutGuard(), TIMEOUT,
69 final Configuration configuration = new ConfigurationBuilder().from(params).build();
70 final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator(configuration);
72 final List<Integer> openDevices = netconfDeviceSimulator.start();
73 if (openDevices.size() == 0) {
74 root.error("Failed to start any simulated devices, exiting...");
78 if (params.distroFolder == null) {
79 root.error("Distro folder is not set, exiting...");
83 final Main.ConfigGenerator configGenerator = new Main.ConfigGenerator(
84 params.distroFolder, openDevices);
85 final List<File> generated = configGenerator.generate(
86 params.ssh, params.generateConfigBatchSize,
87 params.generateConfigsTimeout, params.generateConfigsAddress,
88 params.devicesPerPort);
89 configGenerator.updateFeatureFile(generated);
90 configGenerator.changeLoadOrder();
91 } catch (final Exception e) {
92 root.error("Unhandled exception", e);
93 netconfDeviceSimulator.close();
97 root.warn(params.distroFolder.getAbsolutePath());
99 runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/start");
102 final Process exec = runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/status");
105 } catch (InterruptedException e) {
106 root.warn("Failed to sleep", e);
108 status = CharStreams.toString(new BufferedReader(new InputStreamReader(exec.getInputStream())));
109 root.warn("Current status: {}", status);
110 } while (!status.startsWith("Running ..."));
111 root.warn("Doing feature install {}", params.distroFolder.getAbsolutePath()
112 + "/bin/client -u karaf feature:install odl-restconf-noauth odl-netconf-connector-all");
113 final Process featureInstall = runtime.exec(params.distroFolder.getAbsolutePath()
114 + "/bin/client -u karaf feature:install odl-restconf-noauth odl-netconf-connector-all");
116 CharStreams.toString(new BufferedReader(new InputStreamReader(featureInstall.getInputStream()))));
118 CharStreams.toString(new BufferedReader(new InputStreamReader(featureInstall.getErrorStream()))));
120 } catch (IOException e) {
121 root.warn("Failed to start karaf", e);
125 root.warn("Karaf started, starting stopwatch");
130 new ScaleVerifyCallable(netconfDeviceSimulator, params.deviceCount), RETRY_DELAY, TimeUnit.SECONDS);
131 root.warn("First callable scheduled");
133 root.warn("semaphore released");
134 } catch (InterruptedException e) {
135 throw new RuntimeException(e);
138 timeoutGuardFuture.cancel(false);
139 params.deviceCount += DEVICE_STEP;
140 netconfDeviceSimulator.close();
143 cleanup(runtime, params);
147 private static void setUpLoggers(final TesttoolParameters params) {
148 System.setProperty("log_file_name", "scale-util.log");
150 root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
151 root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
152 resultsLog = LoggerFactory.getLogger("results");
155 private static void cleanup(final Runtime runtime, final TesttoolParameters params) {
157 stopKaraf(runtime, params);
158 deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
160 } catch (IOException | InterruptedException e) {
161 root.warn("Failed to stop karaf", e);
166 private static void stopKaraf(final Runtime runtime, final TesttoolParameters params)
167 throws IOException, InterruptedException {
168 root.info("Stopping karaf and sleeping for 10 sec..");
169 String controllerPid = "";
171 final Process pgrep = runtime.exec("pgrep -f org.apache.karaf.main.Main");
173 controllerPid = CharStreams.toString(new BufferedReader(new InputStreamReader(pgrep.getInputStream())));
174 root.warn(controllerPid);
175 runtime.exec("kill -9 " + controllerPid);
177 Thread.sleep(10000L);
178 } while (!controllerPid.isEmpty());
179 deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
182 private static void deleteFolder(final File folder) {
183 File[] files = folder.listFiles();
184 if (files != null) { //some JVMs return null for empty dirs
185 for (File f : files) {
186 if (f.isDirectory()) {
190 root.warn("Failed to delete {}", f);
195 if (!folder.delete()) {
196 root.warn("Failed to delete {}", folder);
200 private static class ScaleVerifyCallable implements Callable<Void> {
201 private static final Logger LOG = LoggerFactory.getLogger(ScaleVerifyCallable.class);
203 private static final String RESTCONF_URL = "http://127.0.0.1:8181/restconf/operational/"
204 + "network-topology:network-topology/topology/topology-netconf/";
205 private static final Pattern PATTERN = Pattern.compile("connected");
207 private final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(new Builder()
208 .setConnectTimeout(Integer.MAX_VALUE)
209 .setRequestTimeout(Integer.MAX_VALUE)
210 .setAllowPoolingConnections(true)
212 private final NetconfDeviceSimulator simulator;
213 private final int deviceCount;
214 private final Request request;
216 ScaleVerifyCallable(final NetconfDeviceSimulator simulator, final int deviceCount) {
217 LOG.info("New callable created");
218 this.simulator = simulator;
219 this.deviceCount = deviceCount;
220 AsyncHttpClient.BoundRequestBuilder requestBuilder = asyncHttpClient.prepareGet(RESTCONF_URL)
221 .addHeader("content-type", "application/xml")
222 .addHeader("Accept", "application/xml")
223 .setRequestTimeout(Integer.MAX_VALUE);
224 request = requestBuilder.build();
228 public Void call() throws Exception {
230 final Response response = asyncHttpClient.executeRequest(request).get();
232 if (response.getStatusCode() != 200 && response.getStatusCode() != 204) {
233 LOG.warn("Request failed, status code: {}", response.getStatusCode() + response.getStatusText());
234 EXECUTOR.schedule(new ScaleVerifyCallable(simulator, deviceCount), RETRY_DELAY, TimeUnit.SECONDS);
236 final String body = response.getResponseBody();
237 final Matcher matcher = PATTERN.matcher(body);
239 while (matcher.find()) {
242 resultsLog.info("Currently connected devices : {} out of {}, time elapsed: {}",
243 count, deviceCount + 1, STOPWATCH);
244 if (count != deviceCount + 1) {
246 new ScaleVerifyCallable(simulator, deviceCount), RETRY_DELAY, TimeUnit.SECONDS);
249 resultsLog.info("All devices connected in {}", STOPWATCH);
253 } catch (ConnectException | ExecutionException e) {
254 LOG.warn("Failed to connect to Restconf, is the controller running?", e);
255 EXECUTOR.schedule(new ScaleVerifyCallable(simulator, deviceCount), RETRY_DELAY, TimeUnit.SECONDS);
261 private static class TimeoutGuard implements Callable<Void> {
264 resultsLog.warn("Timeout for scale test reached after: {} ..aborting", STOPWATCH);
265 root.warn("Timeout for scale test reached after: {} ..aborting", STOPWATCH);
271 @SuppressWarnings("checkstyle:illegalCatch")
272 public static class LoggingWrapperExecutor extends ScheduledThreadPoolExecutor {
273 public LoggingWrapperExecutor(final int corePoolSize) {
278 public <V> ScheduledFuture<V> schedule(final Callable<V> callable, final long delay, final TimeUnit unit) {
279 return super.schedule(new LogOnExceptionCallable<>(callable), delay, unit);
282 private static class LogOnExceptionCallable<T> implements Callable<T> {
283 private final Callable<T> theCallable;
285 LogOnExceptionCallable(final Callable<T> theCallable) {
286 this.theCallable = theCallable;
292 return theCallable.call();
293 } catch (Exception e) {
295 root.warn("error in executing: " + theCallable + ". It will no longer be run!", e);
297 // rethrow so that the executor can do it's thing
298 throw new RuntimeException(e);