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:
1 parent
35106d405b
commit
9d08e4d3fd
13 files changed
+2147
-68
No files matched your search
@@ -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 (<data dir>/logs/zag.log).
|
||||
\\
|
||||
\\Options:
|
||||
\\ -f, --follow Keep printing new lines (Ctrl+C to stop)
|
||||
\\ -n, --lines <n> 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 <path>
|
||||
\\
|
||||
\\Check a configuration file for syntax errors, unknown sections or keys, and bad values.
|
||||
\\Exits 1 if anything is wrong.
|
||||
\\
|
||||
\\Options:
|
||||
\\ -f, --file <path> File to validate (required)
|
||||
\\
|
||||
;
|
||||
|
||||
pub fn cmdConfigValidate(ctx: *Context) !u8 {
|
||||
const path = ctx.value("file") orelse return ctx.usageError("Missing required option: --file <path>", .{});
|
||||
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 <file> 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 <dir> 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<COMP_CWORD; i++)); do
|
||||
\\ case "${COMP_WORDS[i]}" in
|
||||
\\ -o|--output|--config|--barn-dir) ((i++)) ;;
|
||||
\\ -*) ;;
|
||||
\\ *) if [[ -z "$cmd" ]]; then cmd="${COMP_WORDS[i]}"; elif [[ -z "$sub" ]]; then sub="${COMP_WORDS[i]}"; fi ;;
|
||||
\\ esac
|
||||
\\ done
|
||||
\\ case "$prev" in
|
||||
\\ -o|--output) COMPREPLY=( $(compgen -W "human json xml" -- "$cur") ); return ;;
|
||||
\\ -s|--state) COMPREPLY=( $(compgen -W "queued running succeeded failed canceled killed" -- "$cur") ); return ;;
|
||||
\\ -l|--load-level) COMPREPLY=( $(compgen -W "high medium low" -- "$cur") ); return ;;
|
||||
\\ --config|--barn-dir|-d|--directory|-p|--path|-f|--file) COMPREPLY=( $(compgen -f -- "$cur") ); return ;;
|
||||
\\ esac
|
||||
\\ if [[ -z "$cmd" ]]; then
|
||||
\\ COMPREPLY=( $(compgen -W "$cmds $global" -- "$cur") ); return
|
||||
\\ fi
|
||||
\\ local opts="$global"
|
||||
\\ case "$cmd" in
|
||||
\\ run) opts="$opts -t --tag -l --load-level --max-retries --retry-delay --timeout" ;;
|
||||
\\ status) opts="$opts -t --tag -s --state -n --limit" ;;
|
||||
\\ describe) opts="$opts --logs --manifest" ;;
|
||||
\\ usage) opts="$opts -n --limit --csv --summary" ;;
|
||||
\\ kill) opts="$opts -f --force -q --quiet" ;;
|
||||
\\ clean) opts="$opts --all --older-than --include-failed --dry-run --job-id" ;;
|
||||
\\ autocompletion) opts="$opts --bash --zsh" ;;
|
||||
\\ service)
|
||||
\\ if [[ -z "$sub" ]]; then COMPREPLY=( $(compgen -W "start stop restart reload status logs" -- "$cur") ); return; fi
|
||||
\\ case "$sub" in
|
||||
\\ start) opts="$opts -f --foreground" ;;
|
||||
\\ stop|restart) opts="$opts -f --force" ;;
|
||||
\\ logs) opts="$opts -f --follow -n --lines" ;;
|
||||
\\ esac ;;
|
||||
\\ config)
|
||||
\\ if [[ -z "$sub" ]]; then COMPREPLY=( $(compgen -W "show validate init install" -- "$cur") ); return; fi
|
||||
\\ case "$sub" in
|
||||
\\ show) opts="$opts --defaults" ;;
|
||||
\\ validate) opts="$opts -f --file" ;;
|
||||
\\ init) opts="$opts -p --path -f --force" ;;
|
||||
\\ install) opts="$opts -d --directory -f --force --show" ;;
|
||||
\\ esac ;;
|
||||
\\ esac
|
||||
\\ COMPREPLY=( $(compgen -W "$opts" -- "$cur") )
|
||||
\\}
|
||||
\\complete -F _zag zag
|
||||
\\
|
||||
;
|
||||
|
||||
pub fn cmdAutocompletion(ctx: *Context) !u8 {
|
||||
const zsh = ctx.flag("zsh");
|
||||
if (!ctx.flag("bash") and !zsh) {
|
||||
try ctx.stdout.writeAll(autocompletion_usage);
|
||||
return exit_ok;
|
||||
}
|
||||
if (zsh) try ctx.stdout.writeAll("#compdef zag\n\n# Zsh completion for zag\n# Generated by zag autocompletion --zsh\n\nautoload -U +X bashcompinit && bashcompinit\n\n");
|
||||
try ctx.stdout.writeAll(bash_completion);
|
||||
return exit_ok;
|
||||
}
|
||||
Reference in new issue
Block a user