feat: zag CLI with all commands, human/JSON/XML output and e2e smoke test (M5)

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:47:34 +01:00
1 parent 35106d405b
commit 9d08e4d3fd
13 files changed
+2147 -68

No files matched your search

+834
View File
@@ -0,0 +1,834 @@
//! Job-related commands: run, status, describe, usage, kill, clean.
const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const cli = @import("cli.zig");
const Context = cli.Context;
const args_mod = @import("args.zig");
const output = @import("output.zig");
const Node = output.Node;
const MapBuilder = output.MapBuilder;
const jsonpretty = @import("jsonpretty.zig");
const jobjson = @import("jobjson.zig");
const config = @import("config.zig");
const dirs_mod = @import("dirs.zig");
const Dirs = dirs_mod.Dirs;
const Repository = @import("repository.zig").Repository;
const repository = @import("repository.zig");
const runner = @import("runner.zig");
const query = @import("query.zig");
const usage_mod = @import("usage.zig");
const cleanup = @import("cleanup.zig");
const duration = @import("duration.zig");
const timestamp = @import("timestamp.zig");
const proc = @import("proc.zig");
const state_mod = @import("state.zig");
const LoadLevel = @import("loadlevel.zig").LoadLevel;
const Classifier = @import("loadclass.zig").Classifier;
const Job = @import("job.zig").Job;
const Instant = @import("job.zig").Instant;
const exit_ok = cli.exit_ok;
const exit_error = cli.exit_error;
const exit_usage = cli.exit_usage;
// -- shared helpers --------------------------------------------------------------------
/// Compact JSON request payload. The writer points into `aw`, so initialise in place:
/// `var p: Payload = undefined; p.init(arena);`.
const Payload = struct {
aw: Io.Writer.Allocating,
w: jsonpretty.Writer,
fn init(self: *Payload, arena: Allocator) void {
self.aw = .init(arena);
self.w = jsonpretty.Writer.initCompact(&self.aw.writer);
}
};
fn parseCount(text: []const u8) ?u32 {
return std.fmt.parseInt(u32, text, 10) catch null;
}
fn joinCommand(arena: Allocator, command: []const []const u8) ![]const u8 {
return std.mem.join(arena, " ", command);
}
fn fmtTime(arena: Allocator, t: ?Instant) []const u8 {
const v = t orelse return "-";
const buf = arena.alloc(u8, 19) catch return "-";
return output.formatLocal(buf[0..19], v);
}
fn exitText(arena: Allocator, job: Job) []const u8 {
const c = job.exit_code orelse return "-";
return switch (c) {
.code => |n| std.fmt.allocPrint(arena, "{d}", .{n}) catch "-",
.symbol => |s| s,
};
}
fn stateStyle(s: state_mod.State) ?output.Style {
return switch (s) {
.queued => .cyan,
.running => .yellow,
.succeeded => .green,
.failed, .killed => .red,
.canceled => null,
};
}
/// Fetches a job from the daemon, or straight from disk with `--offline`.
const Fetched = union(enum) { job: Job, exit: u8 };
fn fetchJob(ctx: *Context, id: []const u8) !Fetched {
if (ctx.flag("offline")) {
var dirs = try ctx.openDirs();
defer dirs.close(ctx.io);
const repo = Repository.init(ctx.io, &dirs);
const job = (try repo.findById(ctx.arena, id)) orelse return .{ .exit = ctx.fail("Job not found: {s}", .{id}) };
return .{ .job = job };
}
var p: Payload = undefined;
p.init(ctx.arena);
try p.w.beginObject();
try p.w.field("jobId", .string, id);
try p.w.endObject();
return switch (ctx.call("get_job", p.aw.written())) {
.ok => |v| .{ .job = try jobjson.jobFromValue(ctx.arena, v) },
.exit => |c| .{ .exit = c },
};
}
fn summaryNode(arena: Allocator, jobs: []const Job) !Node {
var counts = [_]u32{0} ** 6;
for (jobs) |j| counts[@intFromEnum(j.state)] += 1;
var m = MapBuilder.init(arena);
try m.put("total", Node.num(jobs.len));
inline for (@typeInfo(state_mod.State).@"enum".fields) |f| try m.put(f.name, Node.num(counts[f.value]));
return m.done();
}
// -- run -------------------------------------------------------------------------------
pub const run_opts = [_]args_mod.Opt{
.{ .long = "tag", .short = 't', .takes_value = true },
.{ .long = "load-level", .short = 'l', .takes_value = true },
.{ .long = "max-retries", .takes_value = true },
.{ .long = "retry-delay", .takes_value = true },
.{ .long = "timeout", .takes_value = true },
};
pub const run_usage =
\\Usage: zag run [options] [--] <command> [args...]
\\
\\Start a new job. Everything from the first non-option argument on is the command,
\\run directly (no shell), so `zag run curl -u user -o file url` works as written.
\\
\\Options:
\\ -t, --tag <string> Tag for filtering jobs
\\ -l, --load-level <level> high, medium or low (default: auto-detect)
\\ --max-retries <n> Override the maximum number of retries
\\ --retry-delay <secs> Override the initial retry delay
\\ --timeout <secs> Kill the job after this many seconds
\\
\\With --offline the job is created and executed in this process, and the final state
\\is printed. Otherwise it is queued on the running service.
\\
;
pub fn cmdRun(ctx: *Context) !u8 {
const command = ctx.parsed.positionals;
if (command.len == 0) return ctx.usageError("No command specified", .{});
var load_level: ?LoadLevel = null;
if (ctx.value("load-level")) |l| load_level = LoadLevel.parse(l) orelse
return ctx.usageError("Invalid load level '{s}'. Valid values are: high, medium, low", .{l});
var max_retries: ?u32 = null;
if (ctx.value("max-retries")) |v| max_retries = parseCount(v) orelse return ctx.usageError("Invalid --max-retries '{s}'", .{v});
var retry_delay: ?u32 = null;
if (ctx.value("retry-delay")) |v| retry_delay = parseCount(v) orelse return ctx.usageError("Invalid --retry-delay '{s}'", .{v});
var timeout: ?u32 = null;
if (ctx.value("timeout")) |v| timeout = parseCount(v) orelse return ctx.usageError("Invalid --timeout '{s}'", .{v});
if (timeout) |t| if (t == 0) return ctx.usageError("--timeout must be at least 1", .{});
var job: Job = undefined;
if (ctx.flag("offline")) {
job = (try runOffline(ctx, command, load_level, max_retries, retry_delay, timeout)) orelse return exit_error;
} else {
var p: Payload = undefined;
p.init(ctx.arena);
try p.w.beginObject();
try p.w.key("command");
try p.w.beginArray();
for (command) |c| try p.w.string(c);
try p.w.endArray();
if (ctx.value("tag")) |t| try p.w.field("tag", .string, t);
if (load_level) |l| try p.w.field("loadLevel", .string, l.upper());
if (max_retries) |n| try p.w.field("maxRetries", .int, n);
if (retry_delay) |n| try p.w.field("retryDelaySeconds", .int, n);
if (timeout) |n| try p.w.field("timeoutSeconds", .int, n);
try p.w.endObject();
switch (ctx.call("run_job", p.aw.written())) {
.ok => |v| job = try jobjson.jobFromValue(ctx.arena, v),
.exit => |c| return c,
}
}
if (ctx.format == .human) {
try ctx.stdout.print("Job created: {s}\n Command: {s}\n Tag: {s}\n State: {s}\n", .{
job.id,
try joinCommand(ctx.arena, job.command),
job.tag orelse "-",
job.state.lower(),
});
} else try ctx.emit(.{ .job = job });
return exit_ok;
}
fn runOffline(ctx: *Context, command: []const []const u8, load_level: ?LoadLevel, max_retries: ?u32, retry_delay: ?u32, timeout: ?u32) !?Job {
var dirs = try ctx.openDirs();
defer dirs.close(ctx.io);
const repo = Repository.init(ctx.io, &dirs);
const cfg = ctx.configOrDefault();
const sys_dir = try config.systemConfigDir(ctx.arena, ctx.env);
const classifier = try Classifier.loadOrDefaults(ctx.arena, ctx.io, sys_dir);
const created = try repo.create(ctx.arena, command, .{
.tag = ctx.value("tag"),
.load_level = load_level orelse classifier.classify(command),
.max_retries = max_retries orelse cfg.jobs.max_retries,
.retry_delay_seconds = retry_delay orelse cfg.jobs.retry_delay_seconds,
.retry_backoff_multiplier = cfg.jobs.retry_backoff_multiplier,
.timeout_seconds = timeout,
});
var ctl: runner.Control = .{};
var rnd: std.Random.IoSource = .{ .io = ctx.io };
_ = runner.run(ctx.gpa, ctx.io, repo, created.id, &ctl, .{
.heartbeat_interval_ms = @as(u64, cfg.service.heartbeat_interval_seconds) * 1000,
.timeout_seconds = cfg.jobs.default_timeout_seconds,
.retry_codes = cfg.jobs.retry_on_exit_codes,
.random = rnd.interface(),
});
return (try repo.findById(ctx.arena, created.id)) orelse created;
}
// -- status ----------------------------------------------------------------------------
pub const status_opts = [_]args_mod.Opt{
.{ .long = "tag", .short = 't', .takes_value = true },
.{ .long = "state", .short = 's', .takes_value = true },
.{ .long = "limit", .short = 'n', .takes_value = true },
};
pub const status_usage =
\\Usage: zag status [options]
\\
\\Show the status of all jobs, newest first.
\\
\\Options:
\\ -t, --tag <string> Only jobs with this tag
\\ -s, --state <state> Only jobs in this state (queued, running, succeeded, failed, canceled, killed)
\\ -n, --limit <n> Show at most n jobs
\\
;
pub fn cmdStatus(ctx: *Context) !u8 {
var filter: query.Filter = .{ .tag = ctx.value("tag") };
if (ctx.value("state")) |s| filter.state = state_mod.State.parse(s) orelse return ctx.usageError("Unknown state '{s}'", .{s});
if (ctx.value("limit")) |l| filter.limit = std.fmt.parseInt(usize, l, 10) catch return ctx.usageError("Invalid --limit '{s}'", .{l});
var jobs: []const Job = undefined;
if (ctx.flag("offline")) {
var dirs = try ctx.openDirs();
defer dirs.close(ctx.io);
jobs = try query.selectJobs(ctx.arena, Repository.init(ctx.io, &dirs), filter);
} else {
var p: Payload = undefined;
p.init(ctx.arena);
try p.w.beginObject();
if (filter.tag) |t| try p.w.field("tag", .string, t);
if (filter.state) |s| try p.w.field("state", .string, jobjson.upperState(s));
if (filter.limit) |n| try p.w.field("limit", .int, n);
try p.w.endObject();
switch (ctx.call("get_status", p.aw.written())) {
.ok => |v| jobs = try jobjson.jobsFromValue(ctx.arena, v),
.exit => |c| return c,
}
}
if (ctx.format != .human) {
const nodes = try ctx.arena.alloc(Node, jobs.len);
for (jobs, nodes) |j, *n| n.* = .{ .job = j };
var m = MapBuilder.init(ctx.arena);
try m.put("jobs", .{ .list = nodes });
try m.put("summary", if (jobs.len == 0)
Node{ .map = &.{.{ .key = "total", .value = Node.num(0) }} }
else
try summaryNode(ctx.arena, jobs));
try ctx.emit(try m.done());
return exit_ok;
}
if (jobs.len == 0) {
try ctx.stdout.writeAll("No jobs found.\n");
return exit_ok;
}
try printStatusTable(ctx, jobs);
return exit_ok;
}
fn pad(w: *Io.Writer, text: []const u8, width: usize) !void {
try w.writeAll(text);
var n = text.len;
while (n < width) : (n += 1) try w.writeByte(' ');
}
/// Writes `text` padded to `width`, coloured as a whole when `style` is set.
fn colorCell(ctx: *Context, text: []const u8, width: usize, style: ?output.Style) !void {
if (style) |st| {
const padded = try ctx.arena.alloc(u8, @max(width, text.len));
@memset(padded, ' ');
@memcpy(padded[0..text.len], text);
try ctx.stdout.print("{f}", .{ctx.color.wrap(padded, st)});
} else try pad(ctx.stdout, text, width);
}
fn printStatusTable(ctx: *Context, jobs: []const Job) !void {
const w = ctx.stdout;
const a = ctx.arena;
var id_w: usize = 10;
var tag_w: usize = 3;
for (jobs) |j| {
id_w = @max(id_w, j.id.len);
tag_w = @max(tag_w, if (j.tag) |t| t.len else 1);
}
const sep = " ";
try pad(w, "ID", id_w);
try w.writeAll(sep);
try pad(w, "STATE", 9);
try w.writeAll(sep);
try pad(w, "LOAD", 6);
try w.writeAll(sep);
try pad(w, "TAG", tag_w);
try w.writeAll(sep);
try pad(w, "CREATED", 19);
try w.writeAll(sep);
try pad(w, "EXIT", 4);
try w.writeAll(sep);
try pad(w, "PID", 8);
try w.writeAll(sep);
try pad(w, "RETRIES", 7);
try w.writeAll(sep);
try w.writeAll("NEXT RETRY\n");
for (jobs) |j| {
try pad(w, j.id, id_w);
try w.writeAll(sep);
try colorCell(ctx, j.state.lower(), 9, stateStyle(j.state));
try w.writeAll(sep);
try pad(w, j.load_level.lower(), 6);
try w.writeAll(sep);
try pad(w, j.tag orelse "-", tag_w);
try w.writeAll(sep);
try pad(w, fmtTime(a, j.created_at), 19);
try w.writeAll(sep);
const exit_style: ?output.Style = if (j.exit_code) |c| switch (c) {
.code => |n| if (n == 0) output.Style.green else output.Style.red,
.symbol => output.Style.red,
} else null;
try colorCell(ctx, exitText(a, j), 4, exit_style);
try w.writeAll(sep);
try pad(w, if (j.pid) |p| try std.fmt.allocPrint(a, "{d}", .{p}) else "-", 8);
try w.writeAll(sep);
try pad(w, if (j.retry_count > 0) try std.fmt.allocPrint(a, "{d}", .{j.retry_count}) else "-", 7);
try w.writeAll(sep);
try w.print("{s}\n", .{if (j.retry_at) |t| fmtTime(a, t) else "-"});
}
// Summary: "Total: 3 jobs (2 succeeded, 1 failed)"
var counts = [_]u32{0} ** 6;
for (jobs) |j| counts[@intFromEnum(j.state)] += 1;
try w.print("\nTotal: {d} job{s} (", .{ jobs.len, if (jobs.len != 1) "s" else "" });
var first = true;
inline for (@typeInfo(state_mod.State).@"enum".fields) |f| {
if (counts[f.value] > 0) {
if (!first) try w.writeAll(", ");
try w.print("{d} {s}", .{ counts[f.value], f.name });
first = false;
}
}
try w.writeAll(")\n");
}
// -- describe --------------------------------------------------------------------------
pub const describe_opts = [_]args_mod.Opt{
.{ .long = "logs" },
.{ .long = "manifest" },
};
pub const describe_usage =
\\Usage: zag describe [options] <job-id>
\\
\\Show everything known about a job: state, timestamps, paths and retries.
\\
\\Options:
\\ --logs Include the last 20 lines of stdout.log and stderr.log
\\ --manifest Include the job's retry settings from its manifest
\\
;
const log_tail_lines = 20;
/// Last `n` lines of a file (reads at most the final 256 KiB). Empty if the file is missing.
fn tailLines(arena: Allocator, io: Io, dir: Io.Dir, sub_path: []const u8, n: usize) ![]const []const u8 {
var file = dir.openFile(io, sub_path, .{}) catch return &.{};
defer file.close(io);
const len = try file.length(io);
const window: u64 = 256 * 1024;
const start = if (len > window) len - window else 0;
const buf = try arena.alloc(u8, @intCast(len - start));
const got = try file.readPositionalAll(io, buf, start);
var text = buf[0..got];
if (start > 0) {
// Drop the (probably partial) first line.
if (std.mem.indexOfScalar(u8, text, '\n')) |i| text = text[i + 1 ..];
}
var lines: std.ArrayList([]const u8) = .empty;
var it = std.mem.splitScalar(u8, std.mem.trimEnd(u8, text, "\n"), '\n');
while (it.next()) |l| try lines.append(arena, l);
if (text.len == 0) return &.{};
const all = lines.items;
return if (all.len > n) all[all.len - n ..] else all;
}
pub fn cmdDescribe(ctx: *Context) !u8 {
const id = ctx.positional(0) orelse return ctx.usageError("Job ID is required", .{});
const job = switch (try fetchJob(ctx, id)) {
.job => |j| j,
.exit => |c| return c,
};
var dirs = try ctx.openDirs();
defer dirs.close(ctx.io);
const repo = Repository.init(ctx.io, &dirs);
const a = ctx.arena;
const manifest: ?@import("job.zig").Manifest = if (ctx.flag("manifest")) try repo.loadManifest(a, id) else null;
var job_dir = try dirs.openJob(ctx.io, id);
defer job_dir.close(ctx.io);
const include_logs = ctx.flag("logs");
const out_lines = if (include_logs) try tailLines(a, ctx.io, job_dir, "logs/stdout.log", log_tail_lines) else &[_][]const u8{};
const err_lines = if (include_logs) try tailLines(a, ctx.io, job_dir, "logs/stderr.log", log_tail_lines) else &[_][]const u8{};
const work_path = try dirs.jobPath(a, id, "work");
const logs_path = try dirs.jobPath(a, id, "logs");
if (ctx.format == .human) {
const w = ctx.stdout;
const now = timestamp.now(ctx.io);
try w.print("Job: {s}\n", .{job.id});
try w.writeAll("=" ** 80 ++ "\n");
try w.print("State: {s}\n", .{job.state.lower()});
if (job.tag) |t| try w.print("Tag: {s}\n", .{t});
try w.print("Command: {s}\n", .{try joinCommand(a, job.command)});
try w.writeAll("\nTimestamps:\n");
try w.print(" Created: {s}\n Started: {s}\n Finished: {s}\n", .{ fmtTime(a, job.created_at), fmtTime(a, job.started_at), fmtTime(a, job.finished_at) });
try w.writeAll("\nExecution:\n");
try w.print(" PID: {s}\n", .{if (job.pid) |p| try std.fmt.allocPrint(a, "{d}", .{p}) else "-"});
try w.print(" Exit Code: {s}\n", .{exitText(a, job)});
if (job.heartbeat) |h| {
var rb: [32]u8 = undefined;
try w.print(" Heartbeat: {s} ({s})\n", .{ fmtTime(a, h), output.relativeTime(&rb, @intCast(@divFloor(now - h, std.time.ns_per_s))) });
}
if (job.err) |e| try w.print(" Error: {s}\n", .{e});
if (job.retry_count > 0 or job.retry_at != null) {
try w.print("\nRetry:\n Attempts: {d}\n", .{job.retry_count});
if (job.retry_at) |t| try w.print(" Next Retry: {s}\n", .{fmtTime(a, t)});
}
try w.print("\nFiles:\n Work Dir: {s}\n Logs Dir: {s}\n", .{ work_path, logs_path });
if (manifest) |m| {
try w.print("\nManifest:\n Max Retries: {d}\n Retry Delay: {d}s\n Backoff: {d:.1}x\n", .{ m.max_retries, m.retry_delay_seconds, m.retry_backoff_multiplier });
if (m.timeout_seconds) |t| try w.print(" Timeout: {d}s\n", .{t});
}
if (include_logs) {
for ([_]struct { name: []const u8, lines: []const []const u8 }{
.{ .name = "stdout.log", .lines = out_lines },
.{ .name = "stderr.log", .lines = err_lines },
}) |l| {
if (l.lines.len == 0) continue;
try w.print("\n--- {s} (last {d} lines) ---\n", .{ l.name, l.lines.len });
for (l.lines) |line| try w.print("{s}\n", .{line});
}
}
return exit_ok;
}
var m = MapBuilder.init(a);
try m.put("id", Node.str(job.id));
try m.put("state", Node.str(job.state.lower()));
try m.put("tag", Node.optStr(job.tag));
try m.put("command", try stringList(a, job.command));
try m.put("createdAt", try instantNode(a, job.created_at));
try m.put("startedAt", try instantNode(a, job.started_at));
try m.put("finishedAt", try instantNode(a, job.finished_at));
try m.put("pid", if (job.pid) |p| Node{ .int = p } else .null);
try m.put("exitCode", if (job.exit_code) |c| switch (c) {
.code => |n| Node{ .int = n },
.symbol => |s| Node.str(s),
} else .null);
try m.put("error", Node.optStr(job.err));
try m.put("heartbeat", try instantNode(a, job.heartbeat));
try m.put("retryCount", Node.num(job.retry_count));
try m.put("retryAt", try instantNode(a, job.retry_at));
var paths = MapBuilder.init(a);
try paths.put("jobDir", Node.str(try dirs.jobPath(a, id, "")));
try paths.put("workDir", Node.str(work_path));
try paths.put("logsDir", Node.str(logs_path));
try m.put("paths", try paths.done());
if (manifest) |mf| {
var mm = MapBuilder.init(a);
try mm.put("maxRetries", Node.num(mf.max_retries));
try mm.put("retryDelaySeconds", Node.num(mf.retry_delay_seconds));
try mm.put("retryBackoffMultiplier", .{ .float = mf.retry_backoff_multiplier });
if (mf.timeout_seconds) |t| try mm.put("timeoutSeconds", Node.num(t));
try m.put("manifest", try mm.done());
}
if (include_logs) {
var lm = MapBuilder.init(a);
try lm.put("stdout", Node.str(try std.mem.join(a, "\n", out_lines)));
try lm.put("stderr", Node.str(try std.mem.join(a, "\n", err_lines)));
try m.put("logs", try lm.done());
}
try ctx.emit(try m.done());
return exit_ok;
}
fn stringList(arena: Allocator, items: []const []const u8) !Node {
const nodes = try arena.alloc(Node, items.len);
for (items, nodes) |s, *n| n.* = Node.str(s);
return .{ .list = nodes };
}
fn instantNode(arena: Allocator, t: ?Instant) !Node {
const v = t orelse return .null;
const buf = try arena.alloc(u8, timestamp.max_len);
return Node.str(timestamp.format(buf[0..timestamp.max_len], v));
}
// -- usage -----------------------------------------------------------------------------
pub const usage_opts = [_]args_mod.Opt{
.{ .long = "limit", .short = 'n', .takes_value = true },
.{ .long = "csv" },
.{ .long = "summary" },
};
pub const usage_usage =
\\Usage: zag usage [options] <job-id>
\\
\\Show CPU, memory and disk usage sampled while a job ran.
\\
\\Options:
\\ -n, --limit <n> Show the last n samples (default: 50)
\\ --csv Print the raw usage.csv
\\ --summary Show summary statistics only
\\
;
fn bytesStr(arena: Allocator, bytes: f64) ![]const u8 {
const buf = try arena.alloc(u8, 32);
return output.formatBytes(buf, @intFromFloat(@max(bytes, 0)));
}
fn statNode(arena: Allocator, s: usage_mod.Stat, comptime keys: [3][]const u8, as_int: bool) !Node {
var m = MapBuilder.init(arena);
const vals = [3]f64{ s.avg, s.max, s.min };
inline for (keys, 0..) |k, i| {
if (k.len == 0) continue;
try m.put(k, if (as_int) Node{ .int = @intFromFloat(vals[i]) } else Node{ .float = vals[i] });
}
return m.done();
}
pub fn cmdUsage(ctx: *Context) !u8 {
const id = ctx.positional(0) orelse return ctx.usageError("Job ID is required", .{});
var limit: usize = 50;
if (ctx.value("limit")) |l| limit = std.fmt.parseInt(usize, l, 10) catch return ctx.usageError("Invalid --limit '{s}'", .{l});
var dirs = try ctx.openDirs();
defer dirs.close(ctx.io);
const repo = Repository.init(ctx.io, &dirs);
const a = ctx.arena;
if ((try repo.findById(a, id)) == null) return ctx.fail("Job not found: {s}", .{id});
var job_dir = try dirs.openJob(ctx.io, id);
defer job_dir.close(ctx.io);
const csv = job_dir.readFileAlloc(ctx.io, usage_mod.csv_file, a, .limited(64 * 1024 * 1024)) catch |err| switch (err) {
error.FileNotFound => return ctx.fail("No usage data available for job: {s}", .{id}),
else => |e| return e,
};
var samples = try usage_mod.parseCsv(a, csv);
if (samples.len == 0) return ctx.fail("No usage data available for job: {s}", .{id});
if (ctx.flag("csv")) {
try ctx.stdout.writeAll(csv);
return exit_ok;
}
if (limit > 0 and samples.len > limit) samples = samples[samples.len - limit ..];
const summary = (try usage_mod.summarize(a, samples)).?;
const summary_only = ctx.flag("summary");
if (ctx.format == .human) {
const w = ctx.stdout;
var b1: [32]u8 = undefined;
var b2: [32]u8 = undefined;
var b3: [32]u8 = undefined;
try w.print("Resource Usage for Job: {s}\n", .{id});
try w.writeAll("=" ** 80 ++ "\n\n");
try w.print("Summary ({d} samples):\n", .{summary.sample_count});
try w.print(" CPU: avg={d:.1}% max={d:.1}% min={d:.1}%\n", .{ summary.cpu.avg, summary.cpu.max, summary.cpu.min });
try w.print(" Memory: avg={s} max={s} min={s}\n", .{
output.formatBytes(&b1, @intFromFloat(summary.memory.avg)),
output.formatBytes(&b2, @intFromFloat(summary.memory.max)),
output.formatBytes(&b3, @intFromFloat(summary.memory.min)),
});
try w.print(" Disk: max={s}\n", .{output.formatBytes(&b1, summary.disk_max)});
const has_gpu = summary.gpu != null;
if (summary.gpu) |g| {
try w.print(" GPU: avg={d:.1}% max={d:.1}%\n", .{ g.avg, g.max });
if (summary.gpu_memory) |gm| try w.print(" GPU Mem: max={s}\n", .{output.formatBytes(&b1, @intFromFloat(gm.max))});
}
if (!summary_only) {
try w.writeAll("\nRecent Samples:\n");
try w.print("{s: <25} {s: >7} {s: >12} {s: >12}", .{ "TIMESTAMP", "CPU %", "MEMORY", "DISK" });
if (has_gpu) try w.print(" {s: >7} {s: >12}", .{ "GPU %", "GPU MEM" });
try w.writeByte('\n');
for (samples) |s| {
try w.print("{s: <25} {d: >7.1} {s: >12} {s: >12}", .{
fmtTime(a, s.at),
s.cpu_percent,
output.formatBytes(&b1, s.memory_bytes),
output.formatBytes(&b2, s.disk_bytes),
});
if (has_gpu) if (s.gpu_percent) |g| {
try w.print(" {d: >7.1} {s: >12}", .{ g, output.formatBytes(&b3, s.gpu_memory_bytes orelse 0) });
};
try w.writeByte('\n');
}
}
return exit_ok;
}
var m = MapBuilder.init(a);
try m.put("jobId", Node.str(id));
var sm = MapBuilder.init(a);
try sm.put("sampleCount", Node.num(summary.sample_count));
try sm.put("cpu", try statNode(a, summary.cpu, .{ "avg", "max", "min" }, false));
try sm.put("memory", try statNode(a, summary.memory, .{ "avgBytes", "maxBytes", "minBytes" }, true));
try sm.put("disk", Node{ .map = &.{.{ .key = "maxBytes", .value = Node.num(summary.disk_max) }} });
if (summary.gpu) |g| try sm.put("gpu", try statNode(a, g, .{ "avg", "max", "" }, false));
if (summary.gpu_memory) |gm| try sm.put("gpuMemory", try statNode(a, gm, .{ "", "maxBytes", "" }, true));
try m.put("summary", try sm.done());
if (!summary_only) {
const nodes = try a.alloc(Node, samples.len);
for (samples, nodes) |s, *n| {
var sample = MapBuilder.init(a);
try sample.put("timestamp", try instantNode(a, s.at));
try sample.put("cpuPercent", .{ .float = s.cpu_percent });
try sample.put("memoryBytes", Node.num(s.memory_bytes));
try sample.put("diskBytes", Node.num(s.disk_bytes));
if (s.gpu_percent) |g| try sample.put("gpuPercent", .{ .float = g });
if (s.gpu_memory_bytes) |g| try sample.put("gpuMemoryBytes", Node.num(g));
n.* = try sample.done();
}
try m.put("samples", .{ .list = nodes });
}
try ctx.emit(try m.done());
return exit_ok;
}
// -- kill ------------------------------------------------------------------------------
pub const kill_opts = [_]args_mod.Opt{
.{ .long = "force", .short = 'f' },
.{ .long = "quiet", .short = 'q' },
};
pub const kill_usage =
\\Usage: zag kill [options] <job-id>
\\
\\Stop a job. A running job's whole process group gets SIGTERM (SIGKILL after a grace
\\period); a queued job is canceled before it ever starts. Either way it ends canceled.
\\
\\Options:
\\ -f, --force Send SIGKILL immediately
\\ -q, --quiet No output on success
\\
;
pub fn cmdKill(ctx: *Context) !u8 {
const id = ctx.positional(0) orelse return ctx.usageError("Job ID is required", .{});
const force = ctx.flag("force");
const job = switch (try fetchJob(ctx, id)) {
.job => |j| j,
.exit => |c| return c,
};
const previous = job.state;
if (previous != .running and previous != .queued)
return ctx.fail("Job is not running (state: {s})", .{previous.lower()});
if (ctx.flag("offline")) {
var dirs = try ctx.openDirs();
defer dirs.close(ctx.io);
const repo = Repository.init(ctx.io, &dirs);
if (previous == .running) if (job.pid) |p| if (p > 0) proc.signalTree(@intCast(p), if (force) .kill else .term);
repo.markCanceled(id) catch |err| switch (err) {
error.InvalidTransition => return ctx.fail("Job {s} changed state while being killed", .{id}),
else => |e| return e,
};
} else {
var p: Payload = undefined;
p.init(ctx.arena);
try p.w.beginObject();
try p.w.field("jobId", .string, id);
try p.w.field("force", .boolean, force);
try p.w.endObject();
switch (ctx.call("kill_job", p.aw.written())) {
.ok => {},
.exit => |c| return c,
}
}
if (ctx.flag("quiet")) return exit_ok;
if (ctx.format == .human) {
try ctx.stdout.print("Job {s} killed\n Previous state: {s}\n New state: canceled\n", .{ id, previous.lower() });
} else {
var m = MapBuilder.init(ctx.arena);
try m.put("id", Node.str(id));
try m.put("previousState", Node.str(previous.lower()));
try m.put("newState", Node.str("canceled"));
try m.put("message", Node.str("Job was killed"));
try ctx.emit(try m.done());
}
return exit_ok;
}
// -- clean -----------------------------------------------------------------------------
pub const clean_opts = [_]args_mod.Opt{
.{ .long = "all" },
.{ .long = "older-than", .takes_value = true },
.{ .long = "include-failed" },
.{ .long = "dry-run" },
.{ .long = "job-id", .takes_value = true },
};
pub const clean_usage =
\\Usage: zag clean [options]
\\
\\Remove finished jobs. With none of --all, --older-than or --job-id, nothing is removed.
\\Running and queued jobs are never touched.
\\
\\Options:
\\ --all Remove every finished job regardless of age
\\ --older-than <dur> Remove jobs finished longer ago than this (e.g. 24h, 7d, 2w)
\\ --include-failed Also remove failed jobs
\\ --dry-run Show what would be removed without removing it
\\ --job-id <id> Remove one specific job
\\
;
pub fn cmdClean(ctx: *Context) !u8 {
var policy: cleanup.ManualPolicy = .{
.all = ctx.flag("all"),
.include_failed = ctx.flag("include-failed"),
.job_id = ctx.value("job-id"),
};
if (ctx.value("older-than")) |s| policy.older_than_seconds = duration.parseSeconds(s) catch
return ctx.usageError("Invalid duration '{s}' (use e.g. 30m, 24h, 7d, 2w)", .{s});
const dry_run = ctx.flag("dry-run");
const a = ctx.arena;
const now = timestamp.now(ctx.io);
var plan: []const cleanup.Candidate = undefined;
if (ctx.flag("offline")) {
var dirs = try ctx.openDirs();
defer dirs.close(ctx.io);
const repo = Repository.init(ctx.io, &dirs);
plan = cleanup.planManual(a, ctx.io, repo, policy, now) catch |err| switch (err) {
error.JobNotFound => return ctx.fail("Job not found: {s}", .{policy.job_id.?}),
error.NotCleanable => return ctx.fail("Cannot clean job {s}: it is running, queued, or failed (use --include-failed)", .{policy.job_id.?}),
else => |e| return e,
};
if (!dry_run) _ = cleanup.execute(repo, plan);
} else {
var p: Payload = undefined;
p.init(a);
try p.w.beginObject();
try p.w.field("all", .boolean, policy.all);
try p.w.field("includeFailed", .boolean, policy.include_failed);
try p.w.field("dryRun", .boolean, dry_run);
if (ctx.value("older-than")) |s| try p.w.field("olderThan", .string, s);
if (policy.job_id) |j| try p.w.field("jobId", .string, j);
try p.w.endObject();
const reply = switch (ctx.call("clean_jobs", p.aw.written())) {
.ok => |v| v,
.exit => |c| return c,
};
const items = switch (reply.object.get("cleaned") orelse .null) {
.array => |arr| arr.items,
else => &.{},
};
const list = try a.alloc(cleanup.Candidate, items.len);
for (items, list) |item, *slot| {
const obj = item.object;
slot.* = .{
.job = try jobjson.jobFromValue(a, obj.get("job").?),
.size_bytes = switch (obj.get("sizeBytes") orelse .null) {
.integer => |n| @intCast(n),
else => 0,
},
};
}
plan = list;
}
var total: u64 = 0;
for (plan) |c| total += c.size_bytes;
if (ctx.format != .human) {
const nodes = try a.alloc(Node, plan.len);
for (plan, nodes) |c, *n| {
var m = MapBuilder.init(a);
try m.put("id", Node.str(c.job.id));
try m.put("state", Node.str(c.job.state.lower()));
try m.put("ageHours", Node{ .int = @intCast(@divFloor(now - cleanup.ageBase(c.job), 3600 * std.time.ns_per_s)) });
try m.put("sizeBytes", Node.num(c.size_bytes));
n.* = try m.done();
}
var m = MapBuilder.init(a);
try m.put("cleaned", .{ .list = nodes });
try m.put("count", Node.num(plan.len));
try m.put("bytesFreed", Node.num(total));
try m.put("dryRun", .{ .boolean = dry_run });
try ctx.emit(try m.done());
return exit_ok;
}
const w = ctx.stdout;
const prefix = if (dry_run) "Would clean" else "Cleaned";
if (plan.len == 0) {
try w.print("{s} 0 jobs.\n", .{prefix});
return exit_ok;
}
try w.print("{s} {d} job{s}:\n", .{ prefix, plan.len, if (plan.len != 1) "s" else "" });
var b: [32]u8 = undefined;
var ab: [32]u8 = undefined;
for (plan) |c| {
try w.print(" {s} ({s}, {s})", .{ c.job.id, c.job.state.lower(), output.formatAge(&ab, @intCast(@divFloor(now - cleanup.ageBase(c.job), std.time.ns_per_s))) });
if (dry_run) try w.print(" - {s}", .{output.formatSize(&b, c.size_bytes)});
try w.writeByte('\n');
}
try w.print("\n{s}: {s}\n", .{ if (dry_run) "Would free" else "Disk space freed", output.formatSize(&b, total) });
return exit_ok;
}