From 9d08e4d3fdba34136e9ca26b6bbdabddf3d97b5a Mon Sep 17 00:00:00 2001 From: Daniel Samson Date: Sat, 17 Oct 2026 13:47:34 +0100 Subject: [PATCH] feat: zag CLI with all commands, human/JSON/XML output and e2e smoke test (M5) Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 8 + build.zig | 5 + src/cli.zig | 425 +++++++++++++++++++++++ src/cli_admin.zig | 699 +++++++++++++++++++++++++++++++++++++ src/cli_jobs.zig | 834 +++++++++++++++++++++++++++++++++++++++++++++ src/jobjson.zig | 6 +- src/jsonpretty.zig | 6 +- src/logging.zig | 50 +++ src/main.zig | 87 ++--- src/output.zig | 2 +- src/repository.zig | 1 + src/root.zig | 2 + test/e2e.sh | 90 +++++ 13 files changed, 2147 insertions(+), 68 deletions(-) create mode 100644 src/cli.zig create mode 100644 src/cli_admin.zig create mode 100644 src/cli_jobs.zig create mode 100644 src/logging.zig create mode 100755 test/e2e.sh diff --git a/AGENTS.md b/AGENTS.md index 52e3713..9ae5e69 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,3 +55,11 @@ Guidance for AI coding agents working in `zag`, the Zig port of the binary is static and does not depend on the host's crt files (the host linker fails on newer gcc `.sframe` sections). - Width/fill on a signed integer prints a leading `+` (`{d:0>2}` of an `i64`); cast to unsigned first. +| `src/args.zig` | Option parser (long/short, `=`/separate values, `--`, stop-at-positional) | +| `src/query.zig` | Job listing filter shared by the daemon and offline CLI | +| `src/logging.zig` | Timestamped stderr logging with a runtime level | +| `src/cli.zig` | CLI dispatch, shared `Context`, help text | +| `src/cli_jobs.zig` | `run`, `status`, `describe`, `usage`, `kill`, `clean` | +| `src/cli_admin.zig` | `service ...`, `config ...`, `autocompletion` | +| `src/main.zig` | Binary entry point | +| `test/e2e.sh` | End-to-end smoke test (`zig build e2e`) | diff --git a/build.zig b/build.zig index 57ee82d..ed93895 100644 --- a/build.zig +++ b/build.zig @@ -39,6 +39,11 @@ pub fn build(b: *std.Build) void { run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| run_cmd.addArgs(args); + const e2e_step = b.step("e2e", "Run the end-to-end smoke test against the built binary"); + const e2e = b.addSystemCommand(&.{ "bash", "test/e2e.sh" }); + e2e.addArtifactArg(exe); + e2e_step.dependOn(&e2e.step); + const test_step = b.step("test", "Run tests"); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mod })).step); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = exe.root_module })).step); diff --git a/src/cli.zig b/src/cli.zig new file mode 100644 index 0000000..c8380b0 --- /dev/null +++ b/src/cli.zig @@ -0,0 +1,425 @@ +//! The `zag` command line: argument dispatch, shared context and help text. +//! Command implementations live in `cli_jobs.zig` and `cli_admin.zig`. +const std = @import("std"); +const Io = std.Io; +const Allocator = std.mem.Allocator; +const Environ = std.process.Environ; +const args_mod = @import("args.zig"); +const config = @import("config.zig"); +const dirs_mod = @import("dirs.zig"); +const ipc = @import("ipc.zig"); +const output = @import("output.zig"); +const jsonpretty = @import("jsonpretty.zig"); +const jobs_cmds = @import("cli_jobs.zig"); +const admin_cmds = @import("cli_admin.zig"); + +pub const exit_ok: u8 = 0; +pub const exit_error: u8 = 1; +pub const exit_usage: u8 = 2; + +pub const Context = struct { + gpa: Allocator, + arena: Allocator, + io: Io, + env: *const Environ.Map, + stdout: *Io.Writer, + stderr: *Io.Writer, + /// Path of the running binary (used to re-exec the daemon). + exe_path: []const u8, + format: output.Format = .human, + color: output.Color = .{}, + parsed: args_mod.Parsed = .{}, + /// Name of the subcommand being run, e.g. `status` or `service start`. + command: []const u8 = "", + + config_loaded: bool = false, + config_value: config.Config = .{}, + config_error: ?config.Error = null, + config_diag: config.Diagnostic = .{}, + + pub fn flag(self: *const Context, name: []const u8) bool { + return self.parsed.flag(name); + } + + pub fn value(self: *const Context, name: []const u8) ?[]const u8 { + return self.parsed.value(name); + } + + pub fn positional(self: *const Context, i: usize) ?[]const u8 { + return if (i < self.parsed.positionals.len) self.parsed.positionals[i] else null; + } + + /// Prints an error in the selected output format; returns `exit_error`. + pub fn fail(self: *Context, comptime fmt: []const u8, fargs: anytype) u8 { + return self.failWithCause(null, fmt, fargs); + } + + pub fn failWithCause(self: *Context, cause: ?[]const u8, comptime fmt: []const u8, fargs: anytype) u8 { + const msg = std.fmt.allocPrint(self.arena, fmt, fargs) catch "out of memory"; + output.renderError(self.stderr, self.format, self.color, msg, cause) catch {}; + return exit_error; + } + + /// Prints an error and returns the usage exit code. + pub fn usageError(self: *Context, comptime fmt: []const u8, fargs: anytype) u8 { + _ = self.fail(fmt, fargs); + return exit_usage; + } + + // -- configuration ------------------------------------------------------------- + + fn loadConfigOnce(self: *Context) void { + if (self.config_loaded) return; + self.config_loaded = true; + if (config.load(self.arena, self.io, self.env, .{ .explicit_path = self.value("config") }, &self.config_diag)) |c| { + self.config_value = c; + } else |err| { + self.config_error = err; + } + } + + /// The effective configuration, or the error that stopped it loading. + pub fn loadConfig(self: *Context) config.Error!config.Config { + self.loadConfigOnce(); + if (self.config_error) |e| return e; + return self.config_value; + } + + /// Like `config`, but a broken file falls back to the defaults (client commands should keep + /// working when the config is wrong; `zag config validate` reports the problem). + pub fn configOrDefault(self: *Context) config.Config { + return self.loadConfig() catch .{}; + } + + pub fn describeConfigError(self: *Context) u8 { + const err = self.config_error orelse return exit_ok; + const d = self.config_diag; + if (err == error.ParseFailed) return self.fail("Failed to parse configuration file {s} at line {d}", .{ d.path, d.line }); + if (d.key.len > 0) return self.fail("Invalid configuration: '{s}' in [{s}] ({s})", .{ d.key, d.section, @errorName(err) }); + return self.fail("Failed to load configuration: {s}", .{@errorName(err)}); + } + + /// `--barn-dir`, else `storage.base_dir`. + pub fn baseDir(self: *Context) []const u8 { + if (self.value("barn-dir")) |d| return d; + return self.configOrDefault().storage.base_dir; + } + + pub fn socketPath(self: *Context) []const u8 { + if (self.value("barn-dir")) |d| return std.fmt.allocPrint(self.arena, "{s}/{s}", .{ d, dirs_mod.socket_file }) catch d; + const cfg = self.configOrDefault(); + return cfg.ipcSocketPath(self.arena) catch "/tmp/zag/zag.sock"; + } + + pub fn openDirs(self: *Context) !dirs_mod.Dirs { + return dirs_mod.Dirs.open(self.io, self.baseDir()); + } + + // -- service access ------------------------------------------------------------ + + pub const CallResult = union(enum) { + ok: std.json.Value, + /// An error was already printed; the value is the exit code. + exit: u8, + }; + + /// Sends a request to the daemon. Failures are printed in the selected format. + pub fn call(self: *Context, request_type: []const u8, payload_json: ?[]const u8) CallResult { + const reply = ipc.call(self.io, self.arena, self.socketPath(), request_type, payload_json) catch |err| switch (err) { + error.ServiceNotRunning => return .{ .exit = self.fail("Service not running. Start with: zag service start\nOr use --offline to run without the service.", .{}) }, + error.ConnectionFailed => return .{ .exit = self.fail("Could not talk to the zag service (connection failed)", .{}) }, + error.BadResponse => return .{ .exit = self.fail("The zag service sent an invalid response", .{}) }, + error.OutOfMemory => return .{ .exit = self.fail("Out of memory", .{}) }, + }; + return switch (reply) { + .ok => |v| .{ .ok = v }, + .err => |e| .{ .exit = self.remoteFail(e) }, + }; + } + + /// Maps a daemon error to a message. + pub fn remoteFail(self: *Context, e: ipc.RemoteError) u8 { + if (std.mem.eql(u8, e.code, "NOT_FOUND") or std.mem.eql(u8, e.code, "INVALID_STATE") or std.mem.eql(u8, e.code, "INVALID_REQUEST")) + return self.fail("{s}", .{e.message}); + return self.fail("IPC error: {s}", .{e.message}); + } + + pub fn emit(self: *Context, node: output.Node) !void { + try output.render(self.stdout, self.format, node); + } +}; + +// -- option tables --------------------------------------------------------------------- + +const global_opts = [_]args_mod.Opt{ + .{ .long = "output", .short = 'o', .takes_value = true }, + .{ .long = "config", .takes_value = true }, + .{ .long = "offline" }, + .{ .long = "barn-dir", .takes_value = true }, + .{ .long = "help", .short = 'h' }, + .{ .long = "version", .short = 'V' }, +}; + +pub const Command = struct { + name: []const u8, + /// Set for commands with subcommands (`service`, `config`). + sub: ?[]const u8 = null, + summary: []const u8, + usage: []const u8, + opts: []const args_mod.Opt = &.{}, + stop_at_positional: bool = false, + run: *const fn (*Context) anyerror!u8, +}; + +const commands = [_]Command{ + .{ .name = "run", .summary = "Start a new job", .usage = jobs_cmds.run_usage, .opts = &jobs_cmds.run_opts, .stop_at_positional = true, .run = jobs_cmds.cmdRun }, + .{ .name = "status", .summary = "Show status of all jobs", .usage = jobs_cmds.status_usage, .opts = &jobs_cmds.status_opts, .run = jobs_cmds.cmdStatus }, + .{ .name = "describe", .summary = "Show detailed job information", .usage = jobs_cmds.describe_usage, .opts = &jobs_cmds.describe_opts, .run = jobs_cmds.cmdDescribe }, + .{ .name = "usage", .summary = "Show resource usage for a job", .usage = jobs_cmds.usage_usage, .opts = &jobs_cmds.usage_opts, .run = jobs_cmds.cmdUsage }, + .{ .name = "kill", .summary = "Stop a running job", .usage = jobs_cmds.kill_usage, .opts = &jobs_cmds.kill_opts, .run = jobs_cmds.cmdKill }, + .{ .name = "clean", .summary = "Remove completed jobs", .usage = jobs_cmds.clean_usage, .opts = &jobs_cmds.clean_opts, .run = jobs_cmds.cmdClean }, + .{ .name = "service", .sub = "start", .summary = "Start the zag service", .usage = admin_cmds.service_start_usage, .opts = &admin_cmds.service_start_opts, .run = admin_cmds.cmdServiceStart }, + .{ .name = "service", .sub = "stop", .summary = "Stop the zag service", .usage = admin_cmds.service_stop_usage, .opts = &admin_cmds.service_stop_opts, .run = admin_cmds.cmdServiceStop }, + .{ .name = "service", .sub = "restart", .summary = "Restart the zag service", .usage = admin_cmds.service_restart_usage, .opts = &admin_cmds.service_restart_opts, .run = admin_cmds.cmdServiceRestart }, + .{ .name = "service", .sub = "reload", .summary = "Reload configuration without stopping jobs", .usage = admin_cmds.service_reload_usage, .run = admin_cmds.cmdServiceReload }, + .{ .name = "service", .sub = "status", .summary = "Show service status", .usage = admin_cmds.service_status_usage, .run = admin_cmds.cmdServiceStatus }, + .{ .name = "service", .sub = "logs", .summary = "Show service logs", .usage = admin_cmds.service_logs_usage, .opts = &admin_cmds.service_logs_opts, .run = admin_cmds.cmdServiceLogs }, + .{ .name = "config", .sub = "show", .summary = "Show effective configuration", .usage = admin_cmds.config_show_usage, .opts = &admin_cmds.config_show_opts, .run = admin_cmds.cmdConfigShow }, + .{ .name = "config", .sub = "validate", .summary = "Validate a configuration file", .usage = admin_cmds.config_validate_usage, .opts = &admin_cmds.config_validate_opts, .run = admin_cmds.cmdConfigValidate }, + .{ .name = "config", .sub = "init", .summary = "Create a default configuration file", .usage = admin_cmds.config_init_usage, .opts = &admin_cmds.config_init_opts, .run = admin_cmds.cmdConfigInit }, + .{ .name = "config", .sub = "install", .summary = "Install default configuration files", .usage = admin_cmds.config_install_usage, .opts = &admin_cmds.config_install_opts, .run = admin_cmds.cmdConfigInstall }, + .{ .name = "autocompletion", .summary = "Generate shell autocompletion scripts", .usage = admin_cmds.autocompletion_usage, .opts = &admin_cmds.autocompletion_opts, .run = admin_cmds.cmdAutocompletion }, +}; + +const root_help = + \\zag - cross-platform job daemon for media processing + \\ + \\Usage: zag [options] [command options] + \\ + \\Commands: + \\ run Start a new job + \\ status Show status of all jobs + \\ describe Show detailed job information + \\ usage Show resource usage for a job + \\ kill Stop a running job + \\ clean Remove completed jobs + \\ service Manage the zag service (start|stop|restart|reload|status|logs) + \\ config Configuration management (show|validate|init|install) + \\ autocompletion Generate shell autocompletion scripts + \\ + \\Global options: + \\ -o, --output Output format: human, json, xml (default: human) + \\ --config Path to a configuration file + \\ --offline Run without the service (same code, in this process) + \\ --barn-dir Data directory (overrides storage.base_dir) + \\ -h, --help Show help (also per command) + \\ -V, --version Show the version + \\ +; + +const service_help = + \\Usage: zag service + \\ + \\ start Start the zag service + \\ stop Stop the zag service + \\ restart Restart the zag service + \\ reload Reload configuration without stopping jobs + \\ status Show service status + \\ logs Show service logs + \\ +; + +const config_help = + \\Usage: zag config + \\ + \\ show Show effective configuration + \\ validate Validate a configuration file + \\ init Create a default configuration file + \\ install Install default configuration files + \\ +; + +/// Number of leading tokens that are global options (and their values). +fn leadingOptionCount(argv: []const []const u8) usize { + var i: usize = 0; + while (i < argv.len and argv[i].len > 1 and argv[i][0] == '-') : (i += 1) { + const a = argv[i]; + if (std.mem.eql(u8, a, "--")) break; + var takes_value = false; + if (std.mem.startsWith(u8, a, "--")) { + if (std.mem.indexOfScalar(u8, a, '=') == null) { + for (global_opts) |o| if (std.mem.eql(u8, o.long, a[2..])) { + takes_value = o.takes_value; + }; + } + } else if (a.len == 2) { + for (global_opts) |o| if (o.short != null and o.short.? == a[1]) { + takes_value = o.takes_value; + }; + } + if (takes_value) i += 1; + } + return @min(i, argv.len); +} + +fn find(name: []const u8, sub: ?[]const u8) ?*const Command { + for (&commands) |*c| { + if (!std.mem.eql(u8, c.name, name)) continue; + if (c.sub == null and sub == null) return c; + if (c.sub != null and sub != null and std.mem.eql(u8, c.sub.?, sub.?)) return c; + } + return null; +} + +fn hasSubcommands(name: []const u8) bool { + return std.mem.eql(u8, name, "service") or std.mem.eql(u8, name, "config"); +} + +/// Runs the CLI and returns the process exit code. +pub fn run( + gpa: Allocator, + io: Io, + env: *const Environ.Map, + stdout: *Io.Writer, + stderr: *Io.Writer, + exe_path: []const u8, + argv: []const []const u8, + stdout_is_tty: bool, +) u8 { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + + var ctx: Context = .{ + .gpa = gpa, + .arena = arena, + .io = io, + .env = env, + .stdout = stdout, + .stderr = stderr, + .exe_path = exe_path, + }; + return dispatch(&ctx, argv, stdout_is_tty) catch |err| { + _ = ctx.fail("Unexpected error: {s}", .{@errorName(err)}); + return exit_error; + }; +} + +fn dispatch(ctx: *Context, argv: []const []const u8, stdout_is_tty: bool) !u8 { + // Global options may precede the command: `zag -o json status`. + const cmd_index = leadingOptionCount(argv); + const prefix = argv[0..@min(cmd_index, argv.len)]; + const rest = argv[@min(cmd_index, argv.len)..]; + + var diag: args_mod.Diagnostic = .{}; + const pre = args_mod.parse(ctx.arena, prefix, &global_opts, .{}, &diag) catch |err| return ctx.usageError("{s}: {s}", .{ @errorName(err), diag.token }); + ctx.parsed = pre; + + if (rest.len == 0) { + if (pre.flag("version")) return printVersion(ctx); + try ctx.stdout.writeAll(root_help); + return exit_ok; + } + if (pre.flag("version")) return printVersion(ctx); + + const name = rest[0]; + var sub: ?[]const u8 = null; + var cmd_args = rest[1..]; + + if (std.mem.eql(u8, name, "help")) { + try ctx.stdout.writeAll(root_help); + return exit_ok; + } + if (hasSubcommands(name)) { + const help_text = if (std.mem.eql(u8, name, "service")) service_help else config_help; + if (cmd_args.len == 0 or std.mem.eql(u8, cmd_args[0], "--help") or std.mem.eql(u8, cmd_args[0], "-h")) { + try ctx.stdout.writeAll(help_text); + return exit_ok; + } + sub = cmd_args[0]; + cmd_args = cmd_args[1..]; + } + + const cmd = find(name, sub) orelse { + if (sub) |s| return ctx.usageError("Unknown subcommand '{s}' for '{s}'\n{s}", .{ s, name, if (std.mem.eql(u8, name, "service")) service_help else config_help }); + return ctx.usageError("Unknown command '{s}'. Run 'zag --help' for usage.", .{name}); + }; + ctx.command = if (cmd.sub) |s| try std.fmt.allocPrint(ctx.arena, "{s} {s}", .{ cmd.name, s }) else cmd.name; + + const specs = try std.mem.concat(ctx.arena, args_mod.Opt, &.{ &global_opts, cmd.opts }); + const own = args_mod.parse(ctx.arena, cmd_args, specs, .{ .stop_at_positional = cmd.stop_at_positional }, &diag) catch |err| { + const what = switch (err) { + error.UnknownOption => "Unknown option", + error.MissingValue => "Missing value for option", + error.UnexpectedValue => "Option does not take a value", + error.OutOfMemory => return error.OutOfMemory, + }; + return ctx.usageError("{s}: {s}\nRun 'zag {s} --help' for usage.", .{ what, diag.token, ctx.command }); + }; + ctx.parsed = try pre.merge(ctx.arena, own); + + if (ctx.flag("version")) return printVersion(ctx); + if (ctx.flag("help")) { + try ctx.stdout.writeAll(cmd.usage); + return exit_ok; + } + + if (ctx.value("output")) |o| { + ctx.format = output.Format.parse(o) orelse return ctx.usageError("Invalid output format '{s}' (expected human, json or xml)", .{o}); + } + ctx.color = .{ .enabled = stdout_is_tty and ctx.format == .human and ctx.env.get("NO_COLOR") == null }; + + const code = try cmd.run(ctx); + return code; +} + +fn printVersion(ctx: *Context) !u8 { + try ctx.stdout.print("zag {s}\n", .{@import("root.zig").version}); + return exit_ok; +} + +// -- tests ----------------------------------------------------------------------------- + +pub const TestRun = struct { code: u8, out: []const u8, err: []const u8 }; + +/// Runs the CLI in-process with captured output (for tests). `env` may be null. +pub fn runCaptured(arena: Allocator, argv: []const []const u8, env_in: ?*const Environ.Map) !TestRun { + var out: Io.Writer.Allocating = .init(arena); + var err: Io.Writer.Allocating = .init(arena); + var empty = Environ.Map.init(std.testing.allocator); + defer empty.deinit(); + const code = run(std.testing.allocator, std.testing.io, env_in orelse &empty, &out.writer, &err.writer, "zag-test", argv, false); + return .{ .code = code, .out = out.written(), .err = err.written() }; +} + +test "no arguments prints help; --version prints the version" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const help = try runCaptured(arena.allocator(), &.{}, null); + try std.testing.expectEqual(exit_ok, help.code); + try std.testing.expect(std.mem.indexOf(u8, help.out, "Usage: zag") != null); + + const v = try runCaptured(arena.allocator(), &.{"--version"}, null); + try std.testing.expectEqual(exit_ok, v.code); + try std.testing.expect(std.mem.startsWith(u8, v.out, "zag ")); +} + +test "usage errors exit with 2" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try std.testing.expectEqual(exit_usage, (try runCaptured(a, &.{"frobnicate"}, null)).code); + try std.testing.expectEqual(exit_usage, (try runCaptured(a, &.{ "status", "--bogus" }, null)).code); + try std.testing.expectEqual(exit_usage, (try runCaptured(a, &.{ "status", "-o", "yaml" }, null)).code); + try std.testing.expectEqual(exit_usage, (try runCaptured(a, &.{ "service", "explode" }, null)).code); +} + +test "per-command help" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const r = try runCaptured(arena.allocator(), &.{ "run", "--help" }, null); + try std.testing.expectEqual(exit_ok, r.code); + try std.testing.expect(std.mem.indexOf(u8, r.out, "--load-level") != null); + const s = try runCaptured(arena.allocator(), &.{ "service", "--help" }, null); + try std.testing.expect(std.mem.indexOf(u8, s.out, "restart") != null); +} diff --git a/src/cli_admin.zig b/src/cli_admin.zig new file mode 100644 index 0000000..f4676b3 --- /dev/null +++ b/src/cli_admin.zig @@ -0,0 +1,699 @@ +//! Service management, configuration and shell-completion commands. +const std = @import("std"); +const builtin = @import("builtin"); +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 config = @import("config.zig"); +const toml = @import("toml.zig"); +const defaults = @import("defaults.zig"); +const dirs_mod = @import("dirs.zig"); +const daemon = @import("daemon.zig"); +const service_mod = @import("service.zig"); +const logging = @import("logging.zig"); +const ipc = @import("ipc.zig"); +const proc = @import("proc.zig"); +const timestamp = @import("timestamp.zig"); +const Repository = @import("repository.zig").Repository; +const state_mod = @import("state.zig"); +const Classifier = @import("loadclass.zig").Classifier; +const jsonpretty = @import("jsonpretty.zig"); + +const exit_ok = cli.exit_ok; +const exit_error = cli.exit_error; +const exit_usage = cli.exit_usage; + +const stop_timeout_ms: u64 = 30_000; + +// -- service start --------------------------------------------------------------------- + +pub const service_start_opts = [_]args_mod.Opt{ + .{ .long = "foreground", .short = 'f' }, + .{ .long = "dry-run" }, +}; + +pub const service_start_usage = + \\Usage: zag service start [options] + \\ + \\Start the zag service in the background. It runs jobs, serves the CLI over a local + \\socket, and survives the terminal or SSH session that started it. + \\ + \\Options: + \\ -f, --foreground Run in this process instead of detaching (used by service managers) + \\ +; + +const ReloadState = struct { + io: Io, + env: *const std.process.Environ.Map, + explicit_path: ?[]const u8, +}; + +fn reloadConfig(ctx_ptr: ?*anyopaque, arena: Allocator) anyerror!config.Config { + const st: *const ReloadState = @ptrCast(@alignCast(ctx_ptr.?)); + return config.load(arena, st.io, st.env, .{ .explicit_path = st.explicit_path }, null); +} + +fn startBackground(ctx: *Context) !u8 { + var dirs = try ctx.openDirs(); + defer dirs.close(ctx.io); + + var argv: std.ArrayList([]const u8) = .empty; + try argv.appendSlice(ctx.arena, &.{ ctx.exe_path, "service", "start", "--foreground" }); + if (ctx.value("barn-dir")) |d| try argv.appendSlice(ctx.arena, &.{ "--barn-dir", d }); + if (ctx.value("config")) |c| try argv.appendSlice(ctx.arena, &.{ "--config", c }); + + const pid = daemon.startBackground(ctx.io, ctx.arena, &dirs, argv.items, ctx.socketPath(), 10_000) catch |err| switch (err) { + error.AlreadyRunning => return ctx.fail("Zag service is already running", .{}), + error.StartTimeout => return ctx.fail("Zag service did not come up within 10 seconds; see {s}/{s}", .{ dirs.base_path, dirs_mod.daemon_log }), + else => |e| return ctx.failWithCause(@errorName(e), "Failed to start service", .{}), + }; + try ctx.stdout.print("Zag service started (PID: {d})\n", .{pid}); + return exit_ok; +} + +pub fn cmdServiceStart(ctx: *Context) !u8 { + const cfg = ctx.loadConfig() catch return ctx.describeConfigError(); + var dirs = try ctx.openDirs(); + defer dirs.close(ctx.io); + + if (daemon.runningPid(ctx.io, &dirs)) |_| return ctx.fail("Zag service is already running", .{}); + if (ctx.flag("dry-run")) { + try ctx.stdout.writeAll("Zag service would be started (dry run)\n"); + return exit_ok; + } + if (!ctx.flag("foreground")) return startBackground(ctx); + + logging.setFromConfig(cfg.service.log_level); + const sys_dir = try config.systemConfigDir(ctx.arena, ctx.env); + const classifier = try Classifier.loadOrDefaults(ctx.arena, ctx.io, sys_dir); + const reload_state = try ctx.arena.create(ReloadState); + reload_state.* = .{ .io = ctx.io, .env = ctx.env, .explicit_path = ctx.value("config") }; + + var svc = service_mod.Service.init(ctx.gpa, ctx.io, &dirs, .{ + .config = cfg, + .classifier = classifier, + .reload_fn = reloadConfig, + .reload_ctx = reload_state, + }); + svc.bind(ctx.socketPath()); + defer svc.deinit(); + + try ctx.stdout.print("Zag service started (PID: {d})\n", .{proc.currentPid()}); + try ctx.stdout.flush(); + daemon.runForeground(ctx.io, &dirs, &svc) catch |err| switch (err) { + error.AlreadyRunning => return ctx.fail("Zag service is already running", .{}), + else => |e| return ctx.failWithCause(@errorName(e), "Service failed", .{}), + }; + return exit_ok; +} + +// -- service stop / restart ------------------------------------------------------------ + +pub const service_stop_opts = [_]args_mod.Opt{.{ .long = "force", .short = 'f' }}; + +pub const service_stop_usage = + \\Usage: zag service stop [options] + \\ + \\Stop the zag service: SIGTERM, then SIGKILL (together with running jobs) if it has not + \\exited after 30 seconds. + \\ + \\Options: + \\ -f, --force Kill the service and its running jobs immediately + \\ +; + +pub fn cmdServiceStop(ctx: *Context) !u8 { + var dirs = try ctx.openDirs(); + defer dirs.close(ctx.io); + const force = ctx.flag("force"); + const result = daemon.stopDaemon(ctx.io, ctx.gpa, &dirs, if (force) 0 else stop_timeout_ms, true); + switch (result) { + .not_running => { + if (force) { + try ctx.stdout.writeAll("Zag service was not running\n"); + return exit_ok; + } + return ctx.fail("Zag service is not running", .{}); + }, + .stopped => try ctx.stdout.writeAll("Zag service stopped\n"), + .killed => try ctx.stdout.writeAll(if (force) "Zag service force stopped\n" else "Zag service stopped (killed after 30 seconds)\n"), + .timed_out => return ctx.fail("Zag service did not stop", .{}), + } + return exit_ok; +} + +pub const service_restart_opts = [_]args_mod.Opt{.{ .long = "force", .short = 'f' }}; + +pub const service_restart_usage = + \\Usage: zag service restart [options] + \\ + \\Stop the running service and start it again. + \\ + \\Options: + \\ -f, --force Kill the old service and its jobs immediately + \\ +; + +pub fn cmdServiceRestart(ctx: *Context) !u8 { + { + var dirs = try ctx.openDirs(); + defer dirs.close(ctx.io); + if (daemon.runningPid(ctx.io, &dirs) == null) return ctx.fail("Zag service is not running", .{}); + const result = daemon.stopDaemon(ctx.io, ctx.gpa, &dirs, if (ctx.flag("force")) 0 else stop_timeout_ms, true); + if (result == .timed_out) return ctx.fail("Failed to stop service", .{}); + } + try ctx.io.sleep(.fromMilliseconds(500), .real); + const code = try startBackground(ctx); + if (code != exit_ok) return code; + try ctx.stdout.writeAll("Zag service restarted\n"); + return exit_ok; +} + +// -- service reload / status / logs ---------------------------------------------------- + +pub const service_reload_usage = + \\Usage: zag service reload + \\ + \\Reload configuration without stopping jobs. Concurrency limits, retry and timeout + \\defaults, heartbeat and cleanup settings apply immediately; paths need a restart. + \\ +; + +pub fn cmdServiceReload(ctx: *Context) !u8 { + var dirs = try ctx.openDirs(); + defer dirs.close(ctx.io); + const pid = daemon.runningPid(ctx.io, &dirs) orelse return ctx.fail("Zag service is not running", .{}); + + const reply = ipc.call(ctx.io, ctx.arena, ctx.socketPath(), "reload", null) catch |err| { + std.log.warn("reload over IPC failed ({s}); sending SIGHUP", .{@errorName(err)}); + std.posix.kill(@intCast(pid), .HUP) catch return ctx.fail("Failed to send reload signal", .{}); + try ctx.stdout.writeAll("Configuration reloaded\n"); + return exit_ok; + }; + switch (reply) { + .ok => { + try ctx.stdout.writeAll("Configuration reloaded\n"); + return exit_ok; + }, + .err => |e| return ctx.fail("Reload failed: {s}", .{e.message}), + } +} + +pub const service_status_usage = + \\Usage: zag service status + \\ + \\Show whether the service is running, its uptime and job counts. + \\ +; + +pub fn cmdServiceStatus(ctx: *Context) !u8 { + var dirs = try ctx.openDirs(); + defer dirs.close(ctx.io); + const a = ctx.arena; + const pid = daemon.runningPid(ctx.io, &dirs); + + var counts = [_]u32{0} ** 6; + var total: usize = 0; + var started_at: ?i128 = null; + var uptime: i64 = 0; + if (pid != null) { + var from_ipc = false; + if (ipc.call(ctx.io, a, ctx.socketPath(), "get_service_status", null)) |reply| { + if (reply == .ok) if (reply.ok == .object) { + const obj = reply.ok.object; + if (obj.get("startedAt")) |v| if (v == .string) { + started_at = timestamp.parse(v.string) catch null; + }; + if (obj.get("uptimeSeconds")) |v| if (v == .integer) { + uptime = v.integer; + }; + if (obj.get("jobs")) |jv| if (jv == .object) { + inline for (@typeInfo(state_mod.State).@"enum".fields) |f| { + if (jv.object.get(f.name)) |c| if (c == .integer) { + counts[f.value] = @intCast(c.integer); + }; + } + if (jv.object.get("total")) |t| if (t == .integer) { + total = @intCast(t.integer); + }; + from_ipc = true; + }; + }; + } else |_| {} + if (!from_ipc) { + const jobs = try Repository.init(ctx.io, &dirs).findAll(a); + for (jobs) |j| counts[@intFromEnum(j.state)] += 1; + total = jobs.len; + } + } + + const w = ctx.stdout; + if (ctx.format == .human) { + try w.writeAll("Zag Service Status\n==================\n"); + try w.print("Status: {s}\n", .{if (pid != null) "running" else "stopped"}); + if (pid) |p| { + var ub: [48]u8 = undefined; + var tb: [19]u8 = undefined; + try w.print("PID: {d}\n", .{p}); + try w.print("Uptime: {s}\n", .{output.formatUptime(&ub, uptime)}); + try w.print("Started: {s}\n", .{if (started_at) |s| output.formatLocal(&tb, s) else "-"}); + try w.writeAll("\nJobs:\n"); + try w.print(" Running: {d}\n Queued: {d}\n Succeeded: {d}\n Failed: {d}\n Canceled: {d}\n Killed: {d}\n Total: {d}\n", .{ + counts[@intFromEnum(state_mod.State.running)], + counts[@intFromEnum(state_mod.State.queued)], + counts[@intFromEnum(state_mod.State.succeeded)], + counts[@intFromEnum(state_mod.State.failed)], + counts[@intFromEnum(state_mod.State.canceled)], + counts[@intFromEnum(state_mod.State.killed)], + total, + }); + } + try w.print("\nData Dir: {s}\n", .{dirs.base_path}); + return exit_ok; + } + + var m = MapBuilder.init(a); + try m.put("status", Node.str(if (pid != null) "running" else "stopped")); + try m.put("running", .{ .boolean = pid != null }); + if (pid) |p| { + try m.put("pid", .{ .int = p }); + try m.put("uptime_seconds", .{ .int = uptime }); + if (started_at) |s| { + const buf = try a.alloc(u8, timestamp.max_len); + try m.put("started_at", Node.str(timestamp.format(buf[0..timestamp.max_len], s))); + } else try m.put("started_at", .null); + var jm = MapBuilder.init(a); + inline for (@typeInfo(state_mod.State).@"enum".fields) |f| try jm.put(f.name, Node.num(counts[f.value])); + try jm.put("total", Node.num(total)); + try m.put("jobs", try jm.done()); + } + try m.put("data_dir", Node.str(dirs.base_path)); + try ctx.emit(try m.done()); + return exit_ok; +} + +pub const service_logs_opts = [_]args_mod.Opt{ + .{ .long = "follow", .short = 'f' }, + .{ .long = "lines", .short = 'n', .takes_value = true }, +}; + +pub const service_logs_usage = + \\Usage: zag service logs [options] + \\ + \\Show the service log (/logs/zag.log). + \\ + \\Options: + \\ -f, --follow Keep printing new lines (Ctrl+C to stop) + \\ -n, --lines Number of lines to show (default: 100) + \\ +; + +pub fn cmdServiceLogs(ctx: *Context) !u8 { + var lines: usize = 100; + if (ctx.value("lines")) |l| lines = std.fmt.parseInt(usize, l, 10) catch return ctx.usageError("Invalid --lines '{s}'", .{l}); + var dirs = try ctx.openDirs(); + defer dirs.close(ctx.io); + const log_path = try std.fmt.allocPrint(ctx.arena, "{s}/{s}", .{ dirs.base_path, dirs_mod.daemon_log }); + + var file = dirs.base.openFile(ctx.io, dirs_mod.daemon_log, .{}) catch |err| switch (err) { + error.FileNotFound => { + try ctx.stdout.print("No log file found at: {s}\n", .{log_path}); + return exit_ok; + }, + else => |e| return e, + }; + defer file.close(ctx.io); + + const len = try file.length(ctx.io); + const window: u64 = 1024 * 1024; + const start = if (len > window) len - window else 0; + const buf = try ctx.arena.alloc(u8, @intCast(len - start)); + const got = try file.readPositionalAll(ctx.io, buf, start); + var text: []const u8 = buf[0..got]; + if (start > 0) if (std.mem.indexOfScalar(u8, text, '\n')) |i| { + text = text[i + 1 ..]; + }; + text = std.mem.trimEnd(u8, text, "\n"); + if (text.len > 0) { + var all: std.ArrayList([]const u8) = .empty; + var it = std.mem.splitScalar(u8, text, '\n'); + while (it.next()) |l| try all.append(ctx.arena, l); + const shown = if (all.items.len > lines) all.items[all.items.len - lines ..] else all.items; + for (shown) |l| try ctx.stdout.print("{s}\n", .{l}); + } + if (!ctx.flag("follow")) return exit_ok; + + try ctx.stdout.writeAll("--- Following log output (Ctrl+C to stop) ---\n"); + try ctx.stdout.flush(); + var offset: u64 = len; + var chunk: [8192]u8 = undefined; + while (true) { + const n = try file.readPositionalAll(ctx.io, &chunk, offset); + if (n > 0) { + try ctx.stdout.writeAll(chunk[0..n]); + try ctx.stdout.flush(); + offset += n; + } else { + ctx.io.sleep(.fromMilliseconds(100), .real) catch return exit_ok; + } + } +} + +// -- config ---------------------------------------------------------------------------- + +pub const config_show_opts = [_]args_mod.Opt{.{ .long = "defaults" }}; + +pub const config_show_usage = + \\Usage: zag config show [options] + \\ + \\Show the effective configuration (defaults, system and user files, --config and ZAG_* + \\environment overrides merged). + \\ + \\Options: + \\ --defaults Show only the built-in defaults + \\ +; + +fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8) !Node { + var root = MapBuilder.init(arena); + var s = MapBuilder.init(arena); + try s.put("log_level", Node.str(@tagName(cfg.service.log_level))); + try s.put("max_concurrent_jobs", Node.num(cfg.service.max_concurrent_jobs)); + try s.put("heartbeat_interval_seconds", Node.num(cfg.service.heartbeat_interval_seconds)); + try s.put("ipc_socket", Node.str(socket)); + try s.put("stale_heartbeat_threshold_seconds", Node.num(cfg.service.stale_heartbeat_threshold_seconds)); + try root.put("service", try s.done()); + + var j = MapBuilder.init(arena); + try j.put("default_timeout_seconds", Node.num(cfg.jobs.default_timeout_seconds)); + try j.put("max_retries", Node.num(cfg.jobs.max_retries)); + try j.put("retry_delay_seconds", Node.num(cfg.jobs.retry_delay_seconds)); + try j.put("retry_backoff_multiplier", .{ .float = cfg.jobs.retry_backoff_multiplier }); + const codes = try arena.alloc(Node, cfg.jobs.retry_on_exit_codes.len); + for (cfg.jobs.retry_on_exit_codes, codes) |c, *n| n.* = .{ .int = c }; + try j.put("retry_on_exit_codes", .{ .list = codes }); + try root.put("jobs", try j.done()); + + var c = MapBuilder.init(arena); + try c.put("enabled", .{ .boolean = cfg.cleanup.enabled }); + try c.put("max_age_hours", Node.num(cfg.cleanup.max_age_hours)); + try c.put("cleanup_interval_minutes", Node.num(cfg.cleanup.cleanup_interval_minutes)); + try c.put("keep_failed_jobs", .{ .boolean = cfg.cleanup.keep_failed_jobs }); + try c.put("keep_failed_jobs_hours", Node.num(cfg.cleanup.keep_failed_jobs_hours)); + try root.put("cleanup", try c.done()); + + var st = MapBuilder.init(arena); + try st.put("base_dir", Node.str(cfg.storage.base_dir)); + try st.put("max_disk_usage_gb", Node.num(cfg.storage.max_disk_usage_gb)); + try st.put("preserve_work_dir", .{ .boolean = cfg.storage.preserve_work_dir }); + try root.put("storage", try st.done()); + + var l = MapBuilder.init(arena); + try l.put("max_high_jobs", Node.num(cfg.load_levels.max_high_jobs)); + try l.put("max_medium_jobs", Node.num(cfg.load_levels.max_medium_jobs)); + try l.put("max_low_jobs", Node.num(cfg.load_levels.max_low_jobs)); + try root.put("load_levels", try l.done()); + return root.done(); +} + +pub fn cmdConfigShow(ctx: *Context) !u8 { + const show_defaults = ctx.flag("defaults"); + const cfg: config.Config = if (show_defaults) .{} else ctx.loadConfig() catch return ctx.describeConfigError(); + const socket = if (show_defaults) try (config.Config{}).ipcSocketPath(ctx.arena) else try cfg.ipcSocketPath(ctx.arena); + + if (ctx.format != .human) { + try ctx.emit(try configNode(ctx.arena, cfg, socket)); + return exit_ok; + } + + const w = ctx.stdout; + try w.writeAll("Zag Configuration\n=================\n"); + if (show_defaults) { + try w.writeAll("Showing default values\n"); + } else { + var found: std.ArrayList([]const u8) = .empty; + const paths = try config.searchPaths(ctx.arena, ctx.env); + for (paths) |p| if (Io.Dir.cwd().statFile(ctx.io, p, .{})) |_| try found.append(ctx.arena, p) else |_| {}; + if (ctx.value("config")) |p| if (Io.Dir.cwd().statFile(ctx.io, p, .{})) |_| try found.append(ctx.arena, p) else |_| {}; + if (found.items.len == 0) { + try w.writeAll("Config file: (none found, using defaults)\n"); + } else { + try w.print("Config file: {s}\n", .{try std.mem.join(ctx.arena, ", ", found.items)}); + } + } + try w.print("\n[service]\nlog_level = {s}\nmax_concurrent_jobs = {d}\nheartbeat_interval_seconds = {d}\nipc_socket = {s}\nstale_heartbeat_threshold_seconds = {d}\n", .{ + @tagName(cfg.service.log_level), cfg.service.max_concurrent_jobs, cfg.service.heartbeat_interval_seconds, socket, cfg.service.stale_heartbeat_threshold_seconds, + }); + try w.print("\n[jobs]\ndefault_timeout_seconds = {d}\nmax_retries = {d}\nretry_delay_seconds = {d}\nretry_backoff_multiplier = {d:.1}\nretry_on_exit_codes = [", .{ + cfg.jobs.default_timeout_seconds, cfg.jobs.max_retries, cfg.jobs.retry_delay_seconds, cfg.jobs.retry_backoff_multiplier, + }); + for (cfg.jobs.retry_on_exit_codes, 0..) |c, i| try w.print("{s}{d}", .{ if (i > 0) ", " else "", c }); + try w.writeAll("]\n"); + try w.print("\n[cleanup]\nenabled = {any}\nmax_age_hours = {d}\ncleanup_interval_minutes = {d}\nkeep_failed_jobs = {any}\nkeep_failed_jobs_hours = {d}\n", .{ + cfg.cleanup.enabled, cfg.cleanup.max_age_hours, cfg.cleanup.cleanup_interval_minutes, cfg.cleanup.keep_failed_jobs, cfg.cleanup.keep_failed_jobs_hours, + }); + try w.print("\n[storage]\nbase_dir = {s}\nmax_disk_usage_gb = {d}\npreserve_work_dir = {any}\n", .{ + cfg.storage.base_dir, cfg.storage.max_disk_usage_gb, cfg.storage.preserve_work_dir, + }); + try w.print("\n[load_levels]\nmax_high_jobs = {d}\nmax_medium_jobs = {d}\nmax_low_jobs = {d}\n", .{ + cfg.load_levels.max_high_jobs, cfg.load_levels.max_medium_jobs, cfg.load_levels.max_low_jobs, + }); + return exit_ok; +} + +pub const config_validate_opts = [_]args_mod.Opt{.{ .long = "file", .short = 'f', .takes_value = true }}; + +pub const config_validate_usage = + \\Usage: zag config validate --file + \\ + \\Check a configuration file for syntax errors, unknown sections or keys, and bad values. + \\Exits 1 if anything is wrong. + \\ + \\Options: + \\ -f, --file File to validate (required) + \\ +; + +pub fn cmdConfigValidate(ctx: *Context) !u8 { + const path = ctx.value("file") orelse return ctx.usageError("Missing required option: --file ", .{}); + const a = ctx.arena; + + const text = Io.Dir.cwd().readFileAlloc(ctx.io, path, a, .limited(1 << 20)) catch |err| switch (err) { + error.FileNotFound => return ctx.fail("Configuration file not found: {s}", .{path}), + else => return ctx.failWithCause(@errorName(err), "Failed to read configuration file {s}", .{path}), + }; + var td: toml.Diagnostic = .{}; + var list: std.ArrayList(config.Problem) = .empty; + if (toml.parse(a, text, &td)) |doc| { + try list.appendSlice(a, try config.problems(a, doc)); + } else |err| { + const what = switch (err) { + error.KeyOutsideSection => "key-value pair outside of a section", + error.InvalidValue => "cannot parse value", + error.InvalidSyntax => "invalid syntax", + error.OutOfMemory => return error.OutOfMemory, + }; + try list.append(a, .{ .section = "", .key = "", .message = try std.fmt.allocPrint(a, "Parse error at line {d}: {s}", .{ td.line, what }) }); + } + + if (list.items.len == 0) { + if (ctx.format == .human) { + try ctx.stdout.print("Configuration is valid: {s}\n", .{path}); + } else { + var m = MapBuilder.init(a); + try m.put("valid", .{ .boolean = true }); + try m.put("file", Node.str(path)); + try ctx.emit(try m.done()); + } + return exit_ok; + } + + if (ctx.format == .human) { + try ctx.stdout.print("Configuration errors in {s}:\n\n", .{path}); + for (list.items) |p| { + if (p.key.len > 0) try ctx.stdout.print(" Key '{s}': {s}\n", .{ p.key, p.message }) else try ctx.stdout.print(" {s}\n", .{p.message}); + } + } else { + const nodes = try a.alloc(Node, list.items.len); + for (list.items, nodes) |p, *n| { + var em = MapBuilder.init(a); + if (p.key.len > 0) try em.put("key", Node.str(p.key)); + try em.put("message", Node.str(p.message)); + n.* = try em.done(); + } + var m = MapBuilder.init(a); + try m.put("valid", .{ .boolean = false }); + try m.put("file", Node.str(path)); + try m.put("errors", .{ .list = nodes }); + try ctx.emit(try m.done()); + } + return exit_error; +} + +fn writeFileCreatingParents(ctx: *Context, path: []const u8, data: []const u8) !void { + const cwd = Io.Dir.cwd(); + if (std.fs.path.dirname(path)) |parent| try cwd.createDirPath(ctx.io, parent); + try cwd.writeFile(ctx.io, .{ .sub_path = path, .data = data }); +} + +pub const config_init_opts = [_]args_mod.Opt{ + .{ .long = "path", .short = 'p', .takes_value = true }, + .{ .long = "force", .short = 'f' }, +}; + +pub const config_init_usage = + \\Usage: zag config init [options] + \\ + \\Create a configuration file with the default settings (user config by default). + \\ + \\Options: + \\ -p, --path Where to write it + \\ -f, --force Overwrite an existing file + \\ +; + +pub fn cmdConfigInit(ctx: *Context) !u8 { + const target = ctx.value("path") orelse blk: { + const paths = try config.searchPaths(ctx.arena, ctx.env); + break :blk paths[1]; + }; + if (!ctx.flag("force")) if (Io.Dir.cwd().statFile(ctx.io, target, .{})) |_| { + _ = ctx.fail("Configuration file already exists: \"{s}\"", .{target}); + return ctx.fail("Use --force to overwrite", .{}); + } else |_| {}; + writeFileCreatingParents(ctx, target, defaults.zag_conf) catch |err| + return ctx.failWithCause(@errorName(err), "Failed to create configuration file", .{}); + try ctx.stdout.print("Configuration file created: \"{s}\"\n", .{target}); + return exit_ok; +} + +pub const config_install_opts = [_]args_mod.Opt{ + .{ .long = "directory", .short = 'd', .takes_value = true }, + .{ .long = "force", .short = 'f' }, + .{ .long = "show" }, +}; + +pub const config_install_usage = + \\Usage: zag config install [options] + \\ + \\Install the default configuration files (zag.conf and the high/medium/low .load + \\whitelists) into the system config directory. + \\ + \\Options: + \\ -d, --directory Target directory (default: /etc/zag) + \\ -f, --force Write the files (overwriting existing ones) without asking + \\ --show Print what would be installed without writing + \\ +; + +pub fn cmdConfigInstall(ctx: *Context) !u8 { + const target = ctx.value("directory") orelse try config.systemConfigDir(ctx.arena, ctx.env); + const w = ctx.stdout; + + if (ctx.flag("show")) { + try w.print("Files that would be installed to: {s}\n\n", .{target}); + for (defaults.files) |f| try w.print("=== {s} ===\n{s}\n", .{ f.name, f.content }); + return exit_ok; + } + if (!ctx.flag("force")) { + try w.writeAll("The following files will be created/overwritten:\n"); + for (defaults.files) |f| try w.print(" {s}/{s}\n", .{ target, f.name }); + try w.writeAll("\nWARNING: This will overwrite any existing configuration.\nUse --force to proceed, or --show to preview without writing.\n"); + return exit_ok; + } + for (defaults.files) |f| { + const path = try std.fmt.allocPrint(ctx.arena, "{s}/{s}", .{ target, f.name }); + writeFileCreatingParents(ctx, path, f.content) catch |err| + return ctx.failWithCause(@errorName(err), "Failed to install {s} (are you root?)", .{path}); + try w.print("Installed: {s}\n", .{path}); + } + try w.print("\nConfiguration installed successfully.\nConfig directory: {s}\n", .{target}); + return exit_ok; +} + +// -- autocompletion -------------------------------------------------------------------- + +pub const autocompletion_opts = [_]args_mod.Opt{ + .{ .long = "bash" }, + .{ .long = "zsh" }, +}; + +pub const autocompletion_usage = + \\Usage: zag autocompletion (--bash | --zsh) + \\ + \\Print a shell completion script, e.g. `source <(zag autocompletion --bash)`. + \\ +; + +const bash_completion = + \\_zag() { + \\ local cur prev words cword + \\ cur="${COMP_WORDS[COMP_CWORD]}" + \\ prev="${COMP_WORDS[COMP_CWORD-1]}" + \\ local global="-o --output --config --offline --barn-dir -h --help -V --version" + \\ local cmds="run status describe usage kill clean service config autocompletion" + \\ local cmd="" sub="" + \\ local i + \\ for ((i=1; i |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] [--] [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 Tag for filtering jobs + \\ -l, --load-level high, medium or low (default: auto-detect) + \\ --max-retries Override the maximum number of retries + \\ --retry-delay Override the initial retry delay + \\ --timeout 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 Only jobs with this tag + \\ -s, --state Only jobs in this state (queued, running, succeeded, failed, canceled, killed) + \\ -n, --limit 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] + \\ + \\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] + \\ + \\Show CPU, memory and disk usage sampled while a job ran. + \\ + \\Options: + \\ -n, --limit 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] + \\ + \\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 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 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; +} diff --git a/src/jobjson.zig b/src/jobjson.zig index 5ba8f9c..a771a3c 100644 --- a/src/jobjson.zig +++ b/src/jobjson.zig @@ -24,7 +24,7 @@ pub fn upperState(s: state_mod.State) []const u8 { } pub fn writeInstant(w: *jsonpretty.Writer, t: ?Instant) !void { - const v = t orelse return w.@"null"(); + const v = t orelse return w.null(); var buf: [timestamp.max_len]u8 = undefined; try w.string(timestamp.format(&buf, v)); } @@ -50,11 +50,11 @@ pub fn writeJob(w: *jsonpretty.Writer, job: Job) !void { if (job.exit_code) |c| switch (c) { .code => |n| try w.int(n), .symbol => |s| try w.string(s), - } else try w.@"null"(); + } else try w.null(); try w.key("error"); try w.optString(job.err); try w.key("pid"); - if (job.pid) |p| try w.int(p) else try w.@"null"(); + if (job.pid) |p| try w.int(p) else try w.null(); try w.key("heartbeat"); try writeInstant(w, job.heartbeat); try w.field("retryCount", .int, job.retry_count); diff --git a/src/jsonpretty.zig b/src/jsonpretty.zig index b09c8c0..bce2165 100644 --- a/src/jsonpretty.zig +++ b/src/jsonpretty.zig @@ -130,7 +130,7 @@ pub const Writer = struct { /// Writes a string, or `null` for an absent value. pub fn optString(self: *Writer, s: ?[]const u8) Error!void { - if (s) |v| try self.string(v) else try self.@"null"(); + if (s) |v| try self.string(v) else try self.null(); } pub fn field(self: *Writer, name: []const u8, comptime kind: enum { string, int, boolean, float }, value: anytype) Error!void { @@ -223,7 +223,7 @@ test "arrays are inline; objects in arrays indent relative to the enclosing obje try w.string("Hello World"); try w.endArray(); try w.key("tag"); - try w.@"null"(); + try w.null(); try w.key("jobs"); try w.beginArray(); try w.beginObject(); @@ -316,7 +316,7 @@ test "compact style has no whitespace" { try w.beginArray(); try w.endArray(); try w.key("tag"); - try w.@"null"(); + try w.null(); try w.endObject(); try w.endObject(); try std.testing.expectEqualStrings( diff --git a/src/logging.zig b/src/logging.zig new file mode 100644 index 0000000..099a16e --- /dev/null +++ b/src/logging.zig @@ -0,0 +1,50 @@ +//! Process-wide logging: `2026-01-22 01:48:46.749 INFO (scope) message` on stderr. +//! CLI commands log only warnings and errors; the daemon raises the level from its config. +const std = @import("std"); +const output = @import("output.zig"); +const config = @import("config.zig"); + +/// Messages less severe than this are dropped (`err` is the most severe). +pub var level: std.log.Level = .warn; + +pub fn setFromConfig(l: config.LogLevel) void { + level = switch (l) { + .debug => .debug, + .info => .info, + .warn => .warn, + .@"error" => .err, + }; +} + +pub fn logFn( + comptime message_level: std.log.Level, + comptime scope: @EnumLiteral(), + comptime format: []const u8, + args: anytype, +) void { + if (@intFromEnum(message_level) > @intFromEnum(level)) return; + + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.REALTIME, &ts); + const ns: i128 = @as(i128, ts.sec) * std.time.ns_per_s + ts.nsec; + var date: [19]u8 = undefined; + const when = output.formatLocal(&date, ns); + const millis: u32 = @intCast(@divFloor(@mod(ns, std.time.ns_per_s), std.time.ns_per_ms)); + + var buffer: [64]u8 = undefined; + const stderr = std.debug.lockStderr(&buffer).terminal(); + defer std.debug.unlockStderr(); + const w = stderr.writer; + w.print("{s}.{d:0>3} {s: <5} ", .{ when, millis, comptime upper(message_level) }) catch return; + if (scope != .default) w.print("({t}) ", .{scope}) catch return; + w.print(format ++ "\n", args) catch return; +} + +fn upper(comptime l: std.log.Level) []const u8 { + return switch (l) { + .err => "ERROR", + .warn => "WARN", + .info => "INFO", + .debug => "DEBUG", + }; +} diff --git a/src/main.zig b/src/main.zig index a6316a7..757b148 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,71 +1,36 @@ const std = @import("std"); const Io = std.Io; - const zag = @import("zag"); +pub const std_options: std.Options = .{ + .log_level = .debug, // filtering happens at runtime in `zag.logging` + .logFn = zag.logging.logFn, +}; + pub fn main(init: std.process.Init) !void { - // Prints to stderr, unbuffered, ignoring potential errors. - std.debug.print("All your {s} are belong to us.\n", .{"codebase"}); - - // This is appropriate for anything that lives as long as the process. - const arena: std.mem.Allocator = init.arena.allocator(); - - // Accessing command line arguments: - const args = try init.minimal.args.toSlice(arena); - for (args) |arg| { - std.log.info("arg: {s}", .{arg}); - } - - // In order to do I/O operations need an `Io` instance. + const gpa = init.gpa; const io = init.io; - // Stdout is for the actual output of your application, for example if you - // are implementing gzip, then only the compressed bytes should be sent to - // stdout, not any debugging messages. - var stdout_buffer: [1024]u8 = undefined; - var stdout_file_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); - const stdout_writer = &stdout_file_writer.interface; + const argv = try init.minimal.args.toSlice(init.arena.allocator()); + const exe_path = std.process.executablePathAlloc(io, init.arena.allocator()) catch argv[0]; - try zag.printAnotherMessage(stdout_writer); + var stdout_buffer: [8192]u8 = undefined; + var stdout_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); + var stderr_buffer: [4096]u8 = undefined; + var stderr_writer: Io.File.Writer = .init(.stderr(), io, &stderr_buffer); - try stdout_writer.flush(); // Don't forget to flush! -} - -test "simple test" { - const gpa = std.testing.allocator; - var list: std.ArrayList(i32) = .empty; - defer list.deinit(gpa); // Try commenting this out and see if zig detects the memory leak! - try list.append(gpa, 42); - try std.testing.expectEqual(@as(i32, 42), list.pop()); -} - -test "fuzz example" { - try std.testing.fuzz({}, testOne, .{}); -} - -fn testOne(context: void, smith: *std.testing.Smith) !void { - _ = context; - // Try passing `--fuzz` to `zig build test` and see if it manages to fail this test case! - - const gpa = std.testing.allocator; - var list: std.ArrayList(u8) = .empty; - defer list.deinit(gpa); - while (!smith.eos()) switch (smith.value(enum { add_data, dup_data })) { - .add_data => { - const slice = try list.addManyAsSlice(gpa, smith.value(u4)); - smith.bytes(slice); - }, - .dup_data => { - if (list.items.len == 0) continue; - if (list.items.len > std.math.maxInt(u32)) return error.SkipZigTest; - const len = smith.valueRangeAtMost(u32, 1, @min(32, list.items.len)); - const off = smith.valueRangeAtMost(u32, 0, @intCast(list.items.len - len)); - try list.appendSlice(gpa, list.items[off..][0..len]); - try std.testing.expectEqualSlices( - u8, - list.items[off..][0..len], - list.items[list.items.len - len ..], - ); - }, - }; + const tty = Io.File.stdout().isTty(io) catch false; + const code = zag.cli.run( + gpa, + io, + init.environ_map, + &stdout_writer.interface, + &stderr_writer.interface, + exe_path, + argv[1..], + tty, + ); + stdout_writer.interface.flush() catch {}; + stderr_writer.interface.flush() catch {}; + std.process.exit(code); } diff --git a/src/output.zig b/src/output.zig index 5680274..4e686b2 100644 --- a/src/output.zig +++ b/src/output.zig @@ -72,7 +72,7 @@ pub const MapBuilder = struct { pub fn writeNodeJson(w: *jsonpretty.Writer, node: Node) !void { switch (node) { - .null => try w.@"null"(), + .null => try w.null(), .boolean => |b| try w.boolean(b), .int => |n| try w.int(n), .float => |f| try w.float(f), diff --git a/src/repository.zig b/src/repository.zig index 4427afe..e46f4ba 100644 --- a/src/repository.zig +++ b/src/repository.zig @@ -188,6 +188,7 @@ pub const Repository = struct { try h.sf.writeStartedAt(now); try h.sf.writePid(pid); try h.sf.writeHeartbeat(now); + try h.sf.writeRetryAt(null); // the wait is over once the attempt starts } pub fn updateHeartbeat(self: Repository, id: []const u8, at: Instant) !void { diff --git a/src/root.zig b/src/root.zig index a854f8d..bbc0115 100644 --- a/src/root.zig +++ b/src/root.zig @@ -29,6 +29,8 @@ pub const service = @import("service.zig"); pub const daemon = @import("daemon.zig"); pub const output = @import("output.zig"); pub const args = @import("args.zig"); +pub const logging = @import("logging.zig"); +pub const cli = @import("cli.zig"); pub const query = @import("query.zig"); test { diff --git a/test/e2e.sh b/test/e2e.sh new file mode 100755 index 0000000..f4602bd --- /dev/null +++ b/test/e2e.sh @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +# End-to-end smoke test of the zag binary: offline mode, the daemon, IPC, kill/retry/clean. +# Usage: test/e2e.sh [path-to-zag] (default: zig-out/bin/zag) +set -u +ZAG=${1:-zig-out/bin/zag} +DIR=$(mktemp -d /tmp/zag-e2e.XXXXXX) +Z() { "$ZAG" --barn-dir "$DIR" "$@"; } +fails=0 +pass() { printf 'ok %s\n' "$1"; } +fail() { printf 'FAIL %s\n' "$1"; fails=$((fails + 1)); } +check() { # check (command must succeed) + local name=$1; shift + if "$@" >/dev/null 2>&1; then pass "$name"; else fail "$name"; fi +} +contains() { # contains + case $3 in *"$2"*) pass "$1" ;; *) fail "$1 (missing '$2' in: $3)" ;; esac +} +json_field() { printf '%s\n' "$2" | sed -n "s/.*\"$1\" : \"\{0,1\}\([^\",]*\)\"\{0,1\},\{0,1\}\$/\1/p" | head -1; } +wait_state() { # wait_state [seconds] + local i + for ((i = 0; i < ${3:-100}; i++)); do + [[ $(json_field state "$(Z describe -o json "$1" --offline)") == "${2,,}" ]] && return 0 + sleep 0.1 + done + return 1 +} +cleanup() { Z service stop --force >/dev/null 2>&1; rm -rf "$DIR"; } +trap cleanup EXIT + +# --- basics ----------------------------------------------------------------------------- +contains "version" "zag " "$("$ZAG" --version)" +contains "help lists commands" "describe" "$("$ZAG" --help)" +"$ZAG" frobnicate >/dev/null 2>&1; [[ $? -eq 2 ]] && pass "unknown command exits 2" || fail "unknown command exits 2" + +# --- offline mode ----------------------------------------------------------------------- +out=$(Z run --offline -o json -t demo sh -c 'echo hello; exit 0') +id=$(json_field id "$out") +contains "offline run succeeds" '"state" : "SUCCEEDED"' "$out" +contains "offline run tag" '"tag" : "demo"' "$out" +contains "describe --logs shows stdout" "hello" "$(Z describe --offline --logs "$id")" +contains "status table" "succeeded" "$(Z status --offline)" +contains "status json summary" '"succeeded" : 1' "$(Z status --offline -o json)" +contains "status xml" "" "$(Z status --offline -o xml)" +contains "usage has samples" "samples" "$(Z usage "$id")" +contains "clean without selector removes nothing" "Cleaned 0 jobs." "$(Z clean --offline)" +contains "clean --all --dry-run lists the job" "Would clean 1 job" "$(Z clean --offline --all --dry-run)" +contains "clean --all removes it" "Cleaned 1 job" "$(Z clean --offline --all)" +contains "status empty" "No jobs found." "$(Z status --offline)" + +# --- config ----------------------------------------------------------------------------- +contains "config show --defaults" "max_high_jobs = 2" "$(Z config show --defaults)" +printf '[jobs]\nmax_retries = 0\nbogus = 1\n' >"$DIR/bad.conf" +Z config validate --file "$DIR/bad.conf" >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "validate flags bad config" || fail "validate flags bad config" +printf '[jobs]\nmax_retries = 0\n' >"$DIR/good.conf" +contains "validate accepts good config" "Configuration is valid" "$(Z config validate --file "$DIR/good.conf")" +contains "install --show prints files" "high.load" "$(Z config install --show)" + +# --- daemon ----------------------------------------------------------------------------- +Z run echo hi >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "run without service exits 1" || fail "run without service exits 1" +contains "service start" "Zag service started" "$(Z service start)" +contains "second start refused" "already running" "$(Z service start 2>&1)" +contains "service status running" "running" "$(Z service status)" + +out=$(Z run -o json -t svc sh -c 'echo from-daemon') +sid=$(json_field id "$out") +contains "run over IPC is queued" '"state" : "QUEUED"' "$out" +wait_state "$sid" SUCCEEDED && pass "daemon runs the job" || fail "daemon runs the job" + +out=$(Z run -o json sleep 60); kid=$(json_field id "$out") +wait_state "$kid" RUNNING && pass "sleeper is running" || fail "sleeper is running" +contains "kill reports canceled" "New state: canceled" "$(Z kill "$kid")" +wait_state "$kid" CANCELED && pass "killed job is canceled" || fail "killed job is canceled" +contains "kill a finished job fails" "not running" "$(Z kill "$kid" 2>&1)" + +out=$(Z run -o json --max-retries 1 --retry-delay 1 sh -c 'exit 5'); rid=$(json_field id "$out") +sleep 4 +desc=$(Z describe -o json "$rid" --offline) +contains "failed job retried once" '"retryCount" : 1' "$desc" +contains "failed job ended failed" '"state" : "failed"' "$desc" + +out=$(Z run -o json --timeout 1 sleep 30); tid=$(json_field id "$out") +sleep 3 +contains "timeout fails the job" '"exitCode" : "timeout"' "$(Z describe -o json "$tid" --offline)" + +contains "service reload" "Configuration reloaded" "$(Z service reload)" +contains "clean via IPC" "Cleaned" "$(Z clean --all --include-failed)" +contains "service stop" "Zag service stopped" "$(Z service stop)" +contains "service status stopped" "stopped" "$(Z service status)" + +if [[ $fails -eq 0 ]]; then echo "all e2e checks passed"; else echo "$fails e2e check(s) failed"; exit 1; fi