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"})
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, TimeUnit.MINUTES);
68 final Configuration configuration = new ConfigurationBuilder().from(params).build();
69 final NetconfDeviceSimulator netconfDeviceSimulator = new NetconfDeviceSimulator(configuration);
71 final List<Integer> openDevices = netconfDeviceSimulator.start();
72 if (openDevices.size() == 0) {
73 root.error("Failed to start any simulated devices, exiting...");
77 if (params.distroFolder == null) {
78 root.error("Distro folder is not set, exiting...");
82 final Main.ConfigGenerator configGenerator = new Main.ConfigGenerator(
83 params.distroFolder, openDevices);
84 final List<File> generated = configGenerator.generate(
85 params.ssh, params.generateConfigBatchSize,
86 params.generateConfigsTimeout, params.generateConfigsAddress,
87 params.devicesPerPort);
88 configGenerator.updateFeatureFile(generated);
89 configGenerator.changeLoadOrder();
90 } catch (final Exception e) {
91 root.error("Unhandled exception", e);
92 netconfDeviceSimulator.close();
96 root.warn(params.distroFolder.getAbsolutePath());
98 runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/start");
101 final Process exec = runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/status");
104 } catch (InterruptedException e) {
105 root.warn("Failed to sleep", e);
107 status = CharStreams.toString(new BufferedReader(new InputStreamReader(exec.getInputStream())));
108 root.warn("Current status: {}", status);
109 } while (!status.startsWith("Running ..."));
110 root.warn("Doing feature install {}", params.distroFolder.getAbsolutePath()
111 + "/bin/client -u karaf feature:install odl-restconf-noauth odl-netconf-connector-all");
112 final Process featureInstall = runtime.exec(params.distroFolder.getAbsolutePath()
113 + "/bin/client -u karaf feature:install odl-restconf-noauth odl-netconf-connector-all");
115 CharStreams.toString(new BufferedReader(new InputStreamReader(featureInstall.getInputStream()))));
117 CharStreams.toString(new BufferedReader(new InputStreamReader(featureInstall.getErrorStream()))));
119 } catch (IOException e) {
120 root.warn("Failed to start karaf", e);
124 root.warn("Karaf started, starting stopwatch");
129 new ScaleVerifyCallable(netconfDeviceSimulator, params.deviceCount), RETRY_DELAY, TimeUnit.SECONDS);
130 root.warn("First callable scheduled");
132 root.warn("semaphore released");
133 } catch (InterruptedException e) {
134 throw new RuntimeException(e);
137 timeoutGuardFuture.cancel(false);
138 params.deviceCount += DEVICE_STEP;
139 netconfDeviceSimulator.close();
142 cleanup(runtime, params);
146 private static void setUpLoggers(final TesttoolParameters params) {
147 System.setProperty("log_file_name", "scale-util.log");
149 root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
150 root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
151 resultsLog = LoggerFactory.getLogger("results");
154 private static void cleanup(final Runtime runtime, final TesttoolParameters params) {
156 stopKaraf(runtime, params);
157 deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
159 } catch (IOException | InterruptedException e) {
160 root.warn("Failed to stop karaf", e);
165 private static void stopKaraf(final Runtime runtime, final TesttoolParameters params)
166 throws IOException, InterruptedException {
167 root.info("Stopping karaf and sleeping for 10 sec..");
168 String controllerPid = "";
170 final Process pgrep = runtime.exec("pgrep -f org.apache.karaf.main.Main");
172 controllerPid = CharStreams.toString(new BufferedReader(new InputStreamReader(pgrep.getInputStream())));
173 root.warn(controllerPid);
174 runtime.exec("kill -9 " + controllerPid);
176 Thread.sleep(10000L);
177 } while (!controllerPid.isEmpty());
178 deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
181 private static void deleteFolder(File folder) {
182 File[] files = folder.listFiles();
183 if (files != null) { //some JVMs return null for empty dirs
184 for (File f : files) {
185 if (f.isDirectory()) {
189 root.warn("Failed to delete {}", f);
194 if (!folder.delete()) {
195 root.warn("Failed to delete {}", folder);
199 private static class ScaleVerifyCallable implements Callable<Void> {
200 private static final Logger LOG = LoggerFactory.getLogger(ScaleVerifyCallable.class);
202 private static final String RESTCONF_URL
203 = "http://127.0.0.1:8181/restconf/operational/network-topology:network-topology/topology/topology-netconf/";
204 private static final Pattern PATTERN = Pattern.compile("connected");
206 private final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(new Builder()
207 .setConnectTimeout(Integer.MAX_VALUE)
208 .setRequestTimeout(Integer.MAX_VALUE)
209 .setAllowPoolingConnections(true)
211 private final NetconfDeviceSimulator simulator;
212 private final int deviceCount;
213 private final Request request;
215 ScaleVerifyCallable(final NetconfDeviceSimulator simulator, final int deviceCount) {
216 LOG.info("New callable created");
217 this.simulator = simulator;
218 this.deviceCount = deviceCount;
219 AsyncHttpClient.BoundRequestBuilder requestBuilder = asyncHttpClient.prepareGet(RESTCONF_URL)
220 .addHeader("content-type", "application/xml")
221 .addHeader("Accept", "application/xml")
222 .setRequestTimeout(Integer.MAX_VALUE);
223 request = requestBuilder.build();
227 public Void call() throws Exception {
229 final Response response = asyncHttpClient.executeRequest(request).get();
231 if (response.getStatusCode() != 200 && response.getStatusCode() != 204) {
232 LOG.warn("Request failed, status code: {}", response.getStatusCode() + response.getStatusText());
233 EXECUTOR.schedule(new ScaleVerifyCallable(simulator, deviceCount), RETRY_DELAY, TimeUnit.SECONDS);
235 final String body = response.getResponseBody();
236 final Matcher matcher = PATTERN.matcher(body);
238 while (matcher.find()) {
241 resultsLog.info("Currently connected devices : {} out of {}, time elapsed: {}",
242 count, deviceCount + 1, STOPWATCH);
243 if (count != deviceCount + 1) {
245 new ScaleVerifyCallable(simulator, deviceCount), RETRY_DELAY, TimeUnit.SECONDS);
248 resultsLog.info("All devices connected in {}", STOPWATCH);
252 } catch (ConnectException | ExecutionException e) {
253 LOG.warn("Failed to connect to Restconf, is the controller running?", e);
254 EXECUTOR.schedule(new ScaleVerifyCallable(simulator, deviceCount), RETRY_DELAY, TimeUnit.SECONDS);
260 private static class TimeoutGuard implements Callable<Void> {
262 public Void call() throws Exception {
263 resultsLog.warn("Timeout for scale test reached after: {} ..aborting", STOPWATCH);
264 root.warn("Timeout for scale test reached after: {} ..aborting", STOPWATCH);
270 @SuppressWarnings("checkstyle:illegalCatch")
271 public static class LoggingWrapperExecutor extends ScheduledThreadPoolExecutor {
272 public LoggingWrapperExecutor(int corePoolSize) {
277 public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
278 return super.schedule(new LogOnExceptionCallable<>(callable), delay, unit);
281 private static class LogOnExceptionCallable<T> implements Callable<T> {
282 private final Callable<T> theCallable;
284 LogOnExceptionCallable(Callable<T> theCallable) {
285 this.theCallable = theCallable;
289 public T call() throws Exception {
291 return theCallable.call();
292 } catch (Exception e) {
294 root.warn("error in executing: " + theCallable + ". It will no longer be run!", e);
296 // rethrow so that the executor can do it's thing
297 throw new RuntimeException(e);