feat: daemon process management (M4 part 3)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Sonnet 5.5 committed 2026-10-17 13:32:53 +01:00
1 parent 01a3fbfa29
commit 0d91b0490a
4 files changed
+266

No files matched your search

+1
View File
@@ -46,3 +46,4 @@ Guidance for AI coding agents working in `zag`, the Zig port of the
| `src/jobjson.zig` | `Job` JSON (shared by CLI `--output=json` and IPC) |
| `src/ipc.zig` | NDJSON-over-Unix-socket server and client |
| `src/service.zig` | Daemon core: recovery, scheduler, IPC handlers, cleanup timer, reload |
| `src/daemon.zig` | pid file, foreground run loop + signals, detached start, stop (TERM/KILL) |
+256
View File
@@ -0,0 +1,256 @@
//! Daemon process management: pid file, foreground run loop with signal handling, background
//! start (re-exec detached), and stop. `zag service start|stop|...` are thin wrappers over this.
const std = @import("std");
const builtin = @import("builtin");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const posix = std.posix;
const dirs_mod = @import("dirs.zig");
const Dirs = dirs_mod.Dirs;
const service_mod = @import("service.zig");
const Service = service_mod.Service;
const proc = @import("proc.zig");
const ipc = @import("ipc.zig");
const fsutil = @import("fsutil.zig");
const Repository = @import("repository.zig").Repository;
// -- pid file --------------------------------------------------------------------------
pub fn writePidFile(io: Io, dirs: *Dirs, pid: i64) !void {
var buf: [24]u8 = undefined;
try fsutil.writeAtomic(io, dirs.base, dirs_mod.pid_file, try std.fmt.bufPrint(&buf, "{d}", .{pid}));
}
pub fn readPidFile(io: Io, dirs: *Dirs) !?i64 {
var buf: [32]u8 = undefined;
const text = (try fsutil.readTrimmedBuf(io, dirs.base, dirs_mod.pid_file, &buf)) orelse return null;
return std.fmt.parseInt(i64, text, 10) catch null;
}
pub fn removePidFile(io: Io, dirs: *Dirs) void {
fsutil.deleteIfExists(io, dirs.base, dirs_mod.pid_file) catch {};
}
/// The daemon's pid if its pid file names a live process.
pub fn runningPid(io: Io, dirs: *Dirs) ?i64 {
const pid = (readPidFile(io, dirs) catch null) orelse return null;
return if (proc.isAlive(pid)) pid else null;
}
// -- foreground ------------------------------------------------------------------------
var g_stop = std.atomic.Value(bool).init(false);
var g_reload = std.atomic.Value(bool).init(false);
fn onSignal(sig: posix.SIG) callconv(.c) void {
switch (sig) {
.HUP => g_reload.store(true, .release),
else => g_stop.store(true, .release),
}
}
fn installSignalHandlers() void {
if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return;
const act: posix.Sigaction = .{
.handler = .{ .handler = onSignal },
.mask = posix.sigemptyset(),
.flags = 0,
};
posix.sigaction(.TERM, &act, null);
posix.sigaction(.INT, &act, null);
posix.sigaction(.HUP, &act, null);
}
pub const RunError = error{AlreadyRunning} || Service.StartError;
/// Runs the daemon until SIGTERM/SIGINT or an IPC `shutdown`. SIGHUP reloads the configuration.
/// `svc` must already be `bind`-ed. Removes the pid file on the way out.
pub fn runForeground(io: Io, dirs: *Dirs, svc: *Service) RunError!void {
if (runningPid(io, dirs)) |pid| {
if (pid != proc.currentPid()) return error.AlreadyRunning;
}
g_stop.store(false, .release);
g_reload.store(false, .release);
installSignalHandlers();
svc.start() catch |err| switch (err) {
error.AlreadyRunning => return error.AlreadyRunning,
else => return err,
};
writePidFile(io, dirs, proc.currentPid()) catch {};
defer removePidFile(io, dirs);
while (!g_stop.load(.acquire) and !svc.shutdown_requested.load(.acquire)) {
if (g_reload.swap(false, .acq_rel)) {
svc.reload() catch |err| std.log.err("reload failed: {s}", .{@errorName(err)});
}
io.sleep(.fromMilliseconds(100), .real) catch break;
}
std.log.info("shutting down", .{});
const remaining = svc.stop();
if (remaining > 0) {
std.log.warn("{d} job(s) still running after the grace period; killing them", .{remaining});
svc.scheduler.killAll(true);
var waited: u32 = 0;
while (svc.scheduler.activeCount() > 0 and waited < 5000) : (waited += 20) {
io.sleep(.fromMilliseconds(20), .real) catch break;
}
}
}
// -- background start / stop -----------------------------------------------------------
pub const StartError = error{ AlreadyRunning, StartTimeout } || std.process.SpawnError || Io.File.OpenError || Allocator.Error;
/// Re-executes `argv` (typically `zag service start --foreground ...`) as a detached daemon with
/// stdout/stderr appended to `log_file`, then waits until it answers on `socket_path`.
pub fn startBackground(io: Io, arena: Allocator, dirs: *Dirs, argv: []const []const u8, socket_path: []const u8, timeout_ms: u64) StartError!i64 {
if (runningPid(io, dirs)) |_| return error.AlreadyRunning;
var log = try proc.openAppend(io, dirs.base, dirs_mod.daemon_log);
defer log.close(io);
const child = try std.process.spawn(io, .{
.argv = argv,
.stdin = .ignore,
.stdout = .{ .file = log },
.stderr = .{ .file = log },
.pgid = 0, // own process group: survives the launching terminal / ssh session
});
const pid: i64 = child.id orelse 0;
var waited: u64 = 0;
while (waited < timeout_ms) : (waited += 50) {
if (ipc.call(io, arena, socket_path, "get_service_status", null)) |reply| {
if (reply == .ok) return pid;
} else |_| {}
if (!proc.isAlive(pid)) break; // crashed during startup; see the log
io.sleep(.fromMilliseconds(50), .real) catch break;
}
return error.StartTimeout;
}
pub const StopResult = enum {
/// The daemon exited after SIGTERM.
stopped,
/// No live daemon; stale pid file removed if present.
not_running,
/// Still running after the timeout (and `force` was not given).
timed_out,
/// SIGKILLed after the timeout, together with its running jobs.
killed,
};
/// Stops the daemon: SIGTERM and wait; with `force`, SIGKILL it and its running jobs on timeout.
pub fn stopDaemon(io: Io, gpa: Allocator, dirs: *Dirs, timeout_ms: u64, force: bool) StopResult {
const pid = (readPidFile(io, dirs) catch null) orelse return .not_running;
if (!proc.isAlive(pid)) {
removePidFile(io, dirs);
return .not_running;
}
proc.signalTree(@intCast(pid), .term);
var waited: u64 = 0;
while (waited < timeout_ms) : (waited += 50) {
if (!proc.isAlive(pid)) return .stopped;
io.sleep(.fromMilliseconds(50), .real) catch break;
}
if (!force) return .timed_out;
killRunningJobs(io, gpa, dirs);
proc.signalTree(@intCast(pid), .kill);
waited = 0;
while (proc.isAlive(pid) and waited < 5000) : (waited += 50) {
io.sleep(.fromMilliseconds(50), .real) catch break;
}
removePidFile(io, dirs);
return .killed;
}
/// SIGKILLs the process group of every job recorded as running (used by a forced stop, which
/// leaves the daemon no chance to do it; the next start recovers them as orphans).
fn killRunningJobs(io: Io, gpa: Allocator, dirs: *Dirs) void {
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const repo = Repository.init(io, dirs);
const running = repo.findByState(arena_state.allocator(), .running) catch return;
for (running) |job| {
if (job.pid) |p| if (p > 0) proc.signalTree(@intCast(p), .kill);
}
}
// -- tests -----------------------------------------------------------------------------
test "pid file round trip and liveness" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const base = try std.fmt.allocPrint(arena.allocator(), ".zig-cache/tmp/{s}/zag", .{tmp.sub_path});
var dirs = try Dirs.open(io, base);
defer dirs.close(io);
try std.testing.expect((try readPidFile(io, &dirs)) == null);
try std.testing.expect(runningPid(io, &dirs) == null);
try writePidFile(io, &dirs, proc.currentPid());
try std.testing.expectEqual(proc.currentPid(), (try readPidFile(io, &dirs)).?);
try std.testing.expectEqual(proc.currentPid(), runningPid(io, &dirs).?);
try writePidFile(io, &dirs, 999_999_999);
try std.testing.expect(runningPid(io, &dirs) == null);
removePidFile(io, &dirs);
try std.testing.expect((try readPidFile(io, &dirs)) == null);
}
test "stopDaemon handles missing and stale pid files" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const base = try std.fmt.allocPrint(arena.allocator(), ".zig-cache/tmp/{s}/zag", .{tmp.sub_path});
var dirs = try Dirs.open(io, base);
defer dirs.close(io);
try std.testing.expectEqual(StopResult.not_running, stopDaemon(io, std.testing.allocator, &dirs, 100, false));
try writePidFile(io, &dirs, 999_999_999);
try std.testing.expectEqual(StopResult.not_running, stopDaemon(io, std.testing.allocator, &dirs, 100, false));
try std.testing.expect((try readPidFile(io, &dirs)) == null); // stale file cleaned up
}
test "stopDaemon terminates a live process, escalating with force" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const base = try std.fmt.allocPrint(arena.allocator(), ".zig-cache/tmp/{s}/zag", .{tmp.sub_path});
var dirs = try Dirs.open(io, base);
defer dirs.close(io);
// Cooperative process: dies on SIGTERM.
var child = try std.process.spawn(io, .{ .argv = &.{ "sleep", "30" }, .pgid = 0, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore });
try writePidFile(io, &dirs, child.id.?);
const waiter = try std.Thread.spawn(.{}, struct {
fn go(c: *std.process.Child, i: Io) void {
_ = c.wait(i) catch {};
}
}.go, .{ &child, io });
try std.testing.expectEqual(StopResult.stopped, stopDaemon(io, std.testing.allocator, &dirs, 3000, false));
waiter.join();
// Stubborn process: ignores SIGTERM, needs force.
var stubborn = try std.process.spawn(io, .{ .argv = &.{ "sh", "-c", "trap '' TERM; while true; do sleep 1; done" }, .pgid = 0, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore });
try writePidFile(io, &dirs, stubborn.id.?);
const waiter2 = try std.Thread.spawn(.{}, struct {
fn go(c: *std.process.Child, i: Io) void {
_ = c.wait(i) catch {};
}
}.go, .{ &stubborn, io });
try io.sleep(.fromMilliseconds(200), .real); // let the shell install its trap
try std.testing.expectEqual(StopResult.timed_out, stopDaemon(io, std.testing.allocator, &dirs, 300, false));
try std.testing.expectEqual(StopResult.killed, stopDaemon(io, std.testing.allocator, &dirs, 300, true));
waiter2.join();
}
+1
View File
@@ -24,6 +24,7 @@ pub const cleanup = @import("cleanup.zig");
pub const jobjson = @import("jobjson.zig");
pub const ipc = @import("ipc.zig");
pub const service = @import("service.zig");
pub const daemon = @import("daemon.zig");
test {
@import("std").testing.refAllDecls(@This());
+8
View File
@@ -211,6 +211,14 @@ pub const Scheduler = struct {
self.gpa.destroy(entry);
}
/// Asks every running job to stop (they end up canceled).
pub fn killAll(self: *Scheduler, force: bool) void {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
var it = self.active.valueIterator();
while (it.next()) |entry| entry.*.ctl.requestKill(force);
}
/// Kills a job: signals it if it is running here, cancels it if still queued.
pub fn killJob(self: *Scheduler, id: []const u8, force: bool) !KillResult {
{