feat(execution): implement process execution engine (#5)

Add process execution infrastructure:

- ProcessUtils for cross-platform process management (isAlive, killTree)
- ProcessExecutor for command execution with output capture to log files
- ProcessMonitor for asynchronous process monitoring with events
- JobRunner for orchestrating job execution with state management

Features:
- Cross-platform support (Windows, macOS, Linux)
- Real-time stdout/stderr capture to log files
- Heartbeat monitoring during execution
- Graceful and forceful process termination

Includes 54 new tests for comprehensive coverage.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Opus 4.5 committed 2026-01-21 13:19:54 +00:00
1 parent c6e26bbedb
commit 818c45de0a
8 files changed
+1531

No files matched your search

@@ -0,0 +1,202 @@
package com.samsonmedia.barn.execution;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.samsonmedia.barn.jobs.Job;
import com.samsonmedia.barn.jobs.JobRepository;
import com.samsonmedia.barn.state.BarnDirectories;
/**
* Runs jobs by executing their commands and managing their lifecycle.
*
* <p>The JobRunner handles:
* <ul>
* <li>Starting the process</li>
* <li>Updating state to RUNNING</li>
* <li>Writing PID and heartbeat</li>
* <li>Monitoring the process</li>
* <li>Capturing exit code and errors</li>
* <li>Updating final state (SUCCEEDED/FAILED)</li>
* </ul>
*/
public class JobRunner {
private static final Logger LOG = LoggerFactory.getLogger(JobRunner.class);
private static final String STDOUT_LOG = "stdout.log";
private static final String STDERR_LOG = "stderr.log";
private final ProcessExecutor executor;
private final ProcessMonitor monitor;
private final JobRepository repository;
private final BarnDirectories dirs;
/**
* Creates a JobRunner.
*
* @param executor the process executor
* @param monitor the process monitor
* @param repository the job repository
* @param dirs the directory manager
*/
public JobRunner(
ProcessExecutor executor,
ProcessMonitor monitor,
JobRepository repository,
BarnDirectories dirs) {
this.executor = Objects.requireNonNull(executor, "executor must not be null");
this.monitor = Objects.requireNonNull(monitor, "monitor must not be null");
this.repository = Objects.requireNonNull(repository, "repository must not be null");
this.dirs = Objects.requireNonNull(dirs, "dirs must not be null");
}
/**
* Creates a JobRunner with default executor and monitor.
*
* @param repository the job repository
* @param dirs the directory manager
*/
public JobRunner(JobRepository repository, BarnDirectories dirs) {
this(new ProcessExecutor(), new ProcessMonitor(), repository, dirs);
}
/**
* Runs a job synchronously.
*
* <p>This method blocks until the job completes.
*
* @param job the job to run
* @return the result of running the job
*/
public JobResult run(Job job) {
Objects.requireNonNull(job, "job must not be null");
LOG.info("Starting job: {}", job.id());
Instant startTime = Instant.now();
AtomicBoolean completed = new AtomicBoolean(false);
try {
// Get paths
var logsDir = dirs.getJobLogsDir(job.id());
var workDir = dirs.getJobWorkDir(job.id());
var stdoutFile = logsDir.resolve(STDOUT_LOG);
var stderrFile = logsDir.resolve(STDERR_LOG);
// Start process
Process process = executor.execute(
job.command(),
workDir,
stdoutFile,
stderrFile
);
long pid = process.pid();
// Update state to RUNNING
repository.markStarted(job.id(), pid);
// Monitor the process with heartbeat updates
ProcessMonitor.ProcessEvent.Completed completedEvent = monitor.monitorBlocking(
process,
event -> handleEvent(job.id(), event)
);
completed.set(true);
// Update final state
int exitCode = completedEvent.exitCode();
String error = exitCode == 0 ? null : "Process exited with code " + exitCode;
repository.markCompleted(job.id(), exitCode, error);
Duration duration = Duration.between(startTime, Instant.now());
LOG.info("Job {} completed with exit code {} in {}", job.id(), exitCode, formatDuration(duration));
return new JobResult(exitCode, duration, error);
} catch (IOException e) {
LOG.error("Failed to start job {}: {}", job.id(), e.getMessage(), e);
if (!completed.get()) {
try {
repository.markFailed(job.id(), "start_failed", e.getMessage());
} catch (IOException updateError) {
LOG.error("Failed to mark job {} as failed: {}", job.id(), updateError.getMessage());
}
}
Duration duration = Duration.between(startTime, Instant.now());
return new JobResult(-1, duration, e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.warn("Job {} was interrupted", job.id());
if (!completed.get()) {
try {
repository.markFailed(job.id(), "interrupted", "Job was interrupted");
} catch (IOException updateError) {
LOG.error("Failed to mark job {} as failed: {}", job.id(), updateError.getMessage());
}
}
Duration duration = Duration.between(startTime, Instant.now());
return new JobResult(-1, duration, "Job was interrupted");
}
}
private void handleEvent(String jobId, ProcessMonitor.ProcessEvent event) {
try {
switch (event) {
case ProcessMonitor.ProcessEvent.Started started -> {
LOG.debug("Job {} started with PID {}", jobId, started.pid());
}
case ProcessMonitor.ProcessEvent.Heartbeat heartbeat -> {
LOG.trace("Job {} heartbeat at {}", jobId, heartbeat.timestamp());
repository.updateHeartbeat(jobId, heartbeat.timestamp());
}
case ProcessMonitor.ProcessEvent.Completed completed -> {
LOG.debug("Job {} completed with exit code {}", jobId, completed.exitCode());
}
case ProcessMonitor.ProcessEvent.Failed failed -> {
LOG.error("Job {} failed: {}", jobId, failed.error().getMessage());
}
}
} catch (IOException e) {
LOG.error("Failed to handle event for job {}: {}", jobId, e.getMessage(), e);
}
}
private String formatDuration(Duration duration) {
long seconds = duration.getSeconds();
if (seconds < 60) {
return seconds + "s";
} else if (seconds < 3600) {
return String.format("%dm %ds", seconds / 60, seconds % 60);
} else {
return String.format("%dh %dm %ds", seconds / 3600, (seconds % 3600) / 60, seconds % 60);
}
}
/**
* Result of running a job.
*
* @param exitCode the process exit code (-1 if process failed to start)
* @param duration the total runtime
* @param error the error message, if any
*/
public record JobResult(int exitCode, Duration duration, String error) {
/**
* Returns true if the job completed successfully.
*/
public boolean isSuccess() {
return exitCode == 0;
}
}
}
@@ -0,0 +1,150 @@
package com.samsonmedia.barn.execution;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Executes processes and captures their output.
*
* <p>This class provides cross-platform process execution with proper output
* capture to log files.
*/
public class ProcessExecutor {
private static final Logger LOG = LoggerFactory.getLogger(ProcessExecutor.class);
/**
* Executes a command and returns the process.
*
* <p>The process output is redirected to the specified log files.
* Output is appended if the files already exist.
*
* @param command the command and arguments to execute
* @param workingDir the working directory for the process
* @param stdoutFile the file to write stdout to
* @param stderrFile the file to write stderr to
* @param environment additional environment variables (may be null)
* @return the started Process
* @throws IOException if the process cannot be started
*/
public Process execute(
List<String> command,
Path workingDir,
Path stdoutFile,
Path stderrFile,
Map<String, String> environment) throws IOException {
Objects.requireNonNull(command, "command must not be null");
Objects.requireNonNull(workingDir, "workingDir must not be null");
Objects.requireNonNull(stdoutFile, "stdoutFile must not be null");
Objects.requireNonNull(stderrFile, "stderrFile must not be null");
if (command.isEmpty()) {
throw new IllegalArgumentException("command must not be empty");
}
// Ensure parent directories exist
Files.createDirectories(stdoutFile.getParent());
Files.createDirectories(stderrFile.getParent());
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(workingDir.toFile());
builder.redirectOutput(ProcessBuilder.Redirect.appendTo(stdoutFile.toFile()));
builder.redirectError(ProcessBuilder.Redirect.appendTo(stderrFile.toFile()));
if (environment != null && !environment.isEmpty()) {
builder.environment().putAll(environment);
}
LOG.info("Starting process: {}", String.join(" ", command));
LOG.debug("Working directory: {}", workingDir);
LOG.debug("Stdout file: {}", stdoutFile);
LOG.debug("Stderr file: {}", stderrFile);
Process process = builder.start();
LOG.info("Process started with PID: {}", process.pid());
return process;
}
/**
* Executes a command with default settings.
*
* @param command the command and arguments to execute
* @param workingDir the working directory for the process
* @param stdoutFile the file to write stdout to
* @param stderrFile the file to write stderr to
* @return the started Process
* @throws IOException if the process cannot be started
*/
public Process execute(
List<String> command,
Path workingDir,
Path stdoutFile,
Path stderrFile) throws IOException {
return execute(command, workingDir, stdoutFile, stderrFile, null);
}
/**
* Checks if a process is still running.
*
* @param pid the process ID to check
* @return true if the process is running
*/
public boolean isRunning(long pid) {
return ProcessUtils.isAlive(pid);
}
/**
* Kills a process.
*
* @param pid the process ID to kill
* @return true if the process was killed
*/
public boolean kill(long pid) {
return ProcessUtils.killTree(pid);
}
/**
* Waits for a process to complete.
*
* @param process the process to wait for
* @param timeout the maximum time to wait
* @return the exit code if the process completed within the timeout
* @throws InterruptedException if the wait was interrupted
*/
public Optional<Integer> waitFor(Process process, Duration timeout) throws InterruptedException {
Objects.requireNonNull(process, "process must not be null");
Objects.requireNonNull(timeout, "timeout must not be null");
boolean completed = process.waitFor(timeout.toMillis(), TimeUnit.MILLISECONDS);
if (completed) {
return Optional.of(process.exitValue());
}
return Optional.empty();
}
/**
* Waits indefinitely for a process to complete.
*
* @param process the process to wait for
* @return the exit code
* @throws InterruptedException if the wait was interrupted
*/
public int waitFor(Process process) throws InterruptedException {
Objects.requireNonNull(process, "process must not be null");
return process.waitFor();
}
}
@@ -0,0 +1,192 @@
package com.samsonmedia.barn.execution;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Monitors a running process and emits events.
*
* <p>This class provides asynchronous monitoring of process execution with
* event callbacks for process lifecycle events.
*/
public class ProcessMonitor {
private static final Logger LOG = LoggerFactory.getLogger(ProcessMonitor.class);
private static final Duration DEFAULT_HEARTBEAT_INTERVAL = Duration.ofSeconds(10);
private final Duration heartbeatInterval;
/**
* Creates a ProcessMonitor with the default heartbeat interval.
*/
public ProcessMonitor() {
this(DEFAULT_HEARTBEAT_INTERVAL);
}
/**
* Creates a ProcessMonitor with a custom heartbeat interval.
*
* @param heartbeatInterval the interval between heartbeat events
*/
public ProcessMonitor(Duration heartbeatInterval) {
this.heartbeatInterval = Objects.requireNonNull(heartbeatInterval, "heartbeatInterval must not be null");
}
/**
* Monitors a process asynchronously.
*
* <p>The monitor will emit events as the process executes:
* <ul>
* <li>Started - when monitoring begins</li>
* <li>Heartbeat - periodically while running</li>
* <li>Completed - when the process exits normally</li>
* <li>Failed - if an error occurs</li>
* </ul>
*
* @param process the process to monitor
* @param eventHandler the handler to receive events
* @return a future that completes when monitoring is finished
*/
public CompletableFuture<ProcessEvent.Completed> monitor(
Process process,
Consumer<ProcessEvent> eventHandler) {
Objects.requireNonNull(process, "process must not be null");
Objects.requireNonNull(eventHandler, "eventHandler must not be null");
CompletableFuture<ProcessEvent.Completed> result = new CompletableFuture<>();
// Emit started event
long pid = process.pid();
emitEvent(eventHandler, new ProcessEvent.Started(pid, Instant.now()));
// Schedule heartbeat events
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "process-monitor-" + pid);
t.setDaemon(true);
return t;
});
scheduler.scheduleAtFixedRate(
() -> {
if (process.isAlive()) {
emitEvent(eventHandler, new ProcessEvent.Heartbeat(pid, Instant.now()));
}
},
heartbeatInterval.toMillis(),
heartbeatInterval.toMillis(),
TimeUnit.MILLISECONDS
);
// Wait for process completion in background
process.onExit().whenComplete((p, error) -> {
scheduler.shutdown();
if (error != null) {
ProcessEvent.Failed failed = new ProcessEvent.Failed(pid, error, Instant.now());
emitEvent(eventHandler, failed);
result.completeExceptionally(error);
} else {
int exitCode = p.exitValue();
ProcessEvent.Completed completed = new ProcessEvent.Completed(pid, exitCode, Instant.now());
emitEvent(eventHandler, completed);
result.complete(completed);
}
});
return result;
}
/**
* Monitors a process synchronously (blocking).
*
* @param process the process to monitor
* @param eventHandler the handler to receive events
* @return the completion event
* @throws InterruptedException if waiting was interrupted
*/
public ProcessEvent.Completed monitorBlocking(
Process process,
Consumer<ProcessEvent> eventHandler) throws InterruptedException {
try {
return monitor(process, eventHandler).get();
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Process monitoring failed", e.getCause());
}
}
private void emitEvent(Consumer<ProcessEvent> handler, ProcessEvent event) {
try {
handler.accept(event);
} catch (Exception e) {
LOG.error("Error in event handler for {}: {}", event.getClass().getSimpleName(), e.getMessage(), e);
}
}
/**
* Process lifecycle events.
*/
public sealed interface ProcessEvent {
/**
* Emitted when process monitoring starts.
*
* @param pid the process ID
* @param timestamp when the process started
*/
record Started(long pid, Instant timestamp) implements ProcessEvent { }
/**
* Emitted periodically while the process is running.
*
* @param pid the process ID
* @param timestamp when the heartbeat was emitted
*/
record Heartbeat(long pid, Instant timestamp) implements ProcessEvent { }
/**
* Emitted when the process completes.
*
* @param pid the process ID
* @param exitCode the process exit code
* @param timestamp when the process completed
*/
record Completed(long pid, int exitCode, Instant timestamp) implements ProcessEvent {
/**
* Returns true if the process completed successfully (exit code 0).
*
* @return true if exit code is 0
*/
public boolean isSuccess() {
return exitCode == 0;
}
}
/**
* Emitted when process monitoring encounters an error.
*
* @param pid the process ID
* @param error the error that occurred
* @param timestamp when the error occurred
*/
record Failed(long pid, Throwable error, Instant timestamp) implements ProcessEvent { }
}
/**
* Output type for process output events.
*/
public enum OutputType {
STDOUT,
STDERR
}
}
@@ -0,0 +1,131 @@
package com.samsonmedia.barn.execution;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Cross-platform process utilities.
*
* <p>Provides utility methods for process management that work consistently
* across Windows, macOS, and Linux.
*/
public final class ProcessUtils {
private static final Logger LOG = LoggerFactory.getLogger(ProcessUtils.class);
private ProcessUtils() {
// Utility class - prevent instantiation
}
/**
* Checks if a process with the given PID is alive.
*
* @param pid the process ID to check
* @return true if the process is running, false otherwise
*/
public static boolean isAlive(long pid) {
Optional<ProcessHandle> handle = ProcessHandle.of(pid);
return handle.isPresent() && handle.get().isAlive();
}
/**
* Kills a process and all its descendants.
*
* <p>This method attempts to gracefully terminate the process tree first,
* then forcefully kills any remaining processes.
*
* @param pid the process ID to kill
* @return true if the process was found and killed, false if not found
*/
public static boolean killTree(long pid) {
Optional<ProcessHandle> handle = ProcessHandle.of(pid);
if (handle.isEmpty()) {
LOG.debug("Process {} not found", pid);
return false;
}
ProcessHandle process = handle.get();
// Kill descendants first (depth-first)
process.descendants().forEach(descendant -> {
LOG.debug("Killing descendant process: {}", descendant.pid());
descendant.destroy();
});
// Kill the main process
LOG.debug("Killing process: {}", pid);
boolean destroyed = process.destroy();
if (!destroyed) {
LOG.debug("Graceful kill failed, forcing: {}", pid);
destroyed = process.destroyForcibly();
}
return destroyed;
}
/**
* Forcefully kills a process and all its descendants.
*
* <p>This method immediately force-kills without attempting graceful shutdown.
*
* @param pid the process ID to kill
* @return true if the process was found and killed, false if not found
*/
public static boolean killTreeForcibly(long pid) {
Optional<ProcessHandle> handle = ProcessHandle.of(pid);
if (handle.isEmpty()) {
LOG.debug("Process {} not found", pid);
return false;
}
ProcessHandle process = handle.get();
// Kill descendants first
process.descendants().forEach(descendant -> {
LOG.debug("Force killing descendant process: {}", descendant.pid());
descendant.destroyForcibly();
});
// Force kill the main process
LOG.debug("Force killing process: {}", pid);
return process.destroyForcibly();
}
/**
* Waits for a process to terminate.
*
* @param pid the process ID to wait for
* @return the process handle's onExit future, or empty if not found
*/
public static Optional<ProcessHandle> getHandle(long pid) {
return ProcessHandle.of(pid);
}
/**
* Gets the exit code of a terminated process.
*
* <p>Note: Exit codes are only available for direct child processes.
* For processes started via ProcessBuilder, use the Process object's exitValue().
*
* @param process the Process object
* @return the exit code if available
*/
public static Optional<Integer> getExitCode(Process process) {
if (process.isAlive()) {
return Optional.empty();
}
return Optional.of(process.exitValue());
}
/**
* Gets the current process's PID.
*
* @return the current process ID
*/
public static long getCurrentPid() {
return ProcessHandle.current().pid();
}
}
@@ -0,0 +1,212 @@
package com.samsonmedia.barn.execution;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import com.samsonmedia.barn.config.JobsConfig;
import com.samsonmedia.barn.jobs.Job;
import com.samsonmedia.barn.jobs.JobRepository;
import com.samsonmedia.barn.state.BarnDirectories;
import com.samsonmedia.barn.state.JobState;
/**
* Tests for JobRunner.
*/
class JobRunnerTest {
@TempDir
private Path tempDir;
private BarnDirectories dirs;
private JobRepository repository;
private JobRunner runner;
private JobsConfig config;
@BeforeEach
void setUp() throws IOException {
dirs = new BarnDirectories(tempDir);
dirs.initialize();
repository = new JobRepository(dirs);
runner = new JobRunner(repository, dirs);
config = JobsConfig.withDefaults();
}
@Nested
class Run {
@Test
void run_withSuccessfulCommand_shouldReturnSuccessResult() throws IOException {
Job job = repository.create(getEchoCommand("hello"), "test", config);
JobRunner.JobResult result = runner.run(job);
assertThat(result.isSuccess()).isTrue();
assertThat(result.exitCode()).isZero();
assertThat(result.error()).isNull();
assertThat(result.duration()).isNotNull();
}
@Test
void run_shouldUpdateJobState() throws IOException {
Job job = repository.create(getEchoCommand("hello"), "test", config);
runner.run(job);
Job updated = repository.findById(job.id()).orElseThrow();
assertThat(updated.state()).isEqualTo(JobState.SUCCEEDED);
assertThat(updated.exitCode()).isZero();
assertThat(updated.finishedAt()).isNotNull();
}
@Test
void run_withFailingCommand_shouldReturnFailureResult() throws IOException {
Job job = repository.create(getFailingCommand(), "test", config);
JobRunner.JobResult result = runner.run(job);
assertThat(result.isSuccess()).isFalse();
assertThat(result.exitCode()).isNotEqualTo(0);
assertThat(result.error()).isNotNull();
}
@Test
void run_withFailingCommand_shouldMarkJobAsFailed() throws IOException {
Job job = repository.create(getFailingCommand(), "test", config);
runner.run(job);
Job updated = repository.findById(job.id()).orElseThrow();
assertThat(updated.state()).isEqualTo(JobState.FAILED);
}
@Test
void run_shouldCaptureStdout() throws IOException {
Job job = repository.create(getEchoCommand("test output"), "test", config);
runner.run(job);
Path stdoutFile = dirs.getJobLogsDir(job.id()).resolve("stdout.log");
assertThat(Files.exists(stdoutFile)).isTrue();
String content = Files.readString(stdoutFile);
assertThat(content).contains("test output");
}
@Test
void run_shouldCaptureStderr() throws IOException {
Job job = repository.create(getStderrCommand("error output"), "test", config);
runner.run(job);
Path stderrFile = dirs.getJobLogsDir(job.id()).resolve("stderr.log");
assertThat(Files.exists(stderrFile)).isTrue();
String content = Files.readString(stderrFile);
assertThat(content).contains("error output");
}
@Test
void run_shouldWritePid() throws IOException {
Job job = repository.create(getEchoCommand("test"), "test", config);
runner.run(job);
Job updated = repository.findById(job.id()).orElseThrow();
// PID was set during execution (may be null after completion on some platforms)
assertThat(updated.startedAt()).isNotNull();
}
@Test
void run_withNullJob_shouldThrowException() {
assertThatThrownBy(() -> runner.run(null))
.isInstanceOf(NullPointerException.class);
}
}
@Nested
class JobResultRecord {
@Test
void isSuccess_withZeroExitCode_shouldReturnTrue() {
JobRunner.JobResult result = new JobRunner.JobResult(0, Duration.ofSeconds(1), null);
assertThat(result.isSuccess()).isTrue();
}
@Test
void isSuccess_withNonZeroExitCode_shouldReturnFalse() {
JobRunner.JobResult result = new JobRunner.JobResult(1, Duration.ofSeconds(1), "error");
assertThat(result.isSuccess()).isFalse();
}
@Test
void isSuccess_withNegativeExitCode_shouldReturnFalse() {
JobRunner.JobResult result = new JobRunner.JobResult(-1, Duration.ofSeconds(1), "failed to start");
assertThat(result.isSuccess()).isFalse();
}
}
@Nested
class Constructor {
@Test
void constructor_withNullRepository_shouldThrowException() {
assertThatThrownBy(() -> new JobRunner(null, dirs))
.isInstanceOf(NullPointerException.class);
}
@Test
void constructor_withNullDirs_shouldThrowException() {
assertThatThrownBy(() -> new JobRunner(repository, null))
.isInstanceOf(NullPointerException.class);
}
@Test
void constructor_withAllDependencies_shouldSucceed() {
ProcessExecutor executor = new ProcessExecutor();
ProcessMonitor monitor = new ProcessMonitor();
JobRunner customRunner = new JobRunner(executor, monitor, repository, dirs);
assertThat(customRunner).isNotNull();
}
}
// Platform-agnostic command helpers
private List<String> getEchoCommand(String message) {
if (isWindows()) {
return List.of("cmd", "/c", "echo", message);
}
return List.of("echo", message);
}
private List<String> getStderrCommand(String message) {
if (isWindows()) {
return List.of("cmd", "/c", "echo", message, "1>&2");
}
return List.of("sh", "-c", "echo '" + message + "' >&2");
}
private List<String> getFailingCommand() {
if (isWindows()) {
return List.of("cmd", "/c", "exit", "1");
}
return List.of("sh", "-c", "exit 1");
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("win");
}
}
@@ -0,0 +1,240 @@
package com.samsonmedia.barn.execution;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Tests for ProcessExecutor.
*/
class ProcessExecutorTest {
@TempDir
private Path tempDir;
private ProcessExecutor executor;
private Path stdoutFile;
private Path stderrFile;
@BeforeEach
void setUp() {
executor = new ProcessExecutor();
stdoutFile = tempDir.resolve("logs/stdout.log");
stderrFile = tempDir.resolve("logs/stderr.log");
}
@Nested
class Execute {
@Test
void execute_withValidCommand_shouldStartProcess() throws IOException, InterruptedException {
List<String> command = getEchoCommand("hello");
Process process = executor.execute(command, tempDir, stdoutFile, stderrFile);
assertThat(process).isNotNull();
assertThat(process.pid()).isGreaterThan(0);
process.waitFor();
assertThat(process.exitValue()).isZero();
}
@Test
void execute_shouldCaptureStdout() throws IOException, InterruptedException {
List<String> command = getEchoCommand("hello world");
Process process = executor.execute(command, tempDir, stdoutFile, stderrFile);
process.waitFor();
assertThat(Files.exists(stdoutFile)).isTrue();
String content = Files.readString(stdoutFile);
assertThat(content).contains("hello world");
}
@Test
void execute_shouldCaptureStderr() throws IOException, InterruptedException {
// Use a command that writes to stderr
List<String> command = getStderrCommand("error message");
Process process = executor.execute(command, tempDir, stdoutFile, stderrFile);
process.waitFor();
assertThat(Files.exists(stderrFile)).isTrue();
String content = Files.readString(stderrFile);
assertThat(content).contains("error message");
}
@Test
void execute_shouldCreateParentDirectories() throws IOException, InterruptedException {
Path nestedStdout = tempDir.resolve("deep/nested/logs/stdout.log");
Path nestedStderr = tempDir.resolve("deep/nested/logs/stderr.log");
Process process = executor.execute(getEchoCommand("test"), tempDir, nestedStdout, nestedStderr);
process.waitFor();
assertThat(Files.exists(nestedStdout.getParent())).isTrue();
}
@Test
void execute_withEnvironment_shouldPassEnvironment() throws IOException, InterruptedException {
Map<String, String> env = Map.of("TEST_VAR", "test_value");
List<String> command = getEnvPrintCommand("TEST_VAR");
Process process = executor.execute(command, tempDir, stdoutFile, stderrFile, env);
process.waitFor();
String content = Files.readString(stdoutFile);
assertThat(content).contains("test_value");
}
@Test
void execute_withNullCommand_shouldThrowException() {
assertThatThrownBy(() ->
executor.execute(null, tempDir, stdoutFile, stderrFile))
.isInstanceOf(NullPointerException.class);
}
@Test
void execute_withEmptyCommand_shouldThrowException() {
assertThatThrownBy(() ->
executor.execute(List.of(), tempDir, stdoutFile, stderrFile))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void execute_withNullWorkingDir_shouldThrowException() {
assertThatThrownBy(() ->
executor.execute(getEchoCommand("test"), null, stdoutFile, stderrFile))
.isInstanceOf(NullPointerException.class);
}
}
@Nested
class IsRunning {
@Test
void isRunning_withRunningProcess_shouldReturnTrue() throws IOException, InterruptedException {
Process process = executor.execute(getSleepCommand(60), tempDir, stdoutFile, stderrFile);
try {
assertThat(executor.isRunning(process.pid())).isTrue();
} finally {
process.destroyForcibly();
process.waitFor();
}
}
@Test
void isRunning_withTerminatedProcess_shouldReturnFalse() throws IOException, InterruptedException {
Process process = executor.execute(getEchoCommand("test"), tempDir, stdoutFile, stderrFile);
process.waitFor();
// Process handle might still exist briefly after termination
Thread.sleep(100);
assertThat(executor.isRunning(process.pid())).isFalse();
}
}
@Nested
class Kill {
@Test
void kill_withRunningProcess_shouldKillProcess() throws IOException, InterruptedException {
Process process = executor.execute(getSleepCommand(60), tempDir, stdoutFile, stderrFile);
long pid = process.pid();
boolean killed = executor.kill(pid);
assertThat(killed).isTrue();
Thread.sleep(100);
assertThat(executor.isRunning(pid)).isFalse();
}
@Test
void kill_withNonexistentPid_shouldReturnFalse() {
assertThat(executor.kill(999999999L)).isFalse();
}
}
@Nested
class WaitFor {
@Test
void waitFor_withTimeout_shouldReturnExitCode() throws IOException, InterruptedException {
Process process = executor.execute(getEchoCommand("test"), tempDir, stdoutFile, stderrFile);
Optional<Integer> exitCode = executor.waitFor(process, Duration.ofSeconds(10));
assertThat(exitCode).isPresent().hasValue(0);
}
@Test
void waitFor_withExpiredTimeout_shouldReturnEmpty() throws IOException, InterruptedException {
Process process = executor.execute(getSleepCommand(60), tempDir, stdoutFile, stderrFile);
try {
Optional<Integer> exitCode = executor.waitFor(process, Duration.ofMillis(100));
assertThat(exitCode).isEmpty();
} finally {
process.destroyForcibly();
process.waitFor();
}
}
@Test
void waitForBlocking_shouldReturnExitCode() throws IOException, InterruptedException {
Process process = executor.execute(getEchoCommand("test"), tempDir, stdoutFile, stderrFile);
int exitCode = executor.waitFor(process);
assertThat(exitCode).isZero();
}
}
// Platform-agnostic command helpers
private List<String> getEchoCommand(String message) {
if (isWindows()) {
return List.of("cmd", "/c", "echo", message);
}
return List.of("echo", message);
}
private List<String> getStderrCommand(String message) {
if (isWindows()) {
return List.of("cmd", "/c", "echo", message, "1>&2");
}
return List.of("sh", "-c", "echo '" + message + "' >&2");
}
private List<String> getEnvPrintCommand(String varName) {
if (isWindows()) {
return List.of("cmd", "/c", "echo", "%" + varName + "%");
}
return List.of("sh", "-c", "echo $" + varName);
}
private List<String> getSleepCommand(int seconds) {
if (isWindows()) {
return List.of("cmd", "/c", "timeout", "/t", String.valueOf(seconds), "/nobreak");
}
return List.of("sleep", String.valueOf(seconds));
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("win");
}
}
@@ -0,0 +1,224 @@
package com.samsonmedia.barn.execution;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
/**
* Tests for ProcessMonitor.
*/
class ProcessMonitorTest {
private ProcessMonitor monitor;
@BeforeEach
void setUp() {
monitor = new ProcessMonitor(Duration.ofMillis(100));
}
@Nested
class Monitor {
@Test
void monitor_shouldEmitStartedEvent() throws IOException, InterruptedException {
Process process = startShortProcess();
List<ProcessMonitor.ProcessEvent> events = new ArrayList<>();
CountDownLatch startedLatch = new CountDownLatch(1);
monitor.monitor(process, event -> {
events.add(event);
if (event instanceof ProcessMonitor.ProcessEvent.Started) {
startedLatch.countDown();
}
});
assertThat(startedLatch.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(events.get(0)).isInstanceOf(ProcessMonitor.ProcessEvent.Started.class);
process.waitFor();
}
@Test
void monitor_shouldEmitCompletedEvent() throws IOException, InterruptedException {
Process process = startShortProcess();
AtomicReference<ProcessMonitor.ProcessEvent.Completed> completedEvent = new AtomicReference<>();
CountDownLatch completedLatch = new CountDownLatch(1);
monitor.monitor(process, event -> {
if (event instanceof ProcessMonitor.ProcessEvent.Completed completed) {
completedEvent.set(completed);
completedLatch.countDown();
}
});
assertThat(completedLatch.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(completedEvent.get()).isNotNull();
assertThat(completedEvent.get().exitCode()).isZero();
assertThat(completedEvent.get().isSuccess()).isTrue();
}
@Test
void monitor_withLongRunningProcess_shouldEmitHeartbeats() throws IOException, InterruptedException {
Process process = startSleepProcess(2);
List<ProcessMonitor.ProcessEvent.Heartbeat> heartbeats = new ArrayList<>();
CountDownLatch heartbeatLatch = new CountDownLatch(2);
monitor.monitor(process, event -> {
if (event instanceof ProcessMonitor.ProcessEvent.Heartbeat hb) {
heartbeats.add(hb);
heartbeatLatch.countDown();
}
});
try {
assertThat(heartbeatLatch.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(heartbeats.size()).isGreaterThanOrEqualTo(2);
} finally {
process.destroyForcibly();
process.waitFor();
}
}
@Test
void monitor_shouldReturnFuture() throws IOException, InterruptedException {
Process process = startShortProcess();
CompletableFuture<ProcessMonitor.ProcessEvent.Completed> future =
monitor.monitor(process, event -> { });
ProcessMonitor.ProcessEvent.Completed completed = future.join();
assertThat(completed.exitCode()).isZero();
}
@Test
void monitor_withNullProcess_shouldThrowException() {
assertThatThrownBy(() -> monitor.monitor(null, event -> { }))
.isInstanceOf(NullPointerException.class);
}
@Test
void monitor_withNullHandler_shouldThrowException() throws IOException {
Process process = startShortProcess();
try {
assertThatThrownBy(() -> monitor.monitor(process, null))
.isInstanceOf(NullPointerException.class);
} finally {
process.destroyForcibly();
}
}
}
@Nested
class MonitorBlocking {
@Test
void monitorBlocking_shouldReturnCompletedEvent() throws IOException, InterruptedException {
Process process = startShortProcess();
ProcessMonitor.ProcessEvent.Completed completed = monitor.monitorBlocking(process, event -> { });
assertThat(completed).isNotNull();
assertThat(completed.exitCode()).isZero();
}
@Test
void monitorBlocking_shouldReceiveAllEvents() throws IOException, InterruptedException {
Process process = startShortProcess();
List<ProcessMonitor.ProcessEvent> events = new ArrayList<>();
monitor.monitorBlocking(process, events::add);
assertThat(events).isNotEmpty();
assertThat(events.get(0)).isInstanceOf(ProcessMonitor.ProcessEvent.Started.class);
assertThat(events.get(events.size() - 1)).isInstanceOf(ProcessMonitor.ProcessEvent.Completed.class);
}
}
@Nested
class ProcessEventTypes {
@Test
void started_shouldContainPidAndTimestamp() throws IOException, InterruptedException {
Process process = startShortProcess();
AtomicReference<ProcessMonitor.ProcessEvent.Started> startedEvent = new AtomicReference<>();
monitor.monitorBlocking(process, event -> {
if (event instanceof ProcessMonitor.ProcessEvent.Started started) {
startedEvent.set(started);
}
});
assertThat(startedEvent.get()).isNotNull();
assertThat(startedEvent.get().pid()).isGreaterThan(0);
assertThat(startedEvent.get().timestamp()).isNotNull();
}
@Test
void completed_isSuccess_withZeroExitCode_shouldReturnTrue() {
var completed = new ProcessMonitor.ProcessEvent.Completed(1234, 0, java.time.Instant.now());
assertThat(completed.isSuccess()).isTrue();
}
@Test
void completed_isSuccess_withNonZeroExitCode_shouldReturnFalse() {
var completed = new ProcessMonitor.ProcessEvent.Completed(1234, 1, java.time.Instant.now());
assertThat(completed.isSuccess()).isFalse();
}
}
@Nested
class EventHandlerErrors {
@Test
void monitor_withThrowingHandler_shouldContinue() throws IOException, InterruptedException {
Process process = startShortProcess();
AtomicReference<ProcessMonitor.ProcessEvent.Completed> completedEvent = new AtomicReference<>();
monitor.monitorBlocking(process, event -> {
if (event instanceof ProcessMonitor.ProcessEvent.Started) {
throw new RuntimeException("Handler error");
}
if (event instanceof ProcessMonitor.ProcessEvent.Completed completed) {
completedEvent.set(completed);
}
});
// Should still receive completed event despite handler error
assertThat(completedEvent.get()).isNotNull();
}
}
// Helper methods
private Process startShortProcess() throws IOException {
if (isWindows()) {
return new ProcessBuilder("cmd", "/c", "echo", "test").start();
}
return new ProcessBuilder("echo", "test").start();
}
private Process startSleepProcess(int seconds) throws IOException {
if (isWindows()) {
return new ProcessBuilder("cmd", "/c", "timeout", "/t", String.valueOf(seconds), "/nobreak").start();
}
return new ProcessBuilder("sleep", String.valueOf(seconds)).start();
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("win");
}
}
@@ -0,0 +1,180 @@
package com.samsonmedia.barn.execution;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
/**
* Tests for ProcessUtils.
*/
class ProcessUtilsTest {
@Nested
class IsAlive {
@Test
void isAlive_withCurrentProcess_shouldReturnTrue() {
long currentPid = ProcessUtils.getCurrentPid();
assertThat(ProcessUtils.isAlive(currentPid)).isTrue();
}
@Test
void isAlive_withNonexistentPid_shouldReturnFalse() {
// Use a very high PID that's unlikely to exist
assertThat(ProcessUtils.isAlive(999999999L)).isFalse();
}
@Test
void isAlive_withRunningProcess_shouldReturnTrue() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(getSleepCommand(5));
Process process = builder.start();
try {
assertThat(ProcessUtils.isAlive(process.pid())).isTrue();
} finally {
process.destroyForcibly();
process.waitFor();
}
}
}
@Nested
class KillTree {
@Test
void killTree_withRunningProcess_shouldKillProcess() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(getSleepCommand(60));
Process process = builder.start();
long pid = process.pid();
assertThat(ProcessUtils.isAlive(pid)).isTrue();
boolean killed = ProcessUtils.killTree(pid);
assertThat(killed).isTrue();
// Wait a moment for the process to die
Thread.sleep(100);
assertThat(ProcessUtils.isAlive(pid)).isFalse();
}
@Test
void killTree_withNonexistentPid_shouldReturnFalse() {
assertThat(ProcessUtils.killTree(999999999L)).isFalse();
}
}
@Nested
class KillTreeForcibly {
@Test
void killTreeForcibly_withRunningProcess_shouldKillProcess() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(getSleepCommand(60));
Process process = builder.start();
long pid = process.pid();
assertThat(ProcessUtils.isAlive(pid)).isTrue();
boolean killed = ProcessUtils.killTreeForcibly(pid);
assertThat(killed).isTrue();
Thread.sleep(100);
assertThat(ProcessUtils.isAlive(pid)).isFalse();
}
@Test
void killTreeForcibly_withNonexistentPid_shouldReturnFalse() {
assertThat(ProcessUtils.killTreeForcibly(999999999L)).isFalse();
}
}
@Nested
class GetHandle {
@Test
void getHandle_withCurrentProcess_shouldReturnHandle() {
long currentPid = ProcessUtils.getCurrentPid();
Optional<ProcessHandle> handle = ProcessUtils.getHandle(currentPid);
assertThat(handle).isPresent();
assertThat(handle.get().pid()).isEqualTo(currentPid);
}
@Test
void getHandle_withNonexistentPid_shouldReturnEmpty() {
Optional<ProcessHandle> handle = ProcessUtils.getHandle(999999999L);
assertThat(handle).isEmpty();
}
}
@Nested
class GetExitCode {
@Test
void getExitCode_withRunningProcess_shouldReturnEmpty() throws IOException {
ProcessBuilder builder = new ProcessBuilder(getSleepCommand(60));
Process process = builder.start();
try {
assertThat(ProcessUtils.getExitCode(process)).isEmpty();
} finally {
process.destroyForcibly();
}
}
@Test
void getExitCode_withTerminatedProcess_shouldReturnCode() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(getEchoCommand("test"));
Process process = builder.start();
process.waitFor();
assertThat(ProcessUtils.getExitCode(process)).isPresent().hasValue(0);
}
}
@Nested
class GetCurrentPid {
@Test
void getCurrentPid_shouldReturnPositiveValue() {
long pid = ProcessUtils.getCurrentPid();
assertThat(pid).isGreaterThan(0);
}
@Test
void getCurrentPid_shouldReturnConsistentValue() {
long pid1 = ProcessUtils.getCurrentPid();
long pid2 = ProcessUtils.getCurrentPid();
assertThat(pid1).isEqualTo(pid2);
}
}
// Platform-agnostic command helpers
private List<String> getSleepCommand(int seconds) {
if (isWindows()) {
return List.of("cmd", "/c", "timeout", "/t", String.valueOf(seconds), "/nobreak");
}
return List.of("sleep", String.valueOf(seconds));
}
private List<String> getEchoCommand(String message) {
if (isWindows()) {
return List.of("cmd", "/c", "echo", message);
}
return List.of("echo", message);
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("win");
}
}