diff --git a/src/proc.zig b/src/proc.zig new file mode 100644 index 0000000..dd5ed86 --- /dev/null +++ b/src/proc.zig @@ -0,0 +1,183 @@ +//! Child process helpers: spawn a job's command with logs redirected into its job directory, +//! signal its process group, and probe liveness. POSIX only for now (Windows is deferred). +const std = @import("std"); +const builtin = @import("builtin"); +const Io = std.Io; +const Dir = Io.Dir; +const File = Io.File; +const posix = std.posix; + +pub const Pid = posix.pid_t; + +pub const SpawnError = std.process.SpawnError || File.OpenError; + +/// Opens `sub_path` for appending (creating it if needed) so retries accumulate in one log. +pub fn openAppend(io: Io, dir: Dir, sub_path: []const u8) !File { + var file = try dir.createFile(io, sub_path, .{ .truncate = false }); + errdefer file.close(io); + seekToEnd(file); + return file; +} + +fn seekToEnd(file: File) void { + switch (builtin.os.tag) { + .windows, .wasi => {}, + .linux => _ = std.os.linux.lseek(file.handle, 0, std.os.linux.SEEK.END), + else => _ = std.c.lseek(file.handle, 0, std.c.SEEK.END), + } +} + +/// Spawns `command` (no shell) in `work_dir`, appending stdout/stderr to `logs/stdout.log` and +/// `logs/stderr.log` under `job_dir`. The child leads its own process group so the whole tree +/// can be signalled. Returns the child; the caller must `wait` or `kill` it. +pub fn spawnJob(io: Io, job_dir: Dir, command: []const []const u8) SpawnError!std.process.Child { + var work = try job_dir.openDir(io, "work", .{}); + defer work.close(io); + var out = try openAppend(io, job_dir, "logs/stdout.log"); + defer out.close(io); + var err = try openAppend(io, job_dir, "logs/stderr.log"); + defer err.close(io); + + return std.process.spawn(io, .{ + .argv = command, + .cwd = .{ .dir = work }, + .stdin = .ignore, + .stdout = .{ .file = out }, + .stderr = .{ .file = err }, + .pgid = 0, + }); +} + +/// Appends a line to a log file (used to record spawn failures in `stderr.log`). +pub fn appendLog(io: Io, job_dir: Dir, sub_path: []const u8, line: []const u8) !void { + var f = try openAppend(io, job_dir, sub_path); + defer f.close(io); + try f.writeStreamingAll(io, line); + try f.writeStreamingAll(io, "\n"); +} + +pub const Signal = enum { term, kill }; + +/// Signals the process group led by `pid`, falling back to the single process. +pub fn signalTree(pid: Pid, sig: Signal) void { + if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return; + const s: posix.SIG = switch (sig) { + .term => .TERM, + .kill => .KILL, + }; + posix.kill(-pid, s) catch |e| switch (e) { + error.ProcessNotFound => posix.kill(pid, s) catch {}, + else => {}, + }; +} + +/// True if a process with this pid exists (even if owned by another user). +pub fn isAlive(pid: i64) bool { + if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return false; + const p = std.math.cast(Pid, pid) orelse return false; + if (p <= 0) return false; + posix.kill(p, @enumFromInt(0)) catch |e| switch (e) { + error.ProcessNotFound => return false, + else => return true, + }; + return true; +} + +/// Maps a wait result to a shell-style exit code: signals become `128 + signal`. +pub fn exitCodeOf(term: std.process.Child.Term) i32 { + return switch (term) { + .exited => |c| c, + .signal => |s| 128 + @as(i32, @intCast(@intFromEnum(s))), + .stopped => |s| 128 + @as(i32, @intCast(@intFromEnum(s))), + .unknown => |u| @intCast(@min(u, 255)), + }; +} + +fn readAll(io: Io, dir: Dir, sub_path: []const u8) ![]u8 { + return dir.readFileAlloc(io, sub_path, std.testing.allocator, .limited(1 << 16)); +} + +fn makeJobDir(io: Io, tmp: *std.testing.TmpDir) !Dir { + try tmp.dir.createDirPath(io, "work"); + try tmp.dir.createDirPath(io, "logs"); + return tmp.dir; +} + +test "spawnJob redirects stdout and stderr and runs in work/" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try makeJobDir(io, &tmp); + + var child = try spawnJob(io, dir, &.{ "sh", "-c", "echo out; echo err >&2; pwd > where; exit 3" }); + const term = try child.wait(io); + try std.testing.expectEqual(@as(i32, 3), exitCodeOf(term)); + + const out = try readAll(io, dir, "logs/stdout.log"); + defer std.testing.allocator.free(out); + try std.testing.expectEqualStrings("out\n", out); + const err = try readAll(io, dir, "logs/stderr.log"); + defer std.testing.allocator.free(err); + try std.testing.expectEqualStrings("err\n", err); + _ = try dir.statFile(io, "work/where", .{}); +} + +test "logs append across runs" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try makeJobDir(io, &tmp); + + for (0..2) |_| { + var child = try spawnJob(io, dir, &.{ "echo", "line" }); + _ = try child.wait(io); + } + const out = try readAll(io, dir, "logs/stdout.log"); + defer std.testing.allocator.free(out); + try std.testing.expectEqualStrings("line\nline\n", out); +} + +test "spawn failure is reported" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try makeJobDir(io, &tmp); + try std.testing.expectError(error.FileNotFound, spawnJob(io, dir, &.{"/definitely/not/a/binary"})); +} + +test "signalTree kills the whole process group" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try makeJobDir(io, &tmp); + + // The shell forks a background sleeper that records its pid, then waits. + var child = try spawnJob(io, dir, &.{ "sh", "-c", "sleep 30 & echo $! > grandchild; wait" }); + const pid = child.id.?; + var tries: usize = 0; + while (tries < 200) : (tries += 1) { + _ = dir.statFile(io, "work/grandchild", .{}) catch { + try io.sleep(.fromMilliseconds(10), .real); + continue; + }; + break; + } + const raw = try readAll(io, dir, "work/grandchild"); + defer std.testing.allocator.free(raw); + const grandchild = try std.fmt.parseInt(i64, std.mem.trim(u8, raw, "\n "), 10); + try std.testing.expect(isAlive(grandchild)); + + signalTree(pid, .kill); + const term = try child.wait(io); + try std.testing.expectEqual(@as(i32, 137), exitCodeOf(term)); + // Allow the kernel to reap the orphaned sleeper. + tries = 0; + while (isAlive(grandchild) and tries < 200) : (tries += 1) try io.sleep(.fromMilliseconds(10), .real); + try std.testing.expect(!isAlive(grandchild)); +} + +test "isAlive" { + try std.testing.expect(isAlive(std.os.linux.getpid())); + try std.testing.expect(!isAlive(-1)); + try std.testing.expect(!isAlive(0)); +} diff --git a/src/retry.zig b/src/retry.zig new file mode 100644 index 0000000..a70c28c --- /dev/null +++ b/src/retry.zig @@ -0,0 +1,54 @@ +//! Retry policy: whether a failed job is retried, and with what delay. +//! Delay is `base * multiplier^retry_count`, jittered by 0.8..1.2, capped at one hour. +const std = @import("std"); + +pub const max_delay_seconds: f64 = 3600; +pub const jitter_min = 0.8; +pub const jitter_max = 1.2; + +/// A job is retried when retries are enabled, attempts remain, it exited non-zero, and the +/// exit code is retryable (an empty `retry_codes` list means every non-zero code is). +/// Jobs without a numeric exit code (symbolic failures, timeouts) are never retried. +pub fn shouldRetry(retry_count: u32, max_retries: u32, exit_code: ?i32, retry_codes: []const i32) bool { + if (max_retries == 0 or retry_count >= max_retries) return false; + const code = exit_code orelse return false; + if (code == 0) return false; + if (retry_codes.len == 0) return true; + return std.mem.indexOfScalar(i32, retry_codes, code) != null; +} + +/// Delay in whole seconds. `random == null` disables jitter (deterministic, for tests). +pub fn delaySeconds(retry_count: u32, base_seconds: u32, multiplier: f64, random: ?std.Random) u64 { + var d: f64 = @as(f64, @floatFromInt(base_seconds)) * std.math.pow(f64, multiplier, @floatFromInt(retry_count)); + if (random) |r| d *= jitter_min + r.float(f64) * (jitter_max - jitter_min); + return @intFromFloat(@min(d, max_delay_seconds)); +} + +test "shouldRetry honours limits, success and exit-code filters" { + try std.testing.expect(shouldRetry(0, 3, 1, &.{})); + try std.testing.expect(shouldRetry(2, 3, 137, &.{})); + try std.testing.expect(!shouldRetry(3, 3, 1, &.{})); + try std.testing.expect(!shouldRetry(0, 0, 1, &.{})); + try std.testing.expect(!shouldRetry(0, 3, 0, &.{})); + try std.testing.expect(!shouldRetry(0, 3, null, &.{})); + try std.testing.expect(shouldRetry(0, 3, 137, &.{ 1, 137 })); + try std.testing.expect(!shouldRetry(0, 3, 2, &.{ 1, 137 })); +} + +test "delay grows exponentially without jitter and is capped" { + try std.testing.expectEqual(@as(u64, 30), delaySeconds(0, 30, 2.0, null)); + try std.testing.expectEqual(@as(u64, 60), delaySeconds(1, 30, 2.0, null)); + try std.testing.expectEqual(@as(u64, 120), delaySeconds(2, 30, 2.0, null)); + try std.testing.expectEqual(@as(u64, 3600), delaySeconds(20, 30, 2.0, null)); + try std.testing.expectEqual(@as(u64, 0), delaySeconds(3, 0, 2.0, null)); + try std.testing.expectEqual(@as(u64, 30), delaySeconds(5, 30, 1.0, null)); +} + +test "jitter stays within 0.8..1.2 of the base delay" { + var prng = std.Random.DefaultPrng.init(42); + const r = prng.random(); + for (0..200) |_| { + const d = delaySeconds(1, 100, 2.0, r); + try std.testing.expect(d >= 160 and d <= 240); + } +} diff --git a/src/root.zig b/src/root.zig index faccd42..427bbf6 100644 --- a/src/root.zig +++ b/src/root.zig @@ -14,6 +14,8 @@ pub const repository = @import("repository.zig"); pub const defaults = @import("defaults.zig"); pub const config = @import("config.zig"); pub const loadclass = @import("loadclass.zig"); +pub const retry = @import("retry.zig"); +pub const proc = @import("proc.zig"); test { @import("std").testing.refAllDecls(@This());