Implement process execution engine #5

Closed
opened 2026-10-04 19:27:57 +00:00 by daniel · 1 comment
Owner

Imported from GitHub samson-media/barn#5 — opened by @daniel-samson on 2026-01-21 12:36:17 UTC

Overview

Implement the process execution engine that runs commands and captures output.

Context

  • Read first: docs/jobs.md (logs directory layout)
  • Depends on: #4 (Job model), #3 (filesystem state)

Requirements

1. Process Executor

com.samsonmedia.barn.execution.ProcessExecutor.java:

public class ProcessExecutor {
    // Start a process and return handle
    public ProcessHandle execute(
        List<String> command,
        Path workingDir,
        Path stdoutFile,
        Path stderrFile,
        Map<String, String> environment
    ) throws IOException;
    
    // Check if process is still running
    public boolean isRunning(long pid);
    
    // Kill process
    public void kill(long pid);
    
    // Get exit code (blocks until complete or timeout)
    public Optional<Integer> waitFor(long pid, Duration timeout);
}

2. Output Capture

Stdout and stderr should be:

  • Written to log files in <job-dir>/logs/
  • Captured in real-time (not buffered until completion)
  • Appended, never overwritten
// Log file layout:
// <job-dir>/logs/stdout.log
// <job-dir>/logs/stderr.log

3. Process Monitor

com.samsonmedia.barn.execution.ProcessMonitor.java:

public class ProcessMonitor {
    // Monitor a running process
    public void monitor(Job job, Process process, Consumer<ProcessEvent> eventHandler);
    
    // Events
    public sealed interface ProcessEvent {
        record Started(long pid) implements ProcessEvent { }
        record Output(String line, OutputType type) implements ProcessEvent { }
        record Completed(int exitCode) implements ProcessEvent { }
        record Failed(Exception error) implements ProcessEvent { }
    }
    
    public enum OutputType { STDOUT, STDERR }
}

4. Job Runner

com.samsonmedia.barn.execution.JobRunner.java:

public class JobRunner {
    private final ProcessExecutor executor;
    private final JobRepository repository;
    
    // Run a job (blocking)
    public JobResult run(Job job) {
        // 1. Update state to RUNNING
        // 2. Write PID file
        // 3. Execute command
        // 4. Update heartbeat periodically
        // 5. On completion, update state to SUCCEEDED/FAILED
        // 6. Write exit_code, error, finished_at
    }
    
    public record JobResult(int exitCode, Duration duration, String error) { }
}

5. Cross-Platform Considerations

  • On Windows, use ProcessBuilder with proper command escaping
  • Handle SIGTERM/SIGKILL on Unix, TerminateProcess on Windows
  • Process groups for killing child processes
public final class ProcessUtils {
    // Kill process and all children
    public static void killTree(long pid);
    
    // Check if PID exists
    public static boolean isAlive(long pid);
}

6. Tests Required

  • ProcessExecutorTest.java: Test execution, output capture, kill
  • ProcessMonitorTest.java: Test event streaming
  • JobRunnerTest.java: Test full job lifecycle
  • ProcessUtilsTest.java: Test cross-platform utilities

Acceptance Criteria

  • Commands execute with captured stdout/stderr
  • Process PID correctly tracked
  • Process can be killed mid-execution
  • Exit codes correctly captured
  • Works on Windows, macOS, Linux
  • mvn verify passes
  • Tests have 80%+ coverage

Implementation Notes

ProcessBuilder setup:

ProcessBuilder pb = new ProcessBuilder(command);
pb.directory(workingDir.toFile());
pb.redirectOutput(ProcessBuilder.Redirect.appendTo(stdoutFile.toFile()));
pb.redirectError(ProcessBuilder.Redirect.appendTo(stderrFile.toFile()));
Process process = pb.start();

For heartbeat updates during execution:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(
    () -> repository.updateHeartbeat(job.id(), Instant.now()),
    0, heartbeatInterval, TimeUnit.SECONDS
);

Definition of Done

  • Processes execute correctly
  • Output captured to files
  • PID tracked and killable
  • All tests pass
<!-- github-import:issue:5 --> _Imported from GitHub samson-media/barn#5 — opened by **@daniel-samson** on 2026-01-21 12:36:17 UTC_ ## Overview Implement the process execution engine that runs commands and captures output. ## Context - **Read first**: `docs/jobs.md` (logs directory layout) - **Depends on**: #4 (Job model), #3 (filesystem state) ## Requirements ### 1. Process Executor `com.samsonmedia.barn.execution.ProcessExecutor.java`: ```java public class ProcessExecutor { // Start a process and return handle public ProcessHandle execute( List<String> command, Path workingDir, Path stdoutFile, Path stderrFile, Map<String, String> environment ) throws IOException; // Check if process is still running public boolean isRunning(long pid); // Kill process public void kill(long pid); // Get exit code (blocks until complete or timeout) public Optional<Integer> waitFor(long pid, Duration timeout); } ``` ### 2. Output Capture Stdout and stderr should be: - Written to log files in `<job-dir>/logs/` - Captured in real-time (not buffered until completion) - Appended, never overwritten ```java // Log file layout: // <job-dir>/logs/stdout.log // <job-dir>/logs/stderr.log ``` ### 3. Process Monitor `com.samsonmedia.barn.execution.ProcessMonitor.java`: ```java public class ProcessMonitor { // Monitor a running process public void monitor(Job job, Process process, Consumer<ProcessEvent> eventHandler); // Events public sealed interface ProcessEvent { record Started(long pid) implements ProcessEvent { } record Output(String line, OutputType type) implements ProcessEvent { } record Completed(int exitCode) implements ProcessEvent { } record Failed(Exception error) implements ProcessEvent { } } public enum OutputType { STDOUT, STDERR } } ``` ### 4. Job Runner `com.samsonmedia.barn.execution.JobRunner.java`: ```java public class JobRunner { private final ProcessExecutor executor; private final JobRepository repository; // Run a job (blocking) public JobResult run(Job job) { // 1. Update state to RUNNING // 2. Write PID file // 3. Execute command // 4. Update heartbeat periodically // 5. On completion, update state to SUCCEEDED/FAILED // 6. Write exit_code, error, finished_at } public record JobResult(int exitCode, Duration duration, String error) { } } ``` ### 5. Cross-Platform Considerations - On Windows, use `ProcessBuilder` with proper command escaping - Handle SIGTERM/SIGKILL on Unix, TerminateProcess on Windows - Process groups for killing child processes ```java public final class ProcessUtils { // Kill process and all children public static void killTree(long pid); // Check if PID exists public static boolean isAlive(long pid); } ``` ### 6. Tests Required - `ProcessExecutorTest.java`: Test execution, output capture, kill - `ProcessMonitorTest.java`: Test event streaming - `JobRunnerTest.java`: Test full job lifecycle - `ProcessUtilsTest.java`: Test cross-platform utilities ## Acceptance Criteria - [ ] Commands execute with captured stdout/stderr - [ ] Process PID correctly tracked - [ ] Process can be killed mid-execution - [ ] Exit codes correctly captured - [ ] Works on Windows, macOS, Linux - [ ] `mvn verify` passes - [ ] Tests have 80%+ coverage ## Implementation Notes ProcessBuilder setup: ```java ProcessBuilder pb = new ProcessBuilder(command); pb.directory(workingDir.toFile()); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(stdoutFile.toFile())); pb.redirectError(ProcessBuilder.Redirect.appendTo(stderrFile.toFile())); Process process = pb.start(); ``` For heartbeat updates during execution: ```java ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate( () -> repository.updateHeartbeat(job.id(), Instant.now()), 0, heartbeatInterval, TimeUnit.SECONDS ); ``` ## Definition of Done - Processes execute correctly - Output captured to files - PID tracked and killable - All tests pass
daniel added this to the M2: Job Execution milestone 2026-10-04 19:27:57 +00:00
daniel added the execution label 2026-10-04 19:27:57 +00:00
Author
Owner

@daniel-samson commented on 2026-01-21 13:20:03 UTC:

Implemented in commit 818c45d:

Implementation complete:

  • ProcessUtils for cross-platform process management
  • ProcessExecutor for command execution with output capture
  • ProcessMonitor for event streaming (Started, Heartbeat, Completed, Failed)
  • JobRunner for job lifecycle orchestration

Test coverage: 54 new tests, 352 total tests passing

<!-- github-import:comment:3778105399 --> _**@daniel-samson** commented on 2026-01-21 13:20:03 UTC:_ Implemented in commit 818c45d: **Implementation complete:** - ProcessUtils for cross-platform process management - ProcessExecutor for command execution with output capture - ProcessMonitor for event streaming (Started, Heartbeat, Completed, Failed) - JobRunner for job lifecycle orchestration **Test coverage:** 54 new tests, 352 total tests passing
This repo is archived. You cannot comment on issues.