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();
}
}