Files
zag/src/recovery.zig
T

114 lines
5.0 KiB
Zig

//! Crash recovery: on daemon start, running jobs whose heartbeat is stale and whose process is
//! gone are orphans. They are marked KILLED and, when retries remain, re-queued.
const std = @import("std");
const Allocator = std.mem.Allocator;
const Io = std.Io;
const Repository = @import("repository.zig").Repository;
const Job = @import("job.zig").Job;
const Instant = @import("job.zig").Instant;
const proc = @import("proc.zig");
const retry = @import("retry.zig");
const timestamp = @import("timestamp.zig");
pub const killed_error = "Process killed - daemon restarted";
/// A running job with no heartbeat, or one older than `threshold_seconds`, is stale.
pub fn isStale(job: Job, now: Instant, threshold_seconds: u32) bool {
if (job.state != .running) return false;
const hb = job.heartbeat orelse return true;
return hb < now - @as(Instant, threshold_seconds) * std.time.ns_per_s;
}
/// Stale heartbeat and no live process (or no pid recorded at all).
pub fn isOrphaned(job: Job, now: Instant, threshold_seconds: u32) bool {
if (!isStale(job, now, threshold_seconds)) return false;
const pid = job.pid orelse return true;
return !proc.isAlive(pid);
}
pub const Options = struct {
stale_threshold_seconds: u32 = 30,
random: ?std.Random = null,
};
/// Recovers all orphaned jobs and returns how many were handled.
pub fn recoverOrphanedJobs(gpa: Allocator, io: Io, repo: Repository, opts: Options) !usize {
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
const now = timestamp.now(io);
var recovered: usize = 0;
for (try repo.findByState(arena, .running)) |job| {
if (!isOrphaned(job, now, opts.stale_threshold_seconds)) continue;
repo.markKilled(job.id, killed_error) catch |err| {
std.log.err("recovery: cannot mark {s} killed: {s}", .{ job.id, @errorName(err) });
continue;
};
recovered += 1;
const manifest = repo.loadManifest(arena, job.id) catch continue;
if (manifest.max_retries > 0 and job.retry_count < manifest.max_retries) {
const delay = retry.delaySeconds(job.retry_count, manifest.retry_delay_seconds, manifest.retry_backoff_multiplier, opts.random);
const retry_at = now + @as(Instant, delay) * std.time.ns_per_s;
repo.scheduleRetry(gpa, job.id, retry_at, null, killed_error) catch |err|
std.log.err("recovery: cannot requeue {s}: {s}", .{ job.id, @errorName(err) });
}
}
return recovered;
}
// -- tests -----------------------------------------------------------------------------
const Dirs = @import("dirs.zig").Dirs;
const State = @import("state.zig").State;
test "stale and orphaned detection" {
const now: Instant = 1_000 * std.time.ns_per_s;
var j: Job = .{ .id = "job-1", .state = .running, .command = &.{"x"}, .created_at = 0, .pid = 999_999_999 };
try std.testing.expect(isStale(j, now, 30)); // no heartbeat
j.heartbeat = now - 5 * std.time.ns_per_s;
try std.testing.expect(!isStale(j, now, 30));
try std.testing.expect(!isOrphaned(j, now, 30));
j.heartbeat = now - 60 * std.time.ns_per_s;
try std.testing.expect(isStale(j, now, 30));
try std.testing.expect(isOrphaned(j, now, 30)); // pid does not exist
j.pid = std.os.linux.getpid();
try std.testing.expect(!isOrphaned(j, now, 30)); // alive: stale but not orphaned
j.pid = null;
try std.testing.expect(isOrphaned(j, now, 30));
j.state = .queued;
try std.testing.expect(!isStale(j, now, 30));
}
test "orphans are killed and requeued while retries remain" {
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 a = arena.allocator();
const base = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/zag", .{tmp.sub_path});
var dirs = try Dirs.open(io, base);
defer dirs.close(io);
const repo = Repository.init(io, &dirs);
const orphan = try repo.create(a, &.{"x"}, .{ .max_retries = 2, .retry_delay_seconds = 10 });
const no_retry = try repo.create(a, &.{"x"}, .{ .max_retries = 0 });
const healthy = try repo.create(a, &.{"x"}, .{});
for ([_][]const u8{ orphan.id, no_retry.id }) |id| {
try repo.markStarted(id, 999_999_999);
try repo.updateHeartbeat(id, timestamp.now(io) - 120 * std.time.ns_per_s);
}
try repo.markStarted(healthy.id, 999_999_999); // fresh heartbeat
try std.testing.expectEqual(@as(usize, 2), try recoverOrphanedJobs(std.testing.allocator, io, repo, .{}));
const o = (try repo.findById(a, orphan.id)).?;
try std.testing.expectEqual(State.queued, o.state);
try std.testing.expectEqual(@as(u32, 1), o.retry_count);
try std.testing.expect(o.retry_at.? > timestamp.now(io));
try std.testing.expectEqual(State.killed, (try repo.findById(a, no_retry.id)).?.state);
try std.testing.expectEqual(State.running, (try repo.findById(a, healthy.id)).?.state);
}