Something went wrong. Try again.
Ephemeral DigitalOcean droplets for Forgejo Actions and Radicle CI, from one daemon
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The user data a job droplet boots with.//!//! The droplets are plain Ubuntu, not NixOS: cloud-init writes a script and//! runs it, and the script runs `ci-agent` and powers the machine off. When//! the droplet boots a prepared snapshot, podman and the runner binary are//! already baked in and the job image is already in local storage, so the//! apt run and the 1.7 GB pull are skipped -- that setup is the difference//! between a job starting in about a minute and about five.//!//! Every droplet's user data is the same but for its token: what the droplet//! is for -- a Forgejo job, a Radicle run -- is not decided here but handed//! to the agent when it asks, which keeps the forge's runner token out of the//! metadata service, where anything on the droplet could read it back.//!//! The droplets live in the ci team, which shares no VPC with the forge, so//! the forge and the registry are reached at their public addresses like//! anything else. An `/etc/hosts` entry pinning them to a private address//! never took effect when the Python provisioners tried it: the DigitalOcean//! image sets `manage_etc_hosts`, and cloud-init's `update_etc_hosts` rewrites//! the file after `write_files` has appended to it.
const std = @import("std");const Writer = std.Io.Writer;
pub const Error = error{UnsafeValue} || Writer.Error;
/// Every value interpolated below lands inside single quotes in a shell/// script, or on a line of YAML. One holding a quote or a line break would/// let whoever supplied it write the script, so it is refused rather than/// escaped.fn safe(value: []const u8) Error![]const u8 { if (value.len == 0) return error.UnsafeValue; for (value) |c| switch (c) { '\'', '\\', 0...0x1f, 0x7f => return error.UnsafeValue, else => {}, }; return value;}
/// An IP address, as far as its characters go: it lands in a TOML string as/// well as a shell script, and needs nothing but these.fn address(value: []const u8) Error![]const u8 { if (value.len == 0) return error.UnsafeValue; for (value) |c| switch (c) { '0'...'9', 'a'...'f', 'A'...'F', '.', ':' => {}, else => return error.UnsafeValue, }; return value;}
pub const Droplet = struct { /// Where the daemon's droplet API is: `https://ci.example.org`. public_url: []const u8, /// This droplet's token, which names it and nothing else. token: []const u8, /// The SHA-256 of the `ci-agent` the daemon serves, checked before it /// runs: the droplet trusts this user data, which came from the API call /// that created it, and not whatever answered the download. agent_sha256: []const u8, /// The static forgejo-runner a droplet booted from the stock image /// downloads, since it might be given a Forgejo job, and its SHA-256. runner_binary_url: []const u8, runner_binary_sha256: []const u8, /// Whether the droplet boots a prepared snapshot rather than the stock /// image. prepared: bool, /// See `Config.resolvers`. Each must already be an IP address. resolvers: []const []const u8 = &.{}, fallback_resolvers: []const []const u8 = &.{},};
pub fn droplet(w: *Writer, p: Droplet) Error!void { // DigitalOcean's vendor data is not wanted on a one-job droplet, and it // costs every boot about 25 seconds, most of it `install-dotty-agent` // fetching and installing the droplet agent, which serves the web // console. It also adds VPC-peering routes (not used), seeds entropy // (the kernel has its own), writes its VPC resolver into // resolved.conf.d (set below when `resolvers` is), and makes root the // login user. Without it, SSH is as `ubuntu`, with passwordless sudo; // nothing here needs SSH at all. Measured on a droplet booted from the // prepared snapshot: runcmd reached 16.8s after the kernel started // rather than about 42. try w.writeAll( \\#cloud-config \\vendor_data: \\ enabled: false \\ ); if (!p.prepared) try w.writeAll( \\package_update: true \\packages: \\ # podman, not docker.io: cloud03 runs jobs under podman and the \\ # nixos-runner image only works there. Under docker every exec fails \\ # with "openat etc/group: path escapes from parent" because docker \\ # resolves the image's absolute symlinks differently. Matching cloud03's \\ # runtime keeps one image working identically in both places. \\ - podman \\ ); try w.print( \\write_files: \\ - path: /root/ci-token \\ permissions: '0600' \\ content: | \\ {s} \\ , .{try safe(p.token)}); if (p.resolvers.len > 0) { // The droplet's own lookups, the runner's among them, go through // systemd-resolved, and the job's containers are handed podman's // list, which is otherwise resolved's upstream list with none of // this in it. `DNS=` lists add up across drop-ins, so an empty one // clears whatever an earlier file set -- a DigitalOcean.conf baked // into the snapshot, say -- and the fallbacks follow, for resolved to // move to if the first stops answering. try w.writeAll( \\ - path: /etc/systemd/resolved.conf.d/zz-ci.conf \\ content: | \\ [Resolve] \\ DNS= \\ DNS= ); for (p.resolvers, 0..) |r, i| try w.print("{s}{s}", .{ if (i > 0) " " else "", try address(r) }); for (p.fallback_resolvers) |r| try w.print(" {s}", .{try address(r)}); try w.writeAll( \\ \\ - path: /etc/containers/containers.conf.d/ci-dns.conf \\ content: | \\ [containers] \\ dns_servers = [ ); for (p.resolvers, 0..) |r, i| try w.print("{s}\"{s}\"", .{ if (i > 0) ", " else "", try address(r) }); for (p.fallback_resolvers) |r| try w.print(", \"{s}\"", .{try address(r)}); try w.writeAll("]\n"); } try w.writeAll( \\ - path: /root/run-agent.sh \\ permissions: '0755' \\ content: | \\ #!/usr/bin/env bash \\ # always power off, even on failure: a droplet that never does \\ # waits for the daemon to notice and destroy it \\ trap 'poweroff' EXIT \\ set -x \\ ); // resolved reads its drop-ins when it starts, which was before // cloud-init wrote this one. And each interface carries DigitalOcean's // resolver from the network configuration, which resolved would also // send every query to; taking the interfaces off the default route // leaves the global list above as the only one used. if (p.resolvers.len > 0) try w.writeAll( \\ systemctl restart systemd-resolved \\ for link in $(ls /sys/class/net); do \\ [ "$link" = lo ] || resolvectl default-route "$link" false \\ done \\ ); try w.writeAll( \\ # A job that boots a guest - a NixOS virtual machine test, most of \\ # them - needs /dev/kvm. DigitalOcean's droplets do have it: vmx is \\ # in cpuinfo and kvm_intel loads, and a NixOS test has been run on \\ # one to prove the nesting works rather than merely being \\ # advertised. The agent hands the device to the job's container. \\ # \\ # Passing the device is necessary and not sufficient. Nix runs \\ # builders as an unprivileged nixbld user, so it is uid 1001 that \\ # opens /dev/kvm, not the container's root - and the base image \\ # ships the node 0660 root:kvm where NixOS would make it 0666. What \\ # that costs is not an error: qemu takes the EACCES as "no KVM \\ # here", falls back to software emulation, and the machine boots \\ # too slowly for the test driver's timeouts, so the run ends in \\ # "Shell did not start in time" with the real cause thousands of \\ # lines above it. Widening the mode is safe on a droplet that runs \\ # one job for one repository and is then destroyed. podman copies \\ # the host's mode onto the node it creates inside the container, \\ # so this has to happen before one starts. \\ modprobe kvm_intel || modprobe kvm_amd || true \\ if [ -c /dev/kvm ]; then \\ chmod 0666 /dev/kvm \\ fi \\ ); if (p.prepared) { try w.writeAll(" # podman and forgejo-runner are baked into the snapshot\n"); } else { try w.print( \\ curl -fsSL -o /usr/local/bin/forgejo-runner \ \\ '{s}' \\ echo '{s} /usr/local/bin/forgejo-runner' | sha256sum -c - \\ chmod +x /usr/local/bin/forgejo-runner \\ , .{ try safe(p.runner_binary_url), try safe(p.runner_binary_sha256) }); } try w.print( \\ token=$(cat /root/ci-token) \\ curl -fsSL --retry 5 --retry-all-errors \ \\ -H "Authorization: Bearer $token" \ \\ -o /usr/local/bin/ci-agent '{s}/droplet/v1/agent' \\ echo '{s} /usr/local/bin/ci-agent' | sha256sum -c - \\ chmod +x /usr/local/bin/ci-agent \\ # not exec: that would discard the EXIT trap \\ /usr/local/bin/ci-agent '{s}' /root/ci-token \\runcmd: \\ - [ /root/run-agent.sh ] \\ , .{ try safe(p.public_url), try safe(p.agent_sha256), try safe(p.public_url) });}
pub const Builder = struct { runner_image: []const u8, runner_binary_url: []const u8, runner_binary_sha256: []const u8,};
/// Prepares a droplet to be snapshotted, then powers it off.////// Deliberately registers no runner and runs no job: the image is the/// starting point for every future job, so it must hold no credentials and/// nothing specific to one job.pub fn builder(w: *Writer, p: Builder) Error!void { try w.print( \\#cloud-config \\package_update: true \\packages: \\ - podman \\write_files: \\ - path: /root/prepare.sh \\ permissions: '0755' \\ content: | \\ #!/usr/bin/env bash \\ # power off no matter what: the builder waits for the droplet to \\ # stop, and a hang here would otherwise stall it until its timeout \\ trap 'poweroff' EXIT \\ set -eux \\ systemctl enable --now podman.socket \\ curl -fsSL -o /usr/local/bin/forgejo-runner '{s}' \\ echo '{s} /usr/local/bin/forgejo-runner' | sha256sum -c - \\ chmod +x /usr/local/bin/forgejo-runner \\ # the expensive part: pull the job image once, here, instead of once \\ # per job \\ podman pull '{s}' \\ podman images \\ # A droplet runs one job and is destroyed. Nothing that keeps a \\ # long-lived Ubuntu machine up to date has anything to do on one, \\ # and all of it would compete with the job for CPU, disk and \\ # network: apt's timers, unattended upgrades, snapd, the message \\ # of the day fetching news and changelogs, Ubuntu Pro's hooks. \\ # Masked, not merely disabled, so nothing starts them as a \\ # dependency. A unit this release does not have is skipped. \\ for unit in apt-daily.timer apt-daily-upgrade.timer apt-daily.service \ \\ apt-daily-upgrade.service unattended-upgrades.service \ \\ motd-news.timer motd-news.service apt-news.service esm-cache.service \ \\ ua-timer.timer ubuntu-advantage.service man-db.timer \ \\ snapd.service snapd.socket snapd.seeded.service \ \\ ModemManager.service multipathd.service multipathd.socket \ \\ fwupd-refresh.timer update-notifier-download.timer; do \\ systemctl mask "$unit" || true \\ done \\ # less for DigitalOcean to copy into every droplet \\ apt-get clean \\ fstrim -av || true \\ # so that a droplet's boot report shows its own boot rather than \\ # this one's \\ cloud-init clean --logs \\runcmd: \\ - [ /root/prepare.sh ] \\ , .{ try safe(p.runner_binary_url), try safe(p.runner_binary_sha256), try safe(p.runner_image) });}
const testing = std.testing;
const example: Droplet = .{ .public_url = "https://ci.jcollie.dev", .token = "abc123", .agent_sha256 = "0" ** 64, .runner_binary_url = "https://code.forgejo.org/forgejo/runner/releases/download/v13.1.0/forgejo-runner-13.1.0-linux-amd64", .runner_binary_sha256 = "29dae21e93f0eab5cdf3564008d44603c74770b41a4f4f1aceed172c774bc376", .prepared = true,};
fn render(p: Droplet) ![]u8 { var out: Writer.Allocating = .init(testing.allocator); errdefer out.deinit(); try droplet(&out.writer, p); return out.toOwnedSlice();}
test "a droplet's user data" { const text = try render(example); defer testing.allocator.free(text); try testing.expect(std.mem.startsWith(u8, text, "#cloud-config\nvendor_data:\n enabled: false\nwrite_files:\n")); try testing.expect(std.mem.indexOf(u8, text, " abc123\n") != null); try testing.expect(std.mem.indexOf(u8, text, "'https://ci.jcollie.dev/droplet/v1/agent'") != null); try testing.expect(std.mem.indexOf(u8, text, "/usr/local/bin/ci-agent 'https://ci.jcollie.dev' /root/ci-token\n") != null); try testing.expect(std.mem.indexOf(u8, text, "chmod 0666 /dev/kvm\n") != null); // a prepared snapshot has what the stock image has to fetch try testing.expect(std.mem.indexOf(u8, text, "packages:") == null); try testing.expect(std.mem.indexOf(u8, text, "forgejo-runner-13.1.0") == null);}
test "the stock image fetches podman and the runner" { var p = example; p.prepared = false; const text = try render(p); defer testing.allocator.free(text); try testing.expect(std.mem.indexOf(u8, text, "packages:\n") != null); try testing.expect(std.mem.indexOf(u8, text, " - podman\n") != null); try testing.expect(std.mem.indexOf(u8, text, "sha256sum -c -\n chmod +x /usr/local/bin/forgejo-runner\n") != null);}
test "resolvers reach both resolved and podman" { var p = example; p.resolvers = &.{"10.108.0.11"}; p.fallback_resolvers = &.{"67.207.67.3"}; const text = try render(p); defer testing.allocator.free(text); try testing.expect(std.mem.indexOf(u8, text, \\ - path: /etc/systemd/resolved.conf.d/zz-ci.conf \\ content: | \\ [Resolve] \\ DNS= \\ DNS=10.108.0.11 67.207.67.3 \\ - path: /etc/containers/containers.conf.d/ci-dns.conf \\ content: | \\ [containers] \\ dns_servers = ["10.108.0.11", "67.207.67.3"] \\ - path: /root/run-agent.sh ) != null); try testing.expect(std.mem.indexOf(u8, text, "set -x\n systemctl restart systemd-resolved\n") != null); try testing.expect(std.mem.indexOf(u8, text, "resolvectl default-route \"$link\" false\n") != null);
// none configured: nothing written, nothing restarted const plain = try render(example); defer testing.allocator.free(plain); try testing.expect(std.mem.indexOf(u8, plain, "resolved") == null);
p.resolvers = &.{"10.0.0.1\n - path: /etc/shadow"}; try testing.expectError(error.UnsafeValue, render(p)); p.resolvers = &.{"10.0.0.1\", \"8.8.8.8"}; try testing.expectError(error.UnsafeValue, render(p));}
test "a value that could escape its quotes is refused" { var p = example; p.public_url = "https://x'; rm -rf / #"; try testing.expectError(error.UnsafeValue, render(p)); p = example; p.token = "abc\n - path: /etc/shadow"; try testing.expectError(error.UnsafeValue, render(p)); p = example; p.token = ""; try testing.expectError(error.UnsafeValue, render(p));}
test "the snapshot builder's user data" { var out: Writer.Allocating = .init(testing.allocator); defer out.deinit(); try builder(&out.writer, .{ .runner_image = "git.jcollie.dev/jeff/nixos-runner:50-1-0dbdc124", .runner_binary_url = example.runner_binary_url, .runner_binary_sha256 = example.runner_binary_sha256, }); try testing.expectEqualStrings(@embedFile("golden/snapshot-builder.yaml"), out.written());}
test { std.testing.refAllDecls(@This());}