Implement service daemon main loop #15

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

Imported from GitHub samson-media/barn#15 — opened by @daniel-samson on 2026-01-21 12:40:42 UTC

Overview

Implement the service daemon main loop that orchestrates all service components.

Context

  • Read first: README.md (service overview), docs/config.md (service settings)
  • Depends on: #6 (scheduler), #7 (crash recovery), #14 (IPC)

Requirements

1. Service Daemon

com.samsonmedia.barn.service.BarnService.java:

public class BarnService {
    private final Config config;
    private final JobScheduler scheduler;
    private final IpcServer ipcServer;
    private final CleanupScheduler cleanupScheduler;
    private final CrashRecovery crashRecovery;

    public void start() {
        // 1. Initialize directories
        // 2. Run crash recovery
        // 3. Start scheduler
        // 4. Start IPC server
        // 5. Start cleanup scheduler
        // 6. Block until shutdown signal
    }

    public void stop() {
        // 1. Stop accepting new jobs
        // 2. Stop IPC server
        // 3. Wait for running jobs (graceful) or kill (forced)
        // 4. Stop cleanup scheduler
    }

    public void reload() {
        // 1. Re-read config file
        // 2. Apply non-restart settings
        // 3. Log changes
    }
}

2. Startup Sequence

  1. Load Configuration: Read config file, apply env overrides
  2. Initialize Directories: Create /tmp/barn/{jobs,locks,logs}
  3. Acquire Scheduler Lock: Ensure single instance
  4. Crash Recovery: Scan for orphaned jobs, mark as failed
  5. Start Scheduler: Begin processing queued jobs
  6. Start IPC Server: Accept CLI connections
  7. Start Cleanup Scheduler: Periodic cleanup task
  8. Log Ready: Log "Barn service started"

3. Shutdown Sequence

  1. Stop IPC Server: Reject new connections
  2. Stop Cleanup Scheduler: Cancel pending cleanup
  3. Graceful Scheduler Stop: Wait for running jobs up to timeout
  4. Force Kill: If timeout exceeded, kill remaining jobs
  5. Release Scheduler Lock: Remove lock file
  6. Log Shutdown: Log "Barn service stopped"

4. Signal Handling

public class SignalHandler {
    public static void register(BarnService service) {
        // SIGTERM/SIGINT -> graceful shutdown
        Runtime.getRuntime().addShutdownHook(new Thread(service::stop));

        // SIGHUP -> reload config (Unix only)
        if (!OS.isWindows()) {
            Signal.handle(new Signal("HUP"), sig -> service.reload());
        }
    }
}

5. Cleanup Scheduler

com.samsonmedia.barn.service.CleanupScheduler.java:

public class CleanupScheduler {
    private final ScheduledExecutorService executor;

    public void start(Duration interval) {
        executor.scheduleAtFixedRate(
            this::runCleanup,
            interval.toMinutes(),
            interval.toMinutes(),
            TimeUnit.MINUTES
        );
    }

    private void runCleanup() {
        // Find and remove old jobs based on config
    }
}

6. Health Check

public record ServiceHealth(
    boolean running,
    int activeJobs,
    int queuedJobs,
    Instant startedAt,
    long uptimeSeconds
) {}

7. Tests Required

  • BarnServiceTest.java: Test startup/shutdown sequence
  • SignalHandlerTest.java: Test signal handling
  • CleanupSchedulerTest.java: Test periodic cleanup
  • Integration test: Full service lifecycle

Acceptance Criteria

  • Service starts all components in order
  • Crash recovery runs before accepting jobs
  • Graceful shutdown waits for jobs
  • SIGHUP reloads configuration
  • Only one service instance can run
  • Cleanup runs periodically
  • mvn verify passes
  • Tests have 80%+ coverage

Implementation Notes

Blocking main thread until shutdown:

CountDownLatch shutdownLatch = new CountDownLatch(1);

// In shutdown handler
shutdownLatch.countDown();

// In main
shutdownLatch.await();

Graceful shutdown timeout:

if (!scheduler.awaitTermination(shutdownTimeout, TimeUnit.SECONDS)) {
    LOG.warn("Timeout waiting for jobs, forcing shutdown");
    scheduler.shutdownNow();
}

Definition of Done

  • Service starts and stops cleanly
  • All components coordinated
  • Signals handled correctly
  • All tests pass
<!-- github-import:issue:15 --> _Imported from GitHub samson-media/barn#15 — opened by **@daniel-samson** on 2026-01-21 12:40:42 UTC_ ## Overview Implement the service daemon main loop that orchestrates all service components. ## Context - **Read first**: `README.md` (service overview), `docs/config.md` (service settings) - **Depends on**: #6 (scheduler), #7 (crash recovery), #14 (IPC) ## Requirements ### 1. Service Daemon `com.samsonmedia.barn.service.BarnService.java`: ```java public class BarnService { private final Config config; private final JobScheduler scheduler; private final IpcServer ipcServer; private final CleanupScheduler cleanupScheduler; private final CrashRecovery crashRecovery; public void start() { // 1. Initialize directories // 2. Run crash recovery // 3. Start scheduler // 4. Start IPC server // 5. Start cleanup scheduler // 6. Block until shutdown signal } public void stop() { // 1. Stop accepting new jobs // 2. Stop IPC server // 3. Wait for running jobs (graceful) or kill (forced) // 4. Stop cleanup scheduler } public void reload() { // 1. Re-read config file // 2. Apply non-restart settings // 3. Log changes } } ``` ### 2. Startup Sequence 1. **Load Configuration**: Read config file, apply env overrides 2. **Initialize Directories**: Create /tmp/barn/{jobs,locks,logs} 3. **Acquire Scheduler Lock**: Ensure single instance 4. **Crash Recovery**: Scan for orphaned jobs, mark as failed 5. **Start Scheduler**: Begin processing queued jobs 6. **Start IPC Server**: Accept CLI connections 7. **Start Cleanup Scheduler**: Periodic cleanup task 8. **Log Ready**: Log "Barn service started" ### 3. Shutdown Sequence 1. **Stop IPC Server**: Reject new connections 2. **Stop Cleanup Scheduler**: Cancel pending cleanup 3. **Graceful Scheduler Stop**: Wait for running jobs up to timeout 4. **Force Kill**: If timeout exceeded, kill remaining jobs 5. **Release Scheduler Lock**: Remove lock file 6. **Log Shutdown**: Log "Barn service stopped" ### 4. Signal Handling ```java public class SignalHandler { public static void register(BarnService service) { // SIGTERM/SIGINT -> graceful shutdown Runtime.getRuntime().addShutdownHook(new Thread(service::stop)); // SIGHUP -> reload config (Unix only) if (!OS.isWindows()) { Signal.handle(new Signal("HUP"), sig -> service.reload()); } } } ``` ### 5. Cleanup Scheduler `com.samsonmedia.barn.service.CleanupScheduler.java`: ```java public class CleanupScheduler { private final ScheduledExecutorService executor; public void start(Duration interval) { executor.scheduleAtFixedRate( this::runCleanup, interval.toMinutes(), interval.toMinutes(), TimeUnit.MINUTES ); } private void runCleanup() { // Find and remove old jobs based on config } } ``` ### 6. Health Check ```java public record ServiceHealth( boolean running, int activeJobs, int queuedJobs, Instant startedAt, long uptimeSeconds ) {} ``` ### 7. Tests Required - `BarnServiceTest.java`: Test startup/shutdown sequence - `SignalHandlerTest.java`: Test signal handling - `CleanupSchedulerTest.java`: Test periodic cleanup - Integration test: Full service lifecycle ## Acceptance Criteria - [ ] Service starts all components in order - [ ] Crash recovery runs before accepting jobs - [ ] Graceful shutdown waits for jobs - [ ] SIGHUP reloads configuration - [ ] Only one service instance can run - [ ] Cleanup runs periodically - [ ] `mvn verify` passes - [ ] Tests have 80%+ coverage ## Implementation Notes Blocking main thread until shutdown: ```java CountDownLatch shutdownLatch = new CountDownLatch(1); // In shutdown handler shutdownLatch.countDown(); // In main shutdownLatch.await(); ``` Graceful shutdown timeout: ```java if (!scheduler.awaitTermination(shutdownTimeout, TimeUnit.SECONDS)) { LOG.warn("Timeout waiting for jobs, forcing shutdown"); scheduler.shutdownNow(); } ``` ## Definition of Done - Service starts and stops cleanly - All components coordinated - Signals handled correctly - All tests pass
daniel added this to the M4: Service Infrastructure milestone 2026-10-04 19:28:15 +00:00
daniel added the service label 2026-10-04 19:28:15 +00:00
Author
Owner

@daniel-samson commented on 2026-01-21 14:29:25 UTC:

Implemented service daemon main loop with tests

<!-- github-import:comment:3778429533 --> _**@daniel-samson** commented on 2026-01-21 14:29:25 UTC:_ Implemented service daemon main loop with tests
This repo is archived. You cannot comment on issues.