From c5faf8a68202d0f834621c6491bc78ed61b0bb68 Mon Sep 17 00:00:00 2001 From: Daniel Samson Date: Sat, 17 Oct 2026 13:50:24 +0100 Subject: [PATCH] feat: systemd/launchd service install, managed start/stop, install.sh (M6) Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 1 + install.sh | 69 ++++++++++ src/cli.zig | 8 +- src/cli_admin.zig | 185 ++++++++++++++++++++++++- src/root.zig | 1 + src/servicemgr.zig | 335 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 592 insertions(+), 7 deletions(-) create mode 100755 install.sh create mode 100644 src/servicemgr.zig diff --git a/AGENTS.md b/AGENTS.md index 9ae5e69..cee05fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,3 +63,4 @@ Guidance for AI coding agents working in `zag`, the Zig port of the | `src/cli_admin.zig` | `service ...`, `config ...`, `autocompletion` | | `src/main.zig` | Binary entry point | | `test/e2e.sh` | End-to-end smoke test (`zig build e2e`) | +| `src/servicemgr.zig` | systemd unit / launchd plist generation, install detection, manager commands | diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..7abcdbe --- /dev/null +++ b/install.sh @@ -0,0 +1,69 @@ +#!/bin/sh +# Install zag from a release and (optionally) register it as a service. +# +# curl -fsSL https://gitea.samson.media/samson-media/zag/raw/branch/main/install.sh | sh +# +# Environment: +# ZAG_VERSION release tag to install (default: latest) +# ZAG_TOKEN Gitea access token (the repository is private) +# ZAG_PREFIX install directory (default: /usr/local/bin as root, ~/.local/bin otherwise) +# ZAG_NO_SERVICE=1 skip `zag service install` +set -eu + +BASE="https://gitea.samson.media" +REPO="samson-media/zag" + +info() { printf '==> %s\n' "$*"; } +die() { printf 'error: %s\n' "$*" >&2; exit 1; } + +case "$(uname -s)" in + Linux) os=linux ;; + Darwin) os=macos ;; + *) die "unsupported OS: $(uname -s) (Windows is not supported yet)" ;; +esac +case "$(uname -m)" in + x86_64 | amd64) arch=x64 ;; + aarch64 | arm64) arch=arm64 ;; + *) die "unsupported architecture: $(uname -m)" ;; +esac + +auth="" +[ -n "${ZAG_TOKEN:-}" ] && auth="Authorization: token $ZAG_TOKEN" +fetch() { # fetch + if [ -n "$auth" ]; then curl -fsSL -H "$auth" -o "$2" "$1"; else curl -fsSL -o "$2" "$1"; fi +} + +version="${ZAG_VERSION:-}" +if [ -z "$version" ]; then + info "Looking up the latest release" + tmp_json=$(mktemp) + fetch "$BASE/api/v1/repos/$REPO/releases/latest" "$tmp_json" || die "could not query releases (is ZAG_TOKEN set?)" + version=$(sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$tmp_json" | head -1) + rm -f "$tmp_json" + [ -n "$version" ] || die "could not determine the latest version" +fi + +if [ -n "${ZAG_PREFIX:-}" ]; then + prefix=$ZAG_PREFIX +elif [ "$(id -u)" -eq 0 ]; then + prefix=/usr/local/bin +else + prefix="$HOME/.local/bin" +fi +mkdir -p "$prefix" + +asset="zag-$os-$arch" +tmp=$(mktemp) +info "Downloading $asset $version" +fetch "$BASE/$REPO/releases/download/$version/$asset" "$tmp" || die "download failed" +chmod +x "$tmp" +"$tmp" --version >/dev/null 2>&1 || die "downloaded binary does not run on this machine" +mv "$tmp" "$prefix/zag" +info "Installed $("$prefix/zag" --version) to $prefix/zag" + +case ":$PATH:" in *":$prefix:"*) ;; *) info "note: $prefix is not on your PATH" ;; esac + +if [ -z "${ZAG_NO_SERVICE:-}" ]; then + info "Registering the service" + "$prefix/zag" service install --binary "$prefix/zag" || info "service install failed; run 'zag service install' manually" +fi diff --git a/src/cli.zig b/src/cli.zig index c8380b0..74f3423 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -184,6 +184,8 @@ const commands = [_]Command{ .{ .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 = "service", .sub = "install", .summary = "Install zag as a system service", .usage = admin_cmds.service_install_usage, .opts = &admin_cmds.service_install_opts, .run = admin_cmds.cmdServiceInstall }, + .{ .name = "service", .sub = "uninstall", .summary = "Remove the system service", .usage = admin_cmds.service_uninstall_usage, .run = admin_cmds.cmdServiceUninstall }, .{ .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 }, @@ -203,7 +205,7 @@ const root_help = \\ 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) + \\ service Manage the zag service (start|stop|restart|reload|status|logs|install|uninstall) \\ config Configuration management (show|validate|init|install) \\ autocompletion Generate shell autocompletion scripts \\ @@ -218,7 +220,7 @@ const root_help = ; const service_help = - \\Usage: zag service + \\Usage: zag service \\ \\ start Start the zag service \\ stop Stop the zag service @@ -226,6 +228,8 @@ const service_help = \\ reload Reload configuration without stopping jobs \\ status Show service status \\ logs Show service logs + \\ install Install zag as a system service (systemd / launchd) + \\ uninstall Remove the system service \\ ; diff --git a/src/cli_admin.zig b/src/cli_admin.zig index f4676b3..4f48fd0 100644 --- a/src/cli_admin.zig +++ b/src/cli_admin.zig @@ -23,6 +23,7 @@ const Repository = @import("repository.zig").Repository; const state_mod = @import("state.zig"); const Classifier = @import("loadclass.zig").Classifier; const jsonpretty = @import("jsonpretty.zig"); +const servicemgr = @import("servicemgr.zig"); const exit_ok = cli.exit_ok; const exit_error = cli.exit_error; @@ -77,6 +78,37 @@ fn startBackground(ctx: *Context) !u8 { 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(); @@ -87,7 +119,10 @@ pub fn cmdServiceStart(ctx: *Context) !u8 { try ctx.stdout.writeAll("Zag service would be started (dry run)\n"); return exit_ok; } - if (!ctx.flag("foreground")) return startBackground(ctx); + if (!ctx.flag("foreground")) { + if (try installedManager(ctx)) |inst| return startManaged(ctx, inst); + return startBackground(ctx); + } logging.setFromConfig(cfg.service.log_level); const sys_dir = try config.systemConfigDir(ctx.arena, ctx.env); @@ -132,6 +167,21 @@ 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 => { @@ -161,6 +211,17 @@ pub const service_restart_usage = ; 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); @@ -217,6 +278,7 @@ pub fn cmdServiceStatus(ctx: *Context) !u8 { 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; @@ -256,7 +318,12 @@ pub fn cmdServiceStatus(ctx: *Context) !u8 { 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"}); + 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; @@ -294,6 +361,7 @@ pub fn cmdServiceStatus(ctx: *Context) !u8 { 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; } @@ -319,9 +387,26 @@ pub fn cmdServiceLogs(ctx: *Context) !u8 { 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 log_path: []const u8 = 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) { + 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; @@ -365,6 +450,95 @@ pub fn cmdServiceLogs(ctx: *Context) !u8 { } } +// -- 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 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" }}; @@ -666,11 +840,12 @@ const bash_completion = \\ 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 + \\ 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 diff --git a/src/root.zig b/src/root.zig index bbc0115..c147516 100644 --- a/src/root.zig +++ b/src/root.zig @@ -31,6 +31,7 @@ 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 servicemgr = @import("servicemgr.zig"); pub const query = @import("query.zig"); test { diff --git a/src/servicemgr.zig b/src/servicemgr.zig new file mode 100644 index 0000000..bc696eb --- /dev/null +++ b/src/servicemgr.zig @@ -0,0 +1,335 @@ +//! Integration with the OS service manager: systemd on Linux, launchd on macOS. +//! `zag service install` writes a unit/plist (system-wide as root, per-user otherwise); +//! once installed, `service start|stop|restart` go through the manager so it never fights a +//! hand-started daemon. +const std = @import("std"); +const builtin = @import("builtin"); +const Io = std.Io; +const Allocator = std.mem.Allocator; +const Environ = std.process.Environ; + +pub const service_name = "zag"; +pub const launchd_label = "com.samsonmedia.zag"; + +pub const Kind = enum { systemd, launchd }; +pub const Scope = enum { system, user }; + +pub const Installed = struct { + kind: Kind, + scope: Scope, + path: []const u8, + + pub fn managerName(self: Installed) []const u8 { + return switch (self.kind) { + .systemd => "systemd", + .launchd => "launchd", + }; + } +}; + +/// The service manager this platform uses, if any. +pub fn platformKind() ?Kind { + return switch (builtin.os.tag) { + .linux => .systemd, + .macos => .launchd, + else => null, + }; +} + +pub fn systemdAvailable(io: Io) bool { + if (builtin.os.tag != .linux) return false; + return if (Io.Dir.cwd().statFile(io, "/run/systemd/system", .{})) |_| true else |_| false; +} + +pub fn isRoot() bool { + return switch (builtin.os.tag) { + .linux => std.os.linux.geteuid() == 0, + .windows, .wasi => false, + else => std.c.geteuid() == 0, + }; +} + +fn home(env: *const Environ.Map) []const u8 { + return env.get("HOME") orelse ""; +} + +pub fn unitPath(arena: Allocator, env: *const Environ.Map, scope: Scope) Allocator.Error![]const u8 { + return switch (scope) { + .system => std.fmt.allocPrint(arena, "/etc/systemd/system/{s}.service", .{service_name}), + .user => std.fmt.allocPrint(arena, "{s}/.config/systemd/user/{s}.service", .{ home(env), service_name }), + }; +} + +pub fn plistPath(arena: Allocator, env: *const Environ.Map, scope: Scope) Allocator.Error![]const u8 { + return switch (scope) { + .system => std.fmt.allocPrint(arena, "/Library/LaunchDaemons/{s}.plist", .{launchd_label}), + .user => std.fmt.allocPrint(arena, "{s}/Library/LaunchAgents/{s}.plist", .{ home(env), launchd_label }), + }; +} + +fn exists(io: Io, path: []const u8) bool { + return if (Io.Dir.cwd().statFile(io, path, .{})) |_| true else |_| false; +} + +/// Looks for an installed unit/plist (system scope first). +pub fn detectInstalled(io: Io, arena: Allocator, env: *const Environ.Map) Allocator.Error!?Installed { + const kind = platformKind() orelse return null; + for ([_]Scope{ .system, .user }) |scope| { + const path = switch (kind) { + .systemd => try unitPath(arena, env, scope), + .launchd => try plistPath(arena, env, scope), + }; + if (exists(io, path)) return .{ .kind = kind, .scope = scope, .path = path }; + } + return null; +} + +/// Quotes an argument for a systemd `ExecStart=` line when it needs it. +fn systemdQuote(w: *Io.Writer, arg: []const u8) !void { + const plain = for (arg) |c| { + if (std.ascii.isWhitespace(c) or c == '"' or c == '\\' or c == '\'' or c == '$' or c == '%') break false; + } else true; + if (plain and arg.len > 0) return w.writeAll(arg); + try w.writeByte('"'); + for (arg) |c| switch (c) { + '"', '\\' => { + try w.writeByte('\\'); + try w.writeByte(c); + }, + '%' => try w.writeAll("%%"), + '$' => try w.writeAll("$$"), + else => try w.writeByte(c), + }; + try w.writeByte('"'); +} + +pub const UnitOptions = struct { + exe: []const u8, + /// Extra daemon arguments such as `--barn-dir ` or `--config `. + extra_args: []const []const u8 = &.{}, + scope: Scope, +}; + +/// systemd unit. The daemon runs in the foreground (`Type=simple`) and handles SIGTERM itself: +/// `KillMode=mixed` signals only the main process first so running jobs can drain, and systemd +/// kills the rest if it has not exited within `TimeoutStopSec`. No sandboxing is applied because +/// jobs run arbitrary commands that may need to write anywhere. +pub fn systemdUnit(arena: Allocator, o: UnitOptions) ![]u8 { + var aw: Io.Writer.Allocating = .init(arena); + const w = &aw.writer; + try w.print("[Unit]\nDescription=Zag Job Daemon{s}\nDocumentation=https://gitea.samson.media/samson-media/zag\n", .{if (o.scope == .user) " (user)" else ""}); + if (o.scope == .system) try w.writeAll("After=network.target\n"); + try w.writeAll("\n[Service]\nType=simple\nExecStart="); + try systemdQuote(w, o.exe); + for ([_][]const u8{ "service", "start", "--foreground" }) |a| { + try w.writeByte(' '); + try w.writeAll(a); + } + for (o.extra_args) |a| { + try w.writeByte(' '); + try systemdQuote(w, a); + } + try w.writeAll("\nExecReload=/bin/kill -HUP $MAINPID\nRestart=on-failure\nRestartSec=5\n"); + try w.writeAll("KillMode=mixed\nTimeoutStopSec=330\nSyslogIdentifier=zag\n"); + try w.print("\n[Install]\nWantedBy={s}\n", .{if (o.scope == .system) "multi-user.target" else "default.target"}); + return aw.toOwnedSlice(); +} + +fn xmlEscape(w: *Io.Writer, text: []const u8) !void { + for (text) |c| switch (c) { + '&' => try w.writeAll("&"), + '<' => try w.writeAll("<"), + '>' => try w.writeAll(">"), + else => try w.writeByte(c), + }; +} + +pub const PlistOptions = struct { + exe: []const u8, + extra_args: []const []const u8 = &.{}, + log_path: []const u8, +}; + +/// launchd plist. `KeepAlive` restarts the daemon only after a crash (a graceful exit through +/// `service stop` stays stopped). +pub fn launchdPlist(arena: Allocator, o: PlistOptions) ![]u8 { + var aw: Io.Writer.Allocating = .init(arena); + const w = &aw.writer; + try w.writeAll( + \\ + \\ + \\ + \\ + \\ Label + \\ + ); + try w.writeAll(launchd_label); + try w.writeAll("\n ProgramArguments\n \n"); + const all = [_][]const u8{ o.exe, "service", "start", "--foreground" }; + for (all) |a| { + try w.writeAll(" "); + try xmlEscape(w, a); + try w.writeAll("\n"); + } + for (o.extra_args) |a| { + try w.writeAll(" "); + try xmlEscape(w, a); + try w.writeAll("\n"); + } + try w.writeAll(" \n RunAtLoad\n \n"); + try w.writeAll(" KeepAlive\n \n SuccessfulExit\n \n \n"); + for ([_][]const u8{ "StandardOutPath", "StandardErrorPath" }) |key| { + try w.print(" {s}\n ", .{key}); + try xmlEscape(w, o.log_path); + try w.writeAll("\n"); + } + try w.writeAll("\n\n"); + return aw.toOwnedSlice(); +} + +/// Where launchd output goes: `/var/log/zag.log` for daemons, `~/Library/Logs/zag.log` for agents. +pub fn launchdLogPath(arena: Allocator, env: *const Environ.Map, scope: Scope) Allocator.Error![]const u8 { + return switch (scope) { + .system => "/var/log/zag.log", + .user => std.fmt.allocPrint(arena, "{s}/Library/Logs/zag.log", .{home(env)}), + }; +} + +pub const Action = enum { start, stop, restart, enable, disable, daemon_reload, kill_force, is_active }; + +/// The command lines implementing `action` for an installed service (one or two commands). +pub fn commandsFor(arena: Allocator, inst: Installed, action: Action) Allocator.Error![]const []const []const u8 { + var list: std.ArrayList([]const []const u8) = .empty; + switch (inst.kind) { + .systemd => { + const verb: []const u8 = switch (action) { + .start => "start", + .stop => "stop", + .restart => "restart", + .enable => "enable", + .disable => "disable", + .daemon_reload => "daemon-reload", + .kill_force => "kill", + .is_active => "is-active", + }; + var argv: std.ArrayList([]const u8) = .empty; + try argv.append(arena, "systemctl"); + if (inst.scope == .user) try argv.append(arena, "--user"); + try argv.append(arena, verb); + if (action == .kill_force) try argv.append(arena, "--signal=SIGKILL"); + if (action != .daemon_reload) try argv.append(arena, service_name); + try list.append(arena, try argv.toOwnedSlice(arena)); + }, + .launchd => switch (action) { + .start => try list.append(arena, try arena.dupe([]const u8, &.{ "launchctl", "start", launchd_label })), + .stop, .kill_force => try list.append(arena, try arena.dupe([]const u8, &.{ "launchctl", "stop", launchd_label })), + .restart => { + try list.append(arena, try arena.dupe([]const u8, &.{ "launchctl", "stop", launchd_label })); + try list.append(arena, try arena.dupe([]const u8, &.{ "launchctl", "start", launchd_label })); + }, + .enable => try list.append(arena, try arena.dupe([]const u8, &.{ "launchctl", "load", "-w", inst.path })), + .disable => try list.append(arena, try arena.dupe([]const u8, &.{ "launchctl", "unload", "-w", inst.path })), + .daemon_reload => {}, + .is_active => try list.append(arena, try arena.dupe([]const u8, &.{ "launchctl", "list", launchd_label })), + }, + } + return list.toOwnedSlice(arena); +} + +/// Runs the commands for `action`; returns the exit code of the first one that fails (0 if all pass). +pub fn control(io: Io, gpa: Allocator, arena: Allocator, inst: Installed, action: Action) !u8 { + for (try commandsFor(arena, inst, action)) |argv| { + const res = std.process.run(gpa, io, .{ .argv = argv }) catch return 127; + defer gpa.free(res.stdout); + defer gpa.free(res.stderr); + switch (res.term) { + .exited => |c| if (c != 0) return c, + else => return 1, + } + } + return 0; +} + +// -- tests ----------------------------------------------------------------------------- + +test "systemd system unit" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const unit = try systemdUnit(arena.allocator(), .{ .exe = "/usr/local/bin/zag", .scope = .system, .extra_args = &.{ "--barn-dir", "/var/lib/zag" } }); + try std.testing.expectEqualStrings( + \\[Unit] + \\Description=Zag Job Daemon + \\Documentation=https://gitea.samson.media/samson-media/zag + \\After=network.target + \\ + \\[Service] + \\Type=simple + \\ExecStart=/usr/local/bin/zag service start --foreground --barn-dir /var/lib/zag + \\ExecReload=/bin/kill -HUP $MAINPID + \\Restart=on-failure + \\RestartSec=5 + \\KillMode=mixed + \\TimeoutStopSec=330 + \\SyslogIdentifier=zag + \\ + \\[Install] + \\WantedBy=multi-user.target + \\ + , unit); +} + +test "systemd user unit quotes awkward paths" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const unit = try systemdUnit(arena.allocator(), .{ .exe = "/opt/my tools/zag", .scope = .user, .extra_args = &.{ "--config", "/home/a b/zag.conf" } }); + try std.testing.expect(std.mem.indexOf(u8, unit, "ExecStart=\"/opt/my tools/zag\" service start --foreground --config \"/home/a b/zag.conf\"\n") != null); + try std.testing.expect(std.mem.indexOf(u8, unit, "Description=Zag Job Daemon (user)") != null); + try std.testing.expect(std.mem.indexOf(u8, unit, "WantedBy=default.target") != null); + try std.testing.expect(std.mem.indexOf(u8, unit, "After=network.target") == null); +} + +test "launchd plist" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const plist = try launchdPlist(arena.allocator(), .{ .exe = "/usr/local/bin/zag", .extra_args = &.{ "--barn-dir", "/var/zag&co" }, .log_path = "/var/log/zag.log" }); + try std.testing.expect(std.mem.indexOf(u8, plist, "com.samsonmedia.zag") != null); + try std.testing.expect(std.mem.indexOf(u8, plist, "--foreground") != null); + try std.testing.expect(std.mem.indexOf(u8, plist, "/var/zag&co") != null); + try std.testing.expect(std.mem.indexOf(u8, plist, "SuccessfulExit") != null); + try std.testing.expect(std.mem.indexOf(u8, plist, "StandardOutPath\n /var/log/zag.log") != null); +} + +test "paths follow the scope" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var env = Environ.Map.init(std.testing.allocator); + defer env.deinit(); + try env.put("HOME", "/home/dan"); + try std.testing.expectEqualStrings("/etc/systemd/system/zag.service", try unitPath(a, &env, .system)); + try std.testing.expectEqualStrings("/home/dan/.config/systemd/user/zag.service", try unitPath(a, &env, .user)); + try std.testing.expectEqualStrings("/Library/LaunchDaemons/com.samsonmedia.zag.plist", try plistPath(a, &env, .system)); + try std.testing.expectEqualStrings("/home/dan/Library/LaunchAgents/com.samsonmedia.zag.plist", try plistPath(a, &env, .user)); + try std.testing.expectEqualStrings("/home/dan/Library/Logs/zag.log", try launchdLogPath(a, &env, .user)); +} + +test "manager commands" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const sys: Installed = .{ .kind = .systemd, .scope = .system, .path = "/etc/systemd/system/zag.service" }; + const usr: Installed = .{ .kind = .systemd, .scope = .user, .path = "x" }; + const lau: Installed = .{ .kind = .launchd, .scope = .user, .path = "/p/zag.plist" }; + + const start = try commandsFor(a, sys, .start); + try std.testing.expectEqualSlices([]const u8, &.{ "systemctl", "start", "zag" }, start[0]); + const user_stop = try commandsFor(a, usr, .stop); + try std.testing.expectEqualSlices([]const u8, &.{ "systemctl", "--user", "stop", "zag" }, user_stop[0]); + const reload = try commandsFor(a, sys, .daemon_reload); + try std.testing.expectEqualSlices([]const u8, &.{ "systemctl", "daemon-reload" }, reload[0]); + const kill = try commandsFor(a, sys, .kill_force); + try std.testing.expectEqualSlices([]const u8, &.{ "systemctl", "kill", "--signal=SIGKILL", "zag" }, kill[0]); + const restart = try commandsFor(a, lau, .restart); + try std.testing.expectEqual(@as(usize, 2), restart.len); + try std.testing.expectEqualSlices([]const u8, &.{ "launchctl", "load", "-w", "/p/zag.plist" }, (try commandsFor(a, lau, .enable))[0]); +}