adce359f088e7a3d706fe2ba8589ecfe45978940
[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 java.io.BufferedReader;
19 import java.io.File;
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;
37
38 public class ScaleUtil {
39
40     private static final Logger RESULTS_LOG = LoggerFactory.getLogger("results");
41     private static final ScheduledExecutorService executor = new LoggingWrapperExecutor(4);
42
43     private static final int deviceStep = 1000;
44     private static final long retryDelay = 10l;
45     private static final long timeout = 20l;
46
47     private static final Stopwatch stopwatch = Stopwatch.createUnstarted();
48
49     private static ScheduledFuture timeoutGuardFuture;
50     private static ch.qos.logback.classic.Logger root;
51     private static final Semaphore semaphore = new Semaphore(0);
52
53     public static void main(final String[] args) {
54         final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser());
55
56         root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
57         root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
58
59         // cleanup at the start in case controller was already running
60         final Runtime runtime = Runtime.getRuntime();
61         cleanup(runtime, params);
62
63         while (true) {
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();
67             try {
68                 final List<Integer> openDevices = netconfDeviceSimulator.start(params);
69                 if (openDevices.size() == 0) {
70                     root.error("Failed to start any simulated devices, exiting...");
71                     System.exit(1);
72                 }
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();
81                 }
82             } catch (final Exception e) {
83                 root.error("Unhandled exception", e);
84                 netconfDeviceSimulator.close();
85                 System.exit(1);
86             }
87
88             root.warn(params.distroFolder.getAbsolutePath());
89             try {
90                 runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/start");
91                 String status;
92                 do {
93                     final Process exec = runtime.exec(params.distroFolder.getAbsolutePath() + "/bin/status");
94                     try {
95                         Thread.sleep(2000l);
96                     } catch (InterruptedException e) {
97                         root.warn("Failed to sleep", e);
98                     }
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()))));
106
107             } catch (IOException e) {
108                 root.warn("Failed to start karaf", e);
109                 System.exit(1);
110             }
111
112             root.warn("Karaf started, starting stopwatch");
113             stopwatch.start();
114
115             try {
116                 executor.schedule(new ScaleVerifyCallable(netconfDeviceSimulator, params.deviceCount), retryDelay, TimeUnit.SECONDS);
117                 root.warn("First callable scheduled");
118                 semaphore.acquire();
119                 root.warn("semaphore released");
120             } catch (InterruptedException e) {
121                 throw new RuntimeException(e);
122             }
123
124             timeoutGuardFuture.cancel(false);
125             params.deviceCount += deviceStep;
126             netconfDeviceSimulator.close();
127             stopwatch.reset();
128
129             cleanup(runtime, params);
130         }
131     }
132
133     private static void cleanup(final Runtime runtime, final TesttoolParameters params) {
134         try {
135             stopKaraf(runtime, params);
136             deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
137
138         } catch (IOException | InterruptedException e) {
139             root.warn("Failed to stop karaf", e);
140             System.exit(1);
141         }
142     }
143
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 = "";
147         do {
148
149             final Process pgrep = runtime.exec("pgrep -f org.apache.karaf.main.Main");
150
151             controllerPid = CharStreams.toString(new BufferedReader(new InputStreamReader(pgrep.getInputStream())));
152             root.warn(controllerPid);
153             runtime.exec("kill -9 " + controllerPid);
154
155             Thread.sleep(10000l);
156         } while (!controllerPid.isEmpty());
157         deleteFolder(new File(params.distroFolder.getAbsoluteFile() + "/data"));
158     }
159
160     private static void deleteFolder(File folder) {
161         File[] files = folder.listFiles();
162         if(files!=null) { //some JVMs return null for empty dirs
163             for(File f: files) {
164                 if(f.isDirectory()) {
165                     deleteFolder(f);
166                 } else {
167                     f.delete();
168                 }
169             }
170         }
171         folder.delete();
172     }
173
174     private static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) {
175         final TesttoolParameters parameters = new TesttoolParameters();
176         try {
177             parser.parseArgs(args, parameters);
178             return parameters;
179         } catch (ArgumentParserException e) {
180             parser.handleError(e);
181         }
182
183         System.exit(1);
184         return null;
185     }
186
187     private static class ScaleVerifyCallable implements Callable {
188
189         private static final Logger LOG = LoggerFactory.getLogger(ScaleVerifyCallable.class);
190
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");
193
194         private final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(new Builder()
195                 .setConnectTimeout(Integer.MAX_VALUE)
196                 .setRequestTimeout(Integer.MAX_VALUE)
197                 .setAllowPoolingConnections(true)
198                 .build());
199         private final NetconfDeviceSimulator simulator;
200         private final int deviceCount;
201         private final Request request;
202
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();
212         }
213
214         @Override
215         public Object call() throws Exception {
216             try {
217                 final Response response = asyncHttpClient.executeRequest(request).get();
218
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);
222                 } else {
223                     final String body = response.getResponseBody();
224                     final Matcher matcher = PATTERN.matcher(body);
225                     int count = 0;
226                     while (matcher.find()) {
227                         count++;
228                     }
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);
232                     } else {
233                         stopwatch.stop();
234                         RESULTS_LOG.info("All devices connected in {}", stopwatch);
235                         semaphore.release();
236                     }
237                 }
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);
241             }
242             return null;
243         }
244     }
245
246     private static class TimeoutGuard implements Callable {
247
248         @Override
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);
252             System.exit(0);
253             return null;
254         }
255     }
256
257     public static class LoggingWrapperExecutor extends ScheduledThreadPoolExecutor {
258
259         public LoggingWrapperExecutor(int corePoolSize) {
260             super(corePoolSize);
261         }
262
263         @Override
264         public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
265             return super.schedule(wrapCallable(callable), delay, unit);
266         }
267
268         private Callable wrapCallable(Callable callable) {
269             return new LogOnExceptionCallable(callable);
270         }
271
272         private class LogOnExceptionCallable implements Callable {
273             private Callable theCallable;
274
275             public LogOnExceptionCallable(Callable theCallable) {
276                 super();
277                 this.theCallable = theCallable;
278             }
279
280             @Override
281             public Object call() throws Exception {
282                 try {
283                     theCallable.call();
284                     return null;
285                 } catch (Exception e) {
286                     // log
287                     root.warn("error in executing: " + theCallable + ". It will no longer be run!", e);
288
289                     // rethrow so that the executor can do it's thing
290                     throw new RuntimeException(e);
291                 }
292             }
293         }
294     }
295 }