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 java.io.BufferedReader;
20 import java.io.IOException;
21 import java.io.InputStreamReader;
22 import java.net.ConnectException;
23 import java.util.List;
24 import java.util.concurrent.Callable;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.ScheduledExecutorService;
27 import java.util.concurrent.ScheduledFuture;
28 import java.util.concurrent.ScheduledThreadPoolExecutor;
29 import java.util.concurrent.Semaphore;
30 import java.util.concurrent.TimeUnit;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import net.sourceforge.argparse4j.inf.ArgumentParser;
34 import net.sourceforge.argparse4j.inf.ArgumentParserException;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 public class ScaleUtil {
40 private static final Logger RESULTS_LOG = LoggerFactory.getLogger("results");
41 private static final ScheduledExecutorService executor = new LoggingWrapperExecutor(4);
43 private static final int deviceStep = 1000;
44 private static final long retryDelay = 10l;
45 private static final long timeout = 20l;
47 private static final Stopwatch stopwatch = Stopwatch.createUnstarted();
49 private static ScheduledFuture timeoutGuardFuture;
50 private static ch.qos.logback.classic.Logger root;
51 private static final Semaphore semaphore = new Semaphore(0);
53 public static void main(final String[] args) {
54 final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser());
56 root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
57 root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
59 // cleanup at the start in case controller was already running
60 final Runtime runtime = Runtime.getRuntime();
61 cleanup(runtime, params);
64 root.warn("Starting scale test with {} devices", params.deviceCount);
65 timeoutGuardFuture = executor.schedule(new TimeoutGuard(), timeout, TimeUnit.MINUTES);
66 final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator();
68 final List<Integer> openDevices = netconfDeviceSimulator.start(params);
69 if (openDevices.size() == 0) {
70 root.error("Failed to start any simulated devices, exiting...");
73 if (params.distroFolder != null) {
74 final Main.ConfigGenerator configGenerator = new Main.ConfigGenerator(params.distroFolder, openDevices);
75 final List<File> generated = configGenerator.generate(
76 params.ssh, params.generateConfigBatchSize,
77 params.generateConfigsTimeout, params.generateConfigsAddress,
78 params.devicesPerPort);
79 configGenerator.updateFeatureFile(generated);
80 configGenerator.changeLoadOrder();
82 } catch (final Exception e) {
83 root.error("Unhandled exception", e);
84 netconfDeviceSimulator.close();
88 root.warn(params.distroFolder.getAbsolutePath());
90 runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/start");
93 final Process exec = runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/status");
96 } catch (InterruptedException e) {
97 root.warn("Failed to sleep", e);
99 status = CharStreams.toString(new BufferedReader(new InputStreamReader(exec.getInputStream())));
100 root.warn("Current status: {}", status);
101 } while (!status.startsWith("Running ..."));
102 root.warn("Doing feature install {}", params.distroFolder.getAbsolutePath() + "/bin/client -u karaf feature:install odl-restconf-noauth odl-netconf-connector-all");
103 final Process featureInstall = runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/client -u karaf feature:install odl-restconf-noauth odl-netconf-connector-all");
104 root.warn(CharStreams.toString(new BufferedReader(new InputStreamReader(featureInstall.getInputStream()))));
105 root.warn(CharStreams.toString(new BufferedReader(new InputStreamReader(featureInstall.getErrorStream()))));
107 } catch (IOException e) {
108 root.warn("Failed to start karaf", e);
112 root.warn("Karaf started, starting stopwatch");
116 executor.schedule(new ScaleVerifyCallable(netconfDeviceSimulator, params.deviceCount), retryDelay, TimeUnit.SECONDS);
117 root.warn("First callable scheduled");
119 root.warn("semaphore released");
120 } catch (InterruptedException e) {
121 throw new RuntimeException(e);
124 timeoutGuardFuture.cancel(false);
125 params.deviceCount += deviceStep;
126 netconfDeviceSimulator.close();
129 cleanup(runtime, params);
133 private static void cleanup(final Runtime runtime, final TesttoolParameters params) {
135 stopKaraf(runtime, params);
136 deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
138 } catch (IOException | InterruptedException e) {
139 root.warn("Failed to stop karaf", e);
144 private static void stopKaraf(final Runtime runtime, final TesttoolParameters params) throws IOException, InterruptedException {
145 root.info("Stopping karaf and sleeping for 10 sec..");
146 String controllerPid = "";
149 final Process pgrep = runtime.exec("pgrep -f org.apache.karaf.main.Main");
151 controllerPid = CharStreams.toString(new BufferedReader(new InputStreamReader(pgrep.getInputStream())));
152 root.warn(controllerPid);
153 runtime.exec("kill -9 " + controllerPid);
155 Thread.sleep(10000l);
156 } while (!controllerPid.isEmpty());
157 deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
160 private static void deleteFolder(File folder) {
161 File[] files = folder.listFiles();
162 if(files!=null) { //some JVMs return null for empty dirs
164 if(f.isDirectory()) {
174 private static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) {
175 final TesttoolParameters parameters = new TesttoolParameters();
177 parser.parseArgs(args, parameters);
179 } catch (ArgumentParserException e) {
180 parser.handleError(e);
187 private static class ScaleVerifyCallable implements Callable {
189 private static final Logger LOG = LoggerFactory.getLogger(ScaleVerifyCallable.class);
191 private static final String RESTCONF_URL = "http://127.0.0.1:8181/restconf/operational/network-topology:network-topology/topology/topology-netconf/";
192 private static final Pattern PATTERN = Pattern.compile("connected");
194 private final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(new Builder()
195 .setConnectTimeout(Integer.MAX_VALUE)
196 .setRequestTimeout(Integer.MAX_VALUE)
197 .setAllowPoolingConnections(true)
199 private final NetconfDeviceSimulator simulator;
200 private final int deviceCount;
201 private final Request request;
203 public ScaleVerifyCallable(final NetconfDeviceSimulator simulator, final int deviceCount) {
204 LOG.info("New callable created");
205 this.simulator = simulator;
206 this.deviceCount = deviceCount;
207 AsyncHttpClient.BoundRequestBuilder requestBuilder = asyncHttpClient.prepareGet(RESTCONF_URL)
208 .addHeader("content-type", "application/xml")
209 .addHeader("Accept", "application/xml")
210 .setRequestTimeout(Integer.MAX_VALUE);
211 request = requestBuilder.build();
215 public Object call() throws Exception {
217 final Response response = asyncHttpClient.executeRequest(request).get();
219 if (response.getStatusCode() != 200 && response.getStatusCode() != 204) {
220 LOG.warn("Request failed, status code: {}", response.getStatusCode() + response.getStatusText());
221 executor.schedule(new ScaleVerifyCallable(simulator, deviceCount), retryDelay, TimeUnit.SECONDS);
223 final String body = response.getResponseBody();
224 final Matcher matcher = PATTERN.matcher(body);
226 while (matcher.find()) {
229 RESULTS_LOG.info("Currently connected devices : {} out of {}, time elapsed: {}", count, deviceCount + 1, stopwatch);
230 if (count != deviceCount + 1) {
231 executor.schedule(new ScaleVerifyCallable(simulator, deviceCount), retryDelay, TimeUnit.SECONDS);
234 RESULTS_LOG.info("All devices connected in {}", stopwatch);
238 } catch (ConnectException | ExecutionException e) {
239 LOG.warn("Failed to connect to Restconf, is the controller running?", e);
240 executor.schedule(new ScaleVerifyCallable(simulator, deviceCount), retryDelay, TimeUnit.SECONDS);
246 private static class TimeoutGuard implements Callable {
249 public Object call() throws Exception {
250 RESULTS_LOG.warn("Timeout for scale test reached after: {} ..aborting", stopwatch);
251 root.warn("Timeout for scale test reached after: {} ..aborting", stopwatch);
257 public static class LoggingWrapperExecutor extends ScheduledThreadPoolExecutor {
259 public LoggingWrapperExecutor(int corePoolSize) {
264 public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
265 return super.schedule(wrapCallable(callable), delay, unit);
268 private Callable wrapCallable(Callable callable) {
269 return new LogOnExceptionCallable(callable);
272 private class LogOnExceptionCallable implements Callable {
273 private Callable theCallable;
275 public LogOnExceptionCallable(Callable theCallable) {
277 this.theCallable = theCallable;
281 public Object call() throws Exception {
285 } catch (Exception e) {
287 root.warn("error in executing: " + theCallable + ". It will no longer be run!", e);
289 // rethrow so that the executor can do it's thing
290 throw new RuntimeException(e);