-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathScript.java
More file actions
executable file
·491 lines (422 loc) · 16.9 KB
/
Script.java
File metadata and controls
executable file
·491 lines (422 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.script;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.script.OutputInterpreter.TimedOutLogger;
public class Script implements Callable<String> {
private static final Logger s_logger = Logger.getLogger(Script.class);
private final Logger _logger;
public static final String ERR_EXECUTE = "execute.error";
public static final String ERR_TIMEOUT = "timeout";
private int _defaultTimeout = 3600 * 1000; /* 1 hour */
private volatile boolean _isTimeOut = false;
private boolean _passwordCommand = false;
private static final ScheduledExecutorService s_executors = Executors.newScheduledThreadPool(10, new NamedThreadFactory("Script"));
String _workDir;
ArrayList<String> _command;
long _timeout;
Process _process;
Thread _thread;
ScriptBuilder _builder;
public Script(String command, long timeout, Logger logger) {
_command = new ArrayList<String>();
_command.add(command);
_timeout = timeout;
if (_timeout == 0) {
/* always using default timeout 1 hour to avoid thread hang */
_timeout = _defaultTimeout;
}
_process = null;
_logger = logger != null ? logger : s_logger;
}
protected Script(ScriptBuilder builder) {
this(builder._command, builder._timeout, builder._logger);
}
public Script(boolean runWithSudo, String command, long timeout, Logger logger) {
this(command, timeout, logger);
if (runWithSudo) {
_command.add(0, "sudo");
}
}
public Script(String command, Logger logger) {
this(command, 0, logger);
}
public Script(String command) {
this(command, 0, s_logger);
}
public Script(String command, long timeout) {
this(command, timeout, s_logger);
}
public void add(String... params) {
for (String param : params) {
_command.add(param);
}
}
public void add(String param) {
_command.add(param);
}
public Script set(String name, String value) {
_command.add(name);
_command.add(value);
return this;
}
public void setWorkDir(String workDir) {
_workDir = workDir;
}
protected String buildCommandLine(String[] command) {
StringBuilder builder = new StringBuilder();
boolean obscureParam = false;
for (int i = 0; i < command.length; i++) {
String cmd = command[i];
if (obscureParam) {
builder.append("******").append(" ");
obscureParam = false;
} else {
builder.append(command[i]).append(" ");
}
if ("-y".equals(cmd) || "-z".equals(cmd)) {
obscureParam = true;
_passwordCommand = true;
}
}
return builder.toString();
}
protected String buildCommandLine(List<String> command) {
StringBuilder builder = new StringBuilder();
boolean obscureParam = false;
for (String cmd : command) {
if (obscureParam) {
builder.append("******").append(" ");
obscureParam = false;
} else {
builder.append(cmd).append(" ");
}
if ("-y".equals(cmd) || "-z".equals(cmd)) {
obscureParam = true;
_passwordCommand = true;
}
}
return builder.toString();
}
public String execute() {
return execute(new OutputInterpreter.OutputLogger(_logger));
}
@Override
public String toString() {
String[] command = _command.toArray(new String[_command.size()]);
return buildCommandLine(command);
}
public String execute(OutputInterpreter interpreter) {
String[] command = _command.toArray(new String[_command.size()]);
if (_logger.isDebugEnabled()) {
_logger.debug("Executing: " + buildCommandLine(command));
}
try {
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
if(_workDir != null)
pb.directory(new File(_workDir));
_process = pb.start();
if (_process == null) {
_logger.warn("Unable to execute: " + buildCommandLine(command));
return "Unable to execute the command: " + command[0];
}
BufferedReader ir = new BufferedReader(new InputStreamReader(_process.getInputStream()));
_thread = Thread.currentThread();
ScheduledFuture<String> future = null;
if (_timeout > 0) {
future = s_executors.schedule(this, _timeout, TimeUnit.MILLISECONDS);
}
Task task = null;
if (interpreter != null && interpreter.drain()) {
task = new Task(interpreter, ir);
s_executors.execute(task);
}
while (true) {
try {
if (_process.waitFor() == 0) {
_logger.debug("Execution is successful.");
if (interpreter != null) {
return interpreter.drain() ? task.getResult() : interpreter.interpret(ir);
} else {
// null return is ok apparently
return (_process.exitValue() == 0) ? "Ok" : "Failed, exit code " + _process.exitValue();
}
} else {
break;
}
} catch (InterruptedException e) {
if (!_isTimeOut) {
/*
* This is not timeout, we are interrupted by others,
* continue
*/
_logger.debug("We are interrupted but it's not a timeout, just continue");
continue;
}
TimedOutLogger log = new TimedOutLogger(_process);
Task timedoutTask = new Task(log, ir);
timedoutTask.run();
if (!_passwordCommand) {
_logger.warn("Timed out: " + buildCommandLine(command) + ". Output is: " + timedoutTask.getResult());
} else {
_logger.warn("Timed out: " + buildCommandLine(command));
}
return ERR_TIMEOUT;
} finally {
if (future != null) {
future.cancel(false);
}
Thread.interrupted();
}
}
_logger.debug("Exit value is " + _process.exitValue());
BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128);
String error;
if (interpreter != null) {
error = interpreter.processError(reader);
}
else {
error = "Non zero exit code : " + _process.exitValue();
}
if (_logger.isDebugEnabled()) {
_logger.debug(error);
}
return error;
} catch (SecurityException ex) {
_logger.warn("Security Exception....not running as root?", ex);
StringWriter writer = new StringWriter();
ex.printStackTrace(new PrintWriter(writer));
return writer.toString();
} catch (Exception ex) {
_logger.warn("Exception: " + buildCommandLine(command), ex);
StringWriter writer = new StringWriter();
ex.printStackTrace(new PrintWriter(writer));
return writer.toString();
} finally {
if (_process != null) {
try {
_process.getErrorStream().close();
} catch (IOException ex) {
}
try {
_process.getOutputStream().close();
} catch (IOException ex) {
}
try {
_process.getInputStream().close();
} catch (IOException ex) {
}
_process.destroy();
}
}
}
@Override
public String call() {
try {
_logger.trace("Checking exit value of process");
_process.exitValue();
_logger.trace("Script ran within the alloted time");
} catch (IllegalThreadStateException e) {
_logger.warn("Interrupting script.");
_isTimeOut = true;
_thread.interrupt();
}
return null;
}
public static class Task implements Runnable {
OutputInterpreter interpreter;
BufferedReader reader;
String result;
boolean done;
public Task(OutputInterpreter interpreter, BufferedReader reader) {
this.interpreter = interpreter;
this.reader = reader;
this.result = null;
}
public void run() {
done = false;
try {
result = interpreter.interpret(reader);
} catch (IOException ex) {
StringWriter writer = new StringWriter();
ex.printStackTrace(new PrintWriter(writer));
result = writer.toString();
} catch (Exception ex) {
StringWriter writer = new StringWriter();
ex.printStackTrace(new PrintWriter(writer));
result = writer.toString();
} finally {
synchronized (this) {
done = true;
notifyAll();
}
try {
reader.close();
} catch (IOException ex) {
}
;
}
}
public synchronized String getResult() throws InterruptedException {
if (!done) {
wait();
}
return result;
}
}
public static String findScript(String path, String script) {
s_logger.debug("Looking for " + script + " in the classpath");
path = path.replace("/", File.separator);
URL url = ClassLoader.getSystemResource(script);
s_logger.debug("System resource: " + url);
File file = null;
if (url != null) {
file = new File(url.getFile());
s_logger.debug("Absolute path = " + file.getAbsolutePath());
return file.getAbsolutePath();
}
/**
* Look in WEB-INF/classes of the webapp
* URI workaround the URL encoding of url.getFile
*/
if (path.endsWith(File.separator)) {
url = Script.class.getClassLoader().getResource(path + script);
}
else {
url = Script.class.getClassLoader().getResource(path + File.separator + script);
}
s_logger.debug("Classpath resource: " + url);
if (url != null) {
try {
file = new File(new URI(url.toString()).getPath());
s_logger.debug("Absolute path = " + file.getAbsolutePath());
return file.getAbsolutePath();
}
catch (URISyntaxException e) {
s_logger.warn("Unable to convert " + url.toString() + " to a URI");
}
}
if (path.endsWith(File.separator)) {
path = path.substring(0, path.lastIndexOf(File.separator));
}
if (path.startsWith(File.separator)) {
// Path given was absolute so we assume the caller knows what they want.
file = new File(path + File.separator + script);
return file.exists() ? file.getAbsolutePath() : null;
}
s_logger.debug("Looking for " + script);
String search = null;
for (int i = 0; i < 3; i++) {
if (i == 0) {
String cp = Script.class.getResource(Script.class.getSimpleName() + ".class").toExternalForm();
int begin = cp.indexOf(File.separator);
// work around with the inconsistency of java classpath and file separator on Windows 7
if (begin < 0)
begin = cp.indexOf('/');
int endBang = cp.lastIndexOf("!");
int end = cp.lastIndexOf(File.separator, endBang);
if (end < 0)
end = cp.lastIndexOf('/', endBang);
if(end < 0)
cp = cp.substring(begin);
else
cp = cp.substring(begin, end);
s_logger.debug("Current binaries reside at " + cp);
search = cp;
} else if (i == 1) {
s_logger.debug("Searching in environment.properties");
try {
final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
if (propsFile == null) {
s_logger.debug("environment.properties could not be opened");
} else {
final FileInputStream finputstream = new FileInputStream(propsFile);
final Properties props = new Properties();
props.load(finputstream);
finputstream.close();
search = props.getProperty("paths.script");
}
} catch (IOException e) {
s_logger.debug("environment.properties could not be opened");
continue;
}
s_logger.debug("environment.properties says scripts should be in " + search);
} else {
s_logger.debug("Searching in the current directory");
search = ".";
}
search += File.separatorChar + path + File.separator;
do {
search = search.substring(0, search.lastIndexOf(File.separator));
file = new File(search + File.separator + script);
s_logger.debug("Looking for " + script + " in " + file.getAbsolutePath());
} while (!file.exists() && search.lastIndexOf(File.separator) != -1);
if (file.exists()) {
return file.getAbsolutePath();
}
}
search = System.getProperty("paths.script");
search += File.separatorChar + path + File.separator;
do {
search = search.substring(0, search.lastIndexOf(File.separator));
file = new File(search + File.separator + script);
s_logger.debug("Looking for " + script + " in " + file.getAbsolutePath());
} while (!file.exists() && search.lastIndexOf(File.separator) != -1);
if (file.exists()) {
return file.getAbsolutePath();
}
s_logger.warn("Unable to find script " + script);
return null;
}
public static String runSimpleBashScript(String command) {
return Script.runSimpleBashScript(command, 0);
}
public static String runSimpleBashScript(String command, int timeout) {
Script s = new Script("/bin/bash", timeout);
s.add("-c");
s.add(command);
OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
if (s.execute(parser) != null)
return null;
String result = parser.getLine();
if (result == null || result.trim().isEmpty())
return null;
else
return result.trim();
}
}