// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `ci-agent`: what every job droplet runs. //! //! ```console //! ci-agent https://ci.example.org /root/ci-token //! ``` //! //! It asks the daemon what the droplet is for, sending along how long the //! boot took and where the time went, and then does it: //! //! * **A Forgejo job.** It writes the runner's configuration and runs //! `forgejo-runner one-job` for the one job the runner was registered for, //! which talks to the forge itself. //! * **A Radicle run.** It asks the daemon for the job and its source, //! unpacks the source, runs the script in the job image under podman, and //! sends every line of output back as it arrives -- or an empty piece //! every ten seconds when there is none, so that the daemon can tell a //! quiet script from a dead droplet -- then reports the script's exit //! status. //! //! Either way it then tells the daemon it is done, which destroys the droplet //! on its next pass, and exits; cloud-init powers the droplet off behind it //! in case that word never arrives. //! //! It is a static binary with no C in it, downloaded by the droplet at boot //! from the daemon it is about to talk to, and checked against a SHA-256 the //! droplet was created with. The daemon never connects to the droplet: every //! exchange here is a request the droplet makes, authenticated by a token //! that names this droplet and nothing else. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const api = @import("api"); const log = std.log.scoped(.agent); /// Where the source is unpacked. `/work` on a droplet; `CI_AGENT_WORK` /// moves it, which is for running the agent somewhere that is not one. const default_work_dir = "/work"; /// How often output is sent, and how often a heartbeat goes when there is /// none. The daemon gives up on a droplet after five minutes of silence. const flush_seconds = 10; /// Output is sent early once this much is waiting, so a noisy build does not /// make one enormous request. const flush_bytes = 256 * 1024; pub fn main(init: std.process.Init) !void { const io = init.io; const gpa = init.gpa; const arena = init.arena.allocator(); const args = try init.minimal.args.toSlice(arena); if (args.len != 3) { log.err("usage: ci-agent ", .{}); std.process.exit(2); } const token_text = try Io.Dir.cwd().readFileAlloc(io, args[2], arena, .limited(4096)); const token = std.mem.trim(u8, token_text, " \t\r\n"); var client: api.Client = .init(io, gpa, args[1], token, .bearer); defer client.deinit(); const work = init.environ_map.get("CI_AGENT_WORK") orelse default_work_dir; const assignment = try claim(io, arena, &client); const exit_code: i32 = switch (assignment) { .forgejo => |f| forgejo(io, arena, init.environ_map, f, work) catch |err| blk: { log.err("forgejo job {s}: {s}", .{ f.handle, @errorName(err) }); break :blk 125; }, .radicle => try radicle(io, gpa, arena, &client, work), }; done(arena, &client, io, exit_code); } /// Asks for the droplet's work until there is some. The first call carries /// the boot report; the daemon keeps the first it is given, so a retry is /// harmless. fn claim(io: Io, arena: Allocator, client: *api.Client) !api.droplet.Assignment { var body: Io.Writer.Allocating = .init(arena); try std.json.Stringify.value(api.droplet.Claim{ .uptime_seconds = uptime(io), .boot_report = bootReport(io, arena), }, .{}, &body.writer); while (true) { const response = client.request(arena, .post, "/droplet/v1/claim", body.written()) catch |err| { // The daemon restarting, or the network having a bad minute: the // daemon destroys a droplet that never claims, so waiting on is // the right thing and never forever. log.warn("claim: {s}; asking again", .{@errorName(err)}); try Io.sleep(io, .fromSeconds(5), .awake); continue; }; switch (response.status) { .ok => return response.json(api.droplet.Assignment, arena, "claim"), // Nothing yet: the daemon held the request, and it is asked again. .no_content => continue, else => { _ = response.ok("claim") catch {}; // Gone or unauthorized: the droplet is no longer wanted. if (response.status == .gone or response.status == .unauthorized) return error.NotWanted; try Io.sleep(io, .fromSeconds(5), .awake); }, } } } /// Whole seconds since the kernel started, or null if it cannot be read. fn uptime(io: Io) ?i64 { var buf: [64]u8 = undefined; const text = Io.Dir.cwd().readFile(io, "/proc/uptime", &buf) catch return null; const end = std.mem.findScalar(u8, text, '.') orelse std.mem.findScalar(u8, text, ' ') orelse return null; return std.fmt.parseInt(i64, text[0..end], 10) catch null; } /// Where the boot's time went, as systemd and cloud-init tell it, for a /// person to read in the droplet's record. Whatever cannot be run is left /// out: the report is a help, never a reason to fail. fn bootReport(io: Io, arena: Allocator) ?[]const u8 { const commands = [_][]const []const u8{ // Monotonic timestamps, in microseconds since the kernel started, of // the milestones between boot and this agent. &.{ "systemctl", "show", "--property=Id,ActiveEnterTimestampMonotonic", "systemd-networkd-wait-online.service", "network-online.target", "cloud-init-local.service", "cloud-init.service", "cloud-config.service", "cloud-final.service", "snapd.seeded.service", "podman.socket" }, &.{ "systemd-analyze", "blame", "--no-pager" }, // Which resolvers the droplet ended up with, and how long one lookup // of a name every job needs takes through them. &.{ "resolvectl", "dns" }, &.{ "resolvectl", "query", "cache.nixos.org" }, &.{ "cloud-init", "analyze", "blame" }, }; var out: Io.Writer.Allocating = .init(arena); for (commands) |argv| { const result = std.process.run(arena, io, .{ .argv = argv, .stdout_limit = .limited(256 * 1024), .stderr_limit = .limited(16 * 1024), }) catch continue; out.writer.print("$ {s}\n", .{std.mem.join(arena, " ", argv) catch continue}) catch return null; // The top of a blame is what matters, and it is long. var lines = std.mem.splitScalar(u8, result.stdout, '\n'); var n: usize = 0; while (lines.next()) |line| : (n += 1) { if (n == 40) break; out.writer.print("{s}\n", .{line}) catch return null; } out.writer.writeByte('\n') catch return null; } return out.written(); } /// Runs the Forgejo job this droplet was made for, and returns the runner's /// exit status. Its output goes to this process's, which cloud-init logs: /// the job's own log is on the forge, where the runner sends it. fn forgejo(io: Io, arena: Allocator, environ: *const std.process.Environ.Map, f: api.droplet.Forgejo, work: []const u8) !i32 { log.info("forgejo job {s} on {s}, in {s}", .{ f.handle, f.url, f.image }); try Io.Dir.cwd().createDirPath(io, work); // forgejo-runner speaks the docker API; podman's socket provides it. const socket = try std.process.run(arena, io, .{ .argv = &.{ "systemctl", "enable", "--now", "podman.socket" } }); if (socket.term != .exited or socket.term.exited != 0) { log.err("starting podman.socket: {s}", .{socket.stderr}); return error.PodmanSocket; } // The run-agent script loaded the module and widened the node's mode. const kvm = if (Io.Dir.cwd().access(io, "/dev/kvm", .{})) true else |_| false; var config: Io.Writer.Allocating = .init(arena); try api.droplet.runnerConfig(&config.writer, f.nix_config, kvm); const config_path = try std.fs.path.join(arena, &.{ work, "runner-config.yaml" }); const token_path = try std.fs.path.join(arena, &.{ work, "runner-token" }); try Io.Dir.cwd().writeFile(io, .{ .sub_path = config_path, .data = config.written(), .flags = .{ .permissions = .fromMode(0o600) } }); try Io.Dir.cwd().writeFile(io, .{ .sub_path = token_path, .data = f.runner_token, .flags = .{ .permissions = .fromMode(0o600) } }); var env = try environ.clone(arena); try env.put("DOCKER_HOST", "unix:///run/podman/podman.sock"); var child = try std.process.spawn(io, .{ .argv = &.{ "/usr/local/bin/forgejo-runner", "one-job", "--config", config_path, "--url", f.url, "--uuid", f.runner_uuid, "--token-url", try std.mem.concat(arena, u8, &.{ "file:", token_path }), "--handle", f.handle, "--label", try std.mem.concat(arena, u8, &.{ f.label, ":docker://", f.image }), "--wait", }, .environ_map = &env, .stdin = .ignore, }); defer child.kill(io); const code = exitCode(try child.wait(io)); log.info("forgejo job {s}: runner exited with status {d}", .{ f.handle, code }); return code; } /// A Radicle run: fetch the job and its source, run it, and report its /// result. The exit status is the script's. fn radicle(io: Io, gpa: Allocator, arena: Allocator, client: *api.Client, work: []const u8) !i32 { const job = try fetchJob(arena, client); log.info("run {d}: {s} at {s}, in {s}", .{ job.id, job.rid, job.commit, job.image }); const dirs: Dirs = .{ .repo = try std.fs.path.join(arena, &.{ work, "repo" }), .source = try std.fs.path.join(arena, &.{ work, "source.tar.gz" }), }; var sender: Sender = .{ .client = client, .io = io }; const exit_code = run(io, gpa, arena, client, &sender, job, dirs) catch |err| blk: { // Whatever went wrong before or around the script goes into the log, // where the person reading the run's page will look for it. var buf: [256]u8 = undefined; const line = std.fmt.bufPrint(&buf, "\nci-agent: {s}\n", .{@errorName(err)}) catch "\nci-agent: failed\n"; sender.send(arena, line); break :blk 125; }; try report(arena, client, io, exit_code); return exit_code; } fn exitCode(term: std.process.Child.Term) i32 { return switch (term) { .exited => |code| code, .signal => |sig| 128 + @as(i32, @intCast(@intFromEnum(sig))), else => 125, }; } fn fetchJob(arena: Allocator, client: *api.Client) !api.droplet.Job { const response = try client.request(arena, .get, "/droplet/v1/job", null); return response.json(api.droplet.Job, arena, "fetch job"); } const Dirs = struct { repo: []const u8, source: []const u8 }; fn run(io: Io, gpa: Allocator, arena: Allocator, client: *api.Client, sender: *Sender, job: api.droplet.Job, dirs: Dirs) !i32 { try Io.Dir.cwd().createDirPath(io, dirs.repo); const source = try (try client.request(arena, .get, "/droplet/v1/source", null)).ok("fetch source"); try Io.Dir.cwd().writeFile(io, .{ .sub_path = dirs.source, .data = source }); const untar = try std.process.run(arena, io, .{ .argv = &.{ "tar", "-xzf", dirs.source, "-C", dirs.repo } }); if (untar.term != .exited or untar.term.exited != 0) { sender.send(arena, untar.stderr); return error.UnpackFailed; } // The same device the Forgejo droplets pass: cloud-init has already // loaded the module and widened the node's mode for the build user. const kvm = if (Io.Dir.cwd().access(io, "/dev/kvm", .{})) true else |_| false; var argv: std.ArrayList([]const u8) = .empty; // stderr joined to stdout by the shell, so the log reads in the order // things happened rather than as two streams side by side. try argv.appendSlice(arena, &.{ "sh", "-c", "exec \"$@\" 2>&1", "sh" }); try argv.appendSlice(arena, &.{ "podman", "run", "--rm", "--volume", try std.mem.concat(arena, u8, &.{ dirs.repo, ":/work/repo" }), "--workdir", "/work/repo" }); if (kvm) try argv.appendSlice(arena, &.{ "--device", "/dev/kvm" }); if (job.nix_config.len > 0) try argv.appendSlice(arena, &.{ "--env", try std.mem.concat(arena, u8, &.{ "NIX_CONFIG=", job.nix_config }) }); try argv.appendSlice(arena, &.{ job.image, "bash", "-eo", "pipefail", "-c", job.shell }); var child = try std.process.spawn(io, .{ .argv = argv.items, .stdin = .ignore, .stdout = .pipe, .stderr = .inherit }); defer child.kill(io); var buffers: Io.File.MultiReader.Buffer(1) = undefined; var multi: Io.File.MultiReader = undefined; multi.init(gpa, io, buffers.toStreams(), &.{child.stdout.?}); defer multi.deinit(); const output = multi.reader(0); while (true) { const ended = if (multi.fill(1, .{ .duration = .{ .raw = .fromSeconds(flush_seconds), .clock = .awake } })) |_| false else |err| switch (err) { error.EndOfStream => true, error.Timeout => false, else => return err, }; const pending = output.buffered(); if (ended or pending.len >= flush_bytes or sender.due(io)) { sender.send(arena, pending); output.toss(pending.len); } if (ended) break; } return exitCode(try child.wait(io)); } /// Sends numbered pieces of log. A piece that fails is retried; the daemon /// stores each number once, so a piece that arrived but whose answer was lost /// is harmless to send again. const Sender = struct { client: *api.Client, io: Io, seq: u64 = 0, last: ?Io.Timestamp = null, fn due(s: *const Sender, io: Io) bool { const last = s.last orelse return true; return last.untilNow(io, .awake).toSeconds() >= flush_seconds; } fn send(s: *Sender, arena: Allocator, bytes: []const u8) void { s.seq += 1; s.last = Io.Timestamp.now(s.io, .awake); const path = std.fmt.allocPrint(arena, "/droplet/v1/log?seq={d}", .{s.seq}) catch return; retry(s.io, "send log", struct { fn attempt(c: *api.Client, a: Allocator, p: []const u8, b: []const u8) !void { _ = try (try c.request(a, .post, p, b)).ok("send log"); } }.attempt, .{ s.client, arena, path, bytes }); } }; fn report(arena: Allocator, client: *api.Client, io: Io, exit_code: i32) !void { var body: Io.Writer.Allocating = .init(arena); try std.json.Stringify.value(api.droplet.Outcome{ .exit_code = exit_code }, .{}, &body.writer); log.info("exit status {d}", .{exit_code}); retry(io, "report result", struct { fn attempt(c: *api.Client, a: Allocator, b: []const u8) !void { _ = try (try c.request(a, .post, "/droplet/v1/result", b)).ok("report result"); } }.attempt, .{ client, arena, body.written() }); } /// Tells the daemon the droplet's work is over, so that it is destroyed now /// rather than when the daemon next notices. fn done(arena: Allocator, client: *api.Client, io: Io, exit_code: i32) void { var body: Io.Writer.Allocating = .init(arena); std.json.Stringify.value(api.droplet.Outcome{ .exit_code = exit_code }, .{}, &body.writer) catch return; retry(io, "report done", struct { fn attempt(c: *api.Client, a: Allocator, b: []const u8) !void { _ = try (try c.request(a, .post, "/droplet/v1/done", b)).ok("report done"); } }.attempt, .{ client, arena, body.written() }); } /// Six attempts over about a minute. Past that the daemon will notice the /// silence on its own and fail the run, which is the right outcome for a /// droplet that cannot reach it. fn retry(io: Io, what: []const u8, comptime attempt: anytype, args: anytype) void { var delay: i64 = 2; for (0..6) |_| { if (@call(.auto, attempt, args)) |_| return else |err| log.warn("{s}: {s}; retrying in {d}s", .{ what, @errorName(err), delay }); Io.sleep(io, .fromSeconds(delay), .awake) catch return; delay = @min(delay * 2, 20); } log.err("{s}: giving up", .{what}); }