Skip to content

Commit

Permalink
Merge pull request #1116 from OSGP/feature/improved_ping_handling
Browse files Browse the repository at this point in the history
  • Loading branch information
kroesctrl authored Nov 16, 2023
2 parents 9e2a4bf + 803b211 commit f1d6a19
Showing 1 changed file with 35 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,34 +25,58 @@ public class CommandExecutor {

private static final Logger LOGGER = LoggerFactory.getLogger(CommandExecutor.class);

private static final long AWAIT_TERMINATION_IN_SEC = 5;

public List<String> execute(final List<String> commands, final Duration timeout)
throws IOException, TimeoutException, ExecutionException {

final String commandLine = this.commandLine(commands);
final Process process = this.start(commands);

final ExecutorService executorService = Executors.newSingleThreadExecutor();
final Future<List<String>> inputLines =
executorService.submit(() -> this.readLinesFromInput(process));
try {
final Future<List<String>> inputLines =
executorService.submit(() -> this.readLinesFromInput(process));
return inputLines.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (final TimeoutException e) {
inputLines.cancel(true);
throw e;
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
LOGGER.warn(
"Reading input lines from executed process was interrupted: \"{}\"", commandLine, e);
} finally {
executorService.shutdownNow();
if (process.isAlive()) {
LOGGER.debug("Destroy the process running \"{}\"", commandLine);
process.destroyForcibly();
} else {
LOGGER.debug(
"Process running \"{}\" ended with exit value: {}", commands, process.exitValue());
}
this.shutdownAndAwaitTermination(executorService);
this.destroyProcess(process, commands);
}
return Collections.emptyList();
}

private void destroyProcess(final Process process, final List<String> commands) {
process.destroy();
if (process.isAlive()) {
LOGGER.debug("Destroy the process running \"{}\"", commands);
process.destroyForcibly();
} else {
LOGGER.debug(
"Process running \"{}\" ended with exit value: {}", commands, process.exitValue());
}
}

void shutdownAndAwaitTermination(final ExecutorService executorService) {
executorService.shutdown();
try {
if (!executorService.awaitTermination(AWAIT_TERMINATION_IN_SEC, TimeUnit.SECONDS)) {
executorService.shutdownNow();
if (!executorService.awaitTermination(AWAIT_TERMINATION_IN_SEC, TimeUnit.SECONDS)) {
LOGGER.error("Pool did not terminate");
}
}
} catch (final InterruptedException ex) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}

private String commandLine(final List<String> commands) {
return String.join(" ", commands);
}
Expand Down

0 comments on commit f1d6a19

Please sign in to comment.