Skip to content

Commit 761fb4e

Browse files
committed
perf[command]: add timeout param to execCommand method
1 parent 1030dd3 commit 761fb4e

1 file changed

Lines changed: 12 additions & 6 deletions

File tree

monitor/src/main/java/com/zfoo/monitor/util/OSUtils.java

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -260,36 +260,42 @@ public static SystemInfo os() {
260260

261261
// -----------------------------------------------------------------------------------------------------------------
262262
private static final ExecutorService executors = Executors.newCachedThreadPool(new MonitorThreadFactory());
263+
263264
public static class MonitorThreadFactory implements ThreadFactory {
264265
private final AtomicInteger threadNumber = new AtomicInteger(1);
266+
265267
@Override
266268
public Thread newThread(Runnable runnable) {
267269
var threadName = StringUtils.format("monitor-t-{}", threadNumber.getAndIncrement());
268-
return new Thread( runnable, threadName);
270+
return new Thread(runnable, threadName);
269271
}
270272
}
273+
271274
public static String execCommand(String command) {
272275
logger.info("execCommand [{}]", command);
273276
try {
274-
return doExecCommand(command, null);
277+
return doExecCommand(command, null, 5 * TimeUtils.MILLIS_PER_MINUTE);
275278
} catch (IOException | InterruptedException e) {
276279
throw new RuntimeException(e);
277280
}
278281
}
279282

280-
281283
public static String execCommand(String command, String workingDirectory) {
284+
return execCommand(command, workingDirectory, 5 * TimeUtils.MILLIS_PER_MINUTE);
285+
}
286+
287+
public static String execCommand(String command, String workingDirectory, long timeoutMillis) {
282288
logger.info("execCommand [{}] workingDirectory:[{}]", command, workingDirectory);
283289
FileUtils.createDirectory(workingDirectory);
284290
var wd = new File(workingDirectory);
285291
try {
286-
return doExecCommand(command, wd);
292+
return doExecCommand(command, wd, timeoutMillis);
287293
} catch (IOException | InterruptedException e) {
288294
throw new RuntimeException(e);
289295
}
290296
}
291297

292-
private static String doExecCommand(String command, File wd) throws IOException, InterruptedException {
298+
private static String doExecCommand(String command, File wd, long timeoutMillis) throws IOException, InterruptedException {
293299
var commandSplits = command.split(StringUtils.SPACE_REGEX);
294300
var process = new ProcessBuilder(commandSplits)
295301
.redirectErrorStream(true)
@@ -316,7 +322,7 @@ private static String doExecCommand(String command, File wd) throws IOException,
316322

317323
}));
318324

319-
var finished = process.waitFor(256, TimeUnit.SECONDS);
325+
var finished = process.waitFor(timeoutMillis, TimeUnit.MILLISECONDS);
320326
if (!finished) {
321327
process.destroyForcibly();
322328
logger.error("doExecCommand timeout with process of command:[{}]", command);

0 commit comments

Comments
 (0)