CI / test (pull_request) Successful in 3m20s
Completes issue #2 on top of the phase-1 strict single-job FIFO scheduler. Removed: - Job.load_level / Manifest.load_level / CreateOptions.load_level and the manifest.json loadLevel field (old manifests still parse: unknown fields are ignored) - loadLevel in job JSON and <load_level> in XML output (field order shifts; old JSON still parses) - the [load_levels] config section, service.max_concurrent_jobs, ZAG_LOAD_LEVELS_*/ZAG_LOADLEVELS_*/ZAG_SERVICE_MAX_CONCURRENT_JOBS env vars, loadlevel.zig / loadclass.zig and the default .load files Friendly deprecation: old configs and environments still load fine. config validate and config show report the removed settings as non-fatal warnings (validate exit 1 stays reserved for real errors) and the CLI/daemon logs them once at startup. --load-level is gone from zag run; old IPC clients sending loadLevel are simply ignored. e2e: wait_state is now portable to macOS bash 3.2 (it silently skipped three checks before) and a serial-execution check asserts the second job stays QUEUED while the first runs and both finish in FIFO order. README and AGENTS.md document the deviation from barn.
881 lines
38 KiB
Zig
881 lines
38 KiB
Zig
//! 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 jsonpretty = @import("jsonpretty.zig");
|
|
const servicemgr = @import("servicemgr.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, 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;
|
|
}
|
|
|
|
fn installedManager(ctx: *Context) !?servicemgr.Installed {
|
|
return servicemgr.detectInstalled(ctx.io, ctx.arena, ctx.env);
|
|
}
|
|
|
|
/// Polls until the daemon's pid file names a live process (or `want_running` is false and it died).
|
|
fn waitForDaemon(ctx: *Context, dirs: *dirs_mod.Dirs, want_running: bool, timeout_ms: u64) ?i64 {
|
|
var waited: u64 = 0;
|
|
while (waited <= timeout_ms) : (waited += 100) {
|
|
const pid = daemon.runningPid(ctx.io, dirs);
|
|
if (want_running and pid != null) return pid;
|
|
if (!want_running and pid == null) return 0;
|
|
ctx.io.sleep(.fromMilliseconds(100), .real) catch break;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
fn managerFail(ctx: *Context, inst: servicemgr.Installed, verb: []const u8, code: u8) u8 {
|
|
return ctx.fail("{s} could not {s} the service (exit code {d})", .{ inst.managerName(), verb, code });
|
|
}
|
|
|
|
fn startManaged(ctx: *Context, inst: servicemgr.Installed) !u8 {
|
|
var dirs = try ctx.openDirs();
|
|
defer dirs.close(ctx.io);
|
|
const code = try servicemgr.control(ctx.io, ctx.gpa, ctx.arena, inst, .start);
|
|
if (code != 0) return managerFail(ctx, inst, "start", code);
|
|
const pid = waitForDaemon(ctx, &dirs, true, 10_000) orelse
|
|
return ctx.fail("Zag service did not come up within 10 seconds; check the {s} logs (zag service logs)", .{inst.managerName()});
|
|
try ctx.stdout.print("Zag service started (PID: {d}, managed by {s})\n", .{ pid, inst.managerName() });
|
|
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")) {
|
|
if (try installedManager(ctx)) |inst| return startManaged(ctx, inst);
|
|
return startBackground(ctx);
|
|
}
|
|
|
|
logging.setFromConfig(cfg.service.log_level);
|
|
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,
|
|
.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");
|
|
if (try installedManager(ctx)) |inst| {
|
|
if (daemon.runningPid(ctx.io, &dirs) == null) {
|
|
if (force) {
|
|
try ctx.stdout.writeAll("Zag service was not running\n");
|
|
return exit_ok;
|
|
}
|
|
return ctx.fail("Zag service is not running", .{});
|
|
}
|
|
if (force) _ = try servicemgr.control(ctx.io, ctx.gpa, ctx.arena, inst, .kill_force);
|
|
const code = try servicemgr.control(ctx.io, ctx.gpa, ctx.arena, inst, .stop);
|
|
if (code != 0) return managerFail(ctx, inst, "stop", code);
|
|
_ = waitForDaemon(ctx, &dirs, false, 60_000) orelse return ctx.fail("Zag service is still shutting down (waiting for running jobs)", .{});
|
|
try ctx.stdout.writeAll(if (force) "Zag service force stopped\n" else "Zag service stopped\n");
|
|
return exit_ok;
|
|
}
|
|
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 {
|
|
if (try installedManager(ctx)) |inst| {
|
|
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", .{});
|
|
if (ctx.flag("force")) _ = try servicemgr.control(ctx.io, ctx.gpa, ctx.arena, inst, .kill_force);
|
|
const code = try servicemgr.control(ctx.io, ctx.gpa, ctx.arena, inst, .restart);
|
|
if (code != 0) return managerFail(ctx, inst, "restart", code);
|
|
_ = waitForDaemon(ctx, &dirs, true, 15_000) orelse return ctx.fail("Zag service did not come back within 15 seconds", .{});
|
|
try ctx.stdout.writeAll("Zag service restarted\n");
|
|
return exit_ok;
|
|
}
|
|
{
|
|
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);
|
|
const managed_by: ?[]const u8 = if (try installedManager(ctx)) |inst| inst.managerName() else null;
|
|
|
|
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}{s}{s}{s}\n", .{
|
|
if (pid != null) "running" else "stopped",
|
|
if (managed_by != null) " (" else "",
|
|
managed_by orelse "",
|
|
if (managed_by != null) " managed)" else "",
|
|
});
|
|
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));
|
|
if (managed_by) |mb| try m.put("managed_by", Node.str(mb));
|
|
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);
|
|
var log_path: []const u8 = try std.fmt.allocPrint(ctx.arena, "{s}/{s}", .{ dirs.base_path, dirs_mod.daemon_log });
|
|
|
|
if (try installedManager(ctx)) |inst| switch (inst.kind) {
|
|
.systemd => {
|
|
// Under systemd the daemon logs to the journal.
|
|
var argv: std.ArrayList([]const u8) = .empty;
|
|
try argv.append(ctx.arena, "journalctl");
|
|
if (inst.scope == .user) try argv.append(ctx.arena, "--user");
|
|
try argv.appendSlice(ctx.arena, &.{ "-u", servicemgr.service_name, "-n", try std.fmt.allocPrint(ctx.arena, "{d}", .{lines}), "--no-pager" });
|
|
if (ctx.flag("follow")) try argv.append(ctx.arena, "-f");
|
|
try ctx.stdout.flush();
|
|
var child = std.process.spawn(ctx.io, .{ .argv = argv.items }) catch |err|
|
|
return ctx.failWithCause(@errorName(err), "Could not run journalctl", .{});
|
|
const term = try child.wait(ctx.io);
|
|
return if (proc.exitCodeOf(term) == 0) exit_ok else exit_error;
|
|
},
|
|
.launchd => log_path = try servicemgr.launchdLogPath(ctx.arena, ctx.env, inst.scope),
|
|
};
|
|
|
|
var file = Io.Dir.cwd().openFile(ctx.io, log_path, .{}) 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;
|
|
}
|
|
}
|
|
}
|
|
|
|
// -- service install / uninstall -------------------------------------------------------
|
|
|
|
pub const service_install_opts = [_]args_mod.Opt{
|
|
.{ .long = "binary", .takes_value = true },
|
|
.{ .long = "user" },
|
|
.{ .long = "system" },
|
|
};
|
|
|
|
pub const service_install_usage =
|
|
\\Usage: zag service install [options]
|
|
\\
|
|
\\Install zag as a service that starts on boot: a systemd unit on Linux, a launchd job on
|
|
\\macOS. As root it installs system-wide; otherwise it installs for the current user.
|
|
\\--barn-dir and --config are recorded in the service definition when given.
|
|
\\
|
|
\\Options:
|
|
\\ --binary <path> Path to the zag binary (default: the running one)
|
|
\\ --user Install for the current user even when running as root
|
|
\\ --system Install system-wide (requires root)
|
|
\\
|
|
;
|
|
|
|
pub fn cmdServiceInstall(ctx: *Context) !u8 {
|
|
const kind = servicemgr.platformKind() orelse return ctx.fail("Service installation is not supported on this platform yet", .{});
|
|
if (kind == .systemd and !servicemgr.systemdAvailable(ctx.io)) return ctx.fail("Systemd is not available on this system", .{});
|
|
|
|
const scope: servicemgr.Scope = if (ctx.flag("user")) .user else if (ctx.flag("system")) .system else if (servicemgr.isRoot()) .system else .user;
|
|
if (scope == .system and !servicemgr.isRoot()) return ctx.fail("System-wide installation requires root privileges. Run with sudo, or use --user.", .{});
|
|
if (try installedManager(ctx)) |_| return ctx.fail("Zag service is already installed. Use 'zag service uninstall' first.", .{});
|
|
|
|
const exe = ctx.value("binary") orelse ctx.exe_path;
|
|
var extra: std.ArrayList([]const u8) = .empty;
|
|
if (ctx.value("barn-dir")) |d| try extra.appendSlice(ctx.arena, &.{ "--barn-dir", d });
|
|
if (ctx.value("config")) |c| try extra.appendSlice(ctx.arena, &.{ "--config", c });
|
|
|
|
{ // Make sure the data directory exists (the daemon would create it too).
|
|
var dirs = try ctx.openDirs();
|
|
dirs.close(ctx.io);
|
|
}
|
|
|
|
const path: []const u8, const content: []const u8 = switch (kind) {
|
|
.systemd => .{ try servicemgr.unitPath(ctx.arena, ctx.env, scope), try servicemgr.systemdUnit(ctx.arena, .{ .exe = exe, .extra_args = extra.items, .scope = scope }) },
|
|
.launchd => .{ try servicemgr.plistPath(ctx.arena, ctx.env, scope), try servicemgr.launchdPlist(ctx.arena, .{
|
|
.exe = exe,
|
|
.extra_args = extra.items,
|
|
.log_path = try servicemgr.launchdLogPath(ctx.arena, ctx.env, scope),
|
|
}) },
|
|
};
|
|
writeFileCreatingParents(ctx, path, content) catch |err|
|
|
return ctx.failWithCause(@errorName(err), "Failed to write {s}", .{path});
|
|
|
|
const inst: servicemgr.Installed = .{ .kind = kind, .scope = scope, .path = path };
|
|
for ([_]servicemgr.Action{ .daemon_reload, .enable }) |action| {
|
|
const code = try servicemgr.control(ctx.io, ctx.gpa, ctx.arena, inst, action);
|
|
if (code != 0) {
|
|
Io.Dir.cwd().deleteFile(ctx.io, path) catch {};
|
|
return managerFail(ctx, inst, "register", code);
|
|
}
|
|
}
|
|
|
|
const w = ctx.stdout;
|
|
try w.print("Zag installed as {s} {s}\n", .{ if (scope == .system) "system" else "user", if (kind == .systemd) "service (systemd)" else "job (launchd)" });
|
|
try w.print("{s}: {s}\n", .{ if (kind == .systemd) "Unit file" else "Plist", path });
|
|
try w.writeAll("The service starts automatically on boot");
|
|
if (kind == .systemd and scope == .user) try w.writeAll(" once you are logged in (run `loginctl enable-linger $USER` to start it at boot)");
|
|
try w.writeAll(".\n\nTo start now: zag service start\nTo uninstall: zag service uninstall\n");
|
|
return exit_ok;
|
|
}
|
|
|
|
pub const service_uninstall_usage =
|
|
\\Usage: zag service uninstall
|
|
\\
|
|
\\Stop the service and remove its systemd unit / launchd job.
|
|
\\
|
|
;
|
|
|
|
pub fn cmdServiceUninstall(ctx: *Context) !u8 {
|
|
const inst = (try installedManager(ctx)) orelse return ctx.fail("Zag service is not installed", .{});
|
|
if (inst.scope == .system and !servicemgr.isRoot()) return ctx.fail("Removing a system-wide service requires root privileges. Run with sudo.", .{});
|
|
|
|
_ = try servicemgr.control(ctx.io, ctx.gpa, ctx.arena, inst, .stop);
|
|
_ = try servicemgr.control(ctx.io, ctx.gpa, ctx.arena, inst, .disable);
|
|
Io.Dir.cwd().deleteFile(ctx.io, inst.path) catch |err|
|
|
return ctx.failWithCause(@errorName(err), "Failed to remove {s}", .{inst.path});
|
|
_ = try servicemgr.control(ctx.io, ctx.gpa, ctx.arena, inst, .daemon_reload);
|
|
try ctx.stdout.print("Zag service uninstalled ({s})\n", .{inst.path});
|
|
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, warnings: []const []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("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());
|
|
|
|
if (warnings.len > 0) {
|
|
const wn = try arena.alloc(Node, warnings.len);
|
|
for (warnings, wn) |msg, *n| n.* = Node.str(msg);
|
|
try root.put("warnings", .{ .list = wn });
|
|
}
|
|
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, ctx.config_deprecations.items));
|
|
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}\nheartbeat_interval_seconds = {d}\nipc_socket = {s}\nstale_heartbeat_threshold_seconds = {d}\n", .{
|
|
@tagName(cfg.service.log_level), 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,
|
|
});
|
|
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.
|
|
\\Deprecated settings are reported as warnings and do not affect the exit code.
|
|
\\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 }) });
|
|
}
|
|
|
|
var error_count: usize = 0;
|
|
for (list.items) |p| {
|
|
if (!p.is_warning) error_count += 1;
|
|
}
|
|
const warnings = try problemNodes(a, list.items, true);
|
|
const errors = try problemNodes(a, list.items, false);
|
|
|
|
if (ctx.format == .human) {
|
|
for (list.items) |p| if (p.is_warning) try ctx.stdout.print(" Warning: {s}\n", .{p.message});
|
|
if (error_count == 0) {
|
|
try ctx.stdout.print("Configuration is valid: {s}\n", .{path});
|
|
} else {
|
|
try ctx.stdout.print("\nConfiguration errors in {s}:\n\n", .{path});
|
|
for (list.items) |p| {
|
|
if (p.is_warning) continue;
|
|
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 {
|
|
var m = MapBuilder.init(a);
|
|
try m.put("valid", .{ .boolean = error_count == 0 });
|
|
try m.put("file", Node.str(path));
|
|
if (warnings.len > 0) try m.put("warnings", .{ .list = warnings });
|
|
if (error_count > 0) try m.put("errors", .{ .list = errors });
|
|
try ctx.emit(try m.done());
|
|
}
|
|
return if (error_count == 0) exit_ok else exit_error;
|
|
}
|
|
|
|
/// The JSON node list for the warnings or the errors of a problem list.
|
|
fn problemNodes(a: Allocator, list: []const config.Problem, warnings_only: bool) ![]Node {
|
|
var count: usize = 0;
|
|
for (list) |p| {
|
|
if (p.is_warning == warnings_only) count += 1;
|
|
}
|
|
if (count == 0) return a.alloc(Node, 0);
|
|
const nodes = try a.alloc(Node, count);
|
|
var i: usize = 0;
|
|
for (list) |p| {
|
|
if (p.is_warning != warnings_only) continue;
|
|
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));
|
|
nodes[i] = try em.done();
|
|
i += 1;
|
|
}
|
|
return nodes;
|
|
}
|
|
|
|
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 file (zag.conf) 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 ;;
|
|
\\ --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 --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 install uninstall" -- "$cur") ); return; fi
|
|
\\ case "$sub" in
|
|
\\ start) opts="$opts -f --foreground" ;;
|
|
\\ stop|restart) opts="$opts -f --force" ;;
|
|
\\ logs) opts="$opts -f --follow -n --lines" ;;
|
|
\\ install) opts="$opts --binary --user --system" ;;
|
|
\\ 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;
|
|
}
|