feat: systemd/launchd service install, managed start/stop, install.sh (M6)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Sonnet 5.5 committed 2026-10-17 13:50:24 +01:00
1 parent 9d08e4d3fd
commit c5faf8a682
6 files changed
+592 -7

No files matched your search

+180 -5
View File
@@ -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> 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