Remove unused exceptions
[netconf.git] / netconf / tools / netconf-testtool / src / main / java / org / opendaylight / netconf / test / tool / ScaleUtil.java
1 /*
2  * Copyright (c) 2016 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 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;
20 import java.io.File;
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;
38
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();
44
45     private static final long TIMEOUT = 20L;
46     private static final long RETRY_DELAY = 10L;
47     private static final int DEVICE_STEP = 1000;
48
49     private static ch.qos.logback.classic.Logger root;
50     private static Logger resultsLog;
51
52     private ScaleUtil() {
53     }
54
55     @SuppressWarnings("checkstyle:illegalCatch")
56     public static void main(final String[] args) {
57         final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser());
58
59         setUpLoggers(params);
60
61         // cleanup at the start in case controller was already running
62         final Runtime runtime = Runtime.getRuntime();
63         cleanup(runtime, params);
64
65         while (true) {
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);
70             try {
71                 final List<Integer> openDevices = netconfDeviceSimulator.start();
72                 if (openDevices.size() == 0) {
73                     root.error("Failed to start any simulated devices, exiting...");
74                     System.exit(1);
75                 }
76
77                 if (params.distroFolder == null) {
78                     root.error("Distro folder is not set, exiting...");
79                     System.exit(1);
80                 }
81
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();
93                 System.exit(1);
94             }
95
96             root.warn(params.distroFolder.getAbsolutePath());
97             try {
98                 runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/start");
99                 String status;
100                 do {
101                     final Process exec = runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/status");
102                     try {
103                         Thread.sleep(2000L);
104                     } catch (InterruptedException e) {
105                         root.warn("Failed to sleep", e);
106                     }
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");
114                 root.warn(
115                     CharStreams.toString(new BufferedReader(new InputStreamReader(featureInstall.getInputStream()))));
116                 root.warn(
117                     CharStreams.toString(new BufferedReader(new InputStreamReader(featureInstall.getErrorStream()))));
118
119             } catch (IOException e) {
120                 root.warn("Failed to start karaf", e);
121                 System.exit(1);
122             }
123
124             root.warn("Karaf started, starting stopwatch");
125             STOPWATCH.start();
126
127             try {
128                 EXECUTOR.schedule(
129                     new ScaleVerifyCallable(netconfDeviceSimulator, params.deviceCount), RETRY_DELAY, TimeUnit.SECONDS);
130                 root.warn("First callable scheduled");
131                 SEMAPHORE.acquire();
132                 root.warn("semaphore released");
133             } catch (InterruptedException e) {
134                 throw new RuntimeException(e);
135             }
136
137             timeoutGuardFuture.cancel(false);
138             params.deviceCount += DEVICE_STEP;
139             netconfDeviceSimulator.close();
140             STOPWATCH.reset();
141
142             cleanup(runtime, params);
143         }
144     }
145
146     private static void setUpLoggers(final TesttoolParameters params) {
147         System.setProperty("log_file_name", "scale-util.log");
148
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");
152     }
153
154     private static void cleanup(final Runtime runtime, final TesttoolParameters params) {
155         try {
156             stopKaraf(runtime, params);
157             deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
158
159         } catch (IOException | InterruptedException e) {
160             root.warn("Failed to stop karaf", e);
161             System.exit(1);
162         }
163     }
164
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 = "";
169         do {
170             final Process pgrep = runtime.exec("pgrep -f org.apache.karaf.main.Main");
171
172             controllerPid = CharStreams.toString(new BufferedReader(new InputStreamReader(pgrep.getInputStream())));
173             root.warn(controllerPid);
174             runtime.exec("kill -9 " + controllerPid);
175
176             Thread.sleep(10000L);
177         } while (!controllerPid.isEmpty());
178         deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
179     }
180
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()) {
186                     deleteFolder(f);
187                 } else {
188                     if (!f.delete()) {
189                         root.warn("Failed to delete {}", f);
190                     }
191                 }
192             }
193         }
194         if (!folder.delete()) {
195             root.warn("Failed to delete {}", folder);
196         }
197     }
198
199     private static class ScaleVerifyCallable implements Callable<Void> {
200         private static final Logger LOG = LoggerFactory.getLogger(ScaleVerifyCallable.class);
201
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");
205
206         private final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(new Builder()
207                 .setConnectTimeout(Integer.MAX_VALUE)
208                 .setRequestTimeout(Integer.MAX_VALUE)
209                 .setAllowPoolingConnections(true)
210                 .build());
211         private final NetconfDeviceSimulator simulator;
212         private final int deviceCount;
213         private final Request request;
214
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();
224         }
225
226         @Override
227         public Void call() throws Exception {
228             try {
229                 final Response response = asyncHttpClient.executeRequest(request).get();
230
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);
234                 } else {
235                     final String body = response.getResponseBody();
236                     final Matcher matcher = PATTERN.matcher(body);
237                     int count = 0;
238                     while (matcher.find()) {
239                         count++;
240                     }
241                     resultsLog.info("Currently connected devices : {} out of {}, time elapsed: {}",
242                         count, deviceCount + 1, STOPWATCH);
243                     if (count != deviceCount + 1) {
244                         EXECUTOR.schedule(
245                             new ScaleVerifyCallable(simulator, deviceCount), RETRY_DELAY, TimeUnit.SECONDS);
246                     } else {
247                         STOPWATCH.stop();
248                         resultsLog.info("All devices connected in {}", STOPWATCH);
249                         SEMAPHORE.release();
250                     }
251                 }
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);
255             }
256             return null;
257         }
258     }
259
260     private static class TimeoutGuard implements Callable<Void> {
261         @Override
262         public Void call() {
263             resultsLog.warn("Timeout for scale test reached after: {} ..aborting", STOPWATCH);
264             root.warn("Timeout for scale test reached after: {} ..aborting", STOPWATCH);
265             System.exit(0);
266             return null;
267         }
268     }
269
270     @SuppressWarnings("checkstyle:illegalCatch")
271     public static class LoggingWrapperExecutor extends ScheduledThreadPoolExecutor {
272         public LoggingWrapperExecutor(int corePoolSize) {
273             super(corePoolSize);
274         }
275
276         @Override
277         public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
278             return super.schedule(new LogOnExceptionCallable<>(callable), delay, unit);
279         }
280
281         private static class LogOnExceptionCallable<T> implements Callable<T> {
282             private final Callable<T> theCallable;
283
284             LogOnExceptionCallable(Callable<T> theCallable) {
285                 this.theCallable = theCallable;
286             }
287
288             @Override
289             public T call() {
290                 try {
291                     return theCallable.call();
292                 } catch (Exception e) {
293                     // log
294                     root.warn("error in executing: " + theCallable + ". It will no longer be run!", e);
295
296                     // rethrow so that the executor can do it's thing
297                     throw new RuntimeException(e);
298                 }
299             }
300         }
301     }
302 }