gitea: add VM-based actions runner class #1082

Merged
JakeHillion merged 1 commits from jj/nyqzyzvxxsoz into main 2026-05-06 17:11:58 +01:00
10 changed files with 485 additions and 2 deletions

No files matched your search

+1
View File
@@ -96,6 +96,7 @@
"qnaplcd" = final.callPackage ./pkgs/qnaplcd.nix { inherit qnaplcd-menu; };
"opencode-plugin" = final.callPackage ./pkgs/opencode-plugin { };
"oh-my-openagent" = final.callPackage ./pkgs/oh-my-openagent { };
"gitea-actions-vm-image" = final.callPackage ./pkgs/gitea-actions-vm-image { };
})
];
mkSystem = import ./lib/mkSystem.nix { inherit inputs; };
@@ -79,9 +79,13 @@
gitea.actions = {
enable = true;
tokenSecret = ../../modules/services/gitea/actions/boron.age;
capacity = 4;
capacity = 2;
dockerMemoryHigh = 12 * 1024 * 1024 * 1024; # 8 GiB
};
gitea.actions-vm = {
enable = true;
instances = 2;
};
matrix.mautrix_discord = true;
};
};
+2
View File
@@ -27,6 +27,7 @@
buildbot-worker = 411;
open-webui = 412;
mautrix-discord = 413;
gitea-actions-vm = 415;
## Consistent People
jake = 1000;
@@ -55,6 +56,7 @@
open-webui = 412;
mautrix-discord = 413;
mautrix-discord-registration = 414;
gitea-actions-vm = 415;
## Consistent Groups
mediaaccess = 1200;
+7 -1
View File
@@ -17,6 +17,11 @@ in
type = lib.types.str;
default = "/cache";
};
extraDirs = lib.mkOption {
type = with lib.types; listOf str;
default = [ ];
description = "Directories to persist on the cache mount (wiped on boot, on real storage in the meantime).";
};
};
extraDirs = lib.mkOption {
@@ -77,7 +82,8 @@ in
"${cfg.cache.path}/system" = {
hideMounts = true;
directories = (lib.lists.optional config.services.postgresqlBackup.enable config.services.postgresqlBackup.location);
directories = cfg.cache.extraDirs ++
(lib.lists.optional config.services.postgresqlBackup.enable config.services.postgresqlBackup.location);
};
})
];
@@ -0,0 +1,283 @@
{ config, lib, pkgs, ... }:
let
cfg = config.custom.services.gitea.actions-vm;
bridgeName = "br-runners";
bridgeCidr = "10.108.28.0/24";
bridgeAddress = "10.108.28.1";
bridgePrefix = 24;
vmIp = i: "10.108.28.${toString (10 + i)}";
vmMac = i: "52:54:00:7e:b1:${lib.fixedWidthString 2 "0" (lib.toHexString i)}";
instanceIds = lib.range 1 cfg.instances;
image = pkgs.gitea-actions-vm-image;
# Helper that runs inside ExecStart as the dynamic user. It registers a
# fresh ephemeral runner with Gitea, builds the small RUNNERSTATE ext4
# image consumed by the VM, creates a fresh qcow2 overlay backed by the
# read-only Nix-store base image, and finally execs into qemu.
runnerLauncher = i: pkgs.writeShellApplication {
name = "gitea-actions-vm-launch-${toString i}";
runtimeInputs = with pkgs; [
coreutils
gitea-actions-runner
qemu_kvm
util-linux
xorriso
];
text = ''
set -eu
work="$CACHE_DIRECTORY"
base="${image}/image.qcow2"
# Fresh overlay every start — recreating is cheap, and it guarantees
# no leakage of state from the previous job. The explicit 40G virtual
# size is what cloud-initramfs-growroot + systemd-growfs expand the
# in-VM rootfs to on first boot; without it the overlay inherits the
# base image's ~2 GiB, which fills up under any non-trivial job. The
# qcow2 is sparse, so this only consumes host disk as data is written.
rm -f "$work/overlay.qcow2"
qemu-img create -F qcow2 -b "$base" -f qcow2 "$work/overlay.qcow2" 40G
# Stage the cidata directory: cloud-init NoCloud reads meta-data and
# network-config; our in-VM runner service reads .runner + config.yaml.
# cloud-init silently ignores files it doesn't recognise.
stage="$work/cidata-stage"
rm -rf "$stage"
mkdir -p "$stage"
cat > "$stage/meta-data" <<EOF
instance-id: ${config.networking.hostName}-vm-${toString i}-$(date +%s)
local-hostname: ${config.networking.hostName}-vm-${toString i}
EOF
cat > "$stage/network-config" <<EOF
version: 2
ethernets:
primary:
match:
macaddress: "${vmMac i}"
addresses:
- ${vmIp i}/${toString bridgePrefix}
routes:
- to: default
via: ${bridgeAddress}
nameservers:
addresses: [1.1.1.1, 8.8.8.8]
EOF
# Empty user-data — we don't run cloud-init boot scripts.
: > "$stage/user-data"
(
cd "$stage"
act_runner register \
--no-interactive --ephemeral \
--instance "${cfg.giteaUrl}" \
--token "$(cat "$CREDENTIALS_DIRECTORY/token")" \
--name "${config.networking.hostName}-vm-${toString i}-$(date +%s)" \
--labels "${lib.concatStringsSep "," cfg.labels}"
cat > config.yaml <<EOF
log:
level: info
runner:
file: .runner
capacity: 1
fetch_timeout: 5s
fetch_interval: 2s
host:
# Pin the job workspace parent away from the runner state directory
# (/var/lib/gitea-runner) so the action can't see the .runner
# credential at a relative path. Default would be /root/.cache/act,
# which is already separate, but be explicit.
workdir_parent: /var/lib/gitea-runner-jobs
EOF
)
# ISO9660 with label cidata — recognised by cloud-init's NoCloud
# datasource. RO from the guest's perspective by virtue of the format.
xorriso -as mkisofs \
-output "$work/cidata.iso" \
-volid cidata \
-joliet -rock \
"$stage"
# Hand off to QEMU. We exec so systemd tracks the qemu pid as the unit's
# main process, and the VM's poweroff (issued by the in-VM runner unit
# after one job) translates to a clean unit exit + restart.
exec qemu-system-x86_64 \
-enable-kvm -cpu host \
-smp ${toString cfg.vcpus} \
-m ${toString cfg.memoryMiB} \
-drive file="$work/overlay.qcow2",if=virtio,cache=writeback,discard=unmap \
-drive file="$work/cidata.iso",if=virtio,format=raw,readonly=on \
-netdev tap,id=net0,br=${bridgeName},helper=/run/wrappers/bin/qemu-bridge-helper \
-device virtio-net-pci,netdev=net0,mac=${vmMac i} \
-device virtio-balloon-pci,free-page-reporting=on \
-device virtio-rng-pci \
-smbios type=1,serial=ds=nocloud \
-nographic -serial mon:stdio
'';
};
mkInstanceService = i: lib.nameValuePair "gitea-actions-vm-${toString i}" {
description = "Gitea Actions VM runner #${toString i}";
wantedBy = [ "multi-user.target" ];
# Wants= (not just After=) so the bridge services are guaranteed to be in
# the same activation transaction; without Wants= our After= is advisory.
after = [
"network-online.target"
"${bridgeName}-netdev.service"
"network-addresses-${bridgeName}.service"
];
wants = [
"network-online.target"
"${bridgeName}-netdev.service"
"network-addresses-${bridgeName}.service"
];
serviceConfig = {
Type = "simple";
ExecStart = "${runnerLauncher i}/bin/gitea-actions-vm-launch-${toString i}";
Restart = "always";
RestartSec = "5s";
User = "gitea-actions-vm";
Group = "gitea-actions-vm";
SupplementaryGroups = [ "kvm" ];
CacheDirectory = "gitea-actions-vm/${toString i}";
CacheDirectoryMode = "0700";
LoadCredential = "token:${config.age.secrets."gitea-actions-vm/token".path}";
DeviceAllow = [
"/dev/kvm rw"
"/dev/net/tun rw"
];
DevicePolicy = "closed";
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
# qemu execs qemu-bridge-helper, which carries cap_net_admin+ep — the
# kernel only grants those caps on exec when no_new_privs is unset.
NoNewPrivileges = false;
RestrictSUIDSGID = false;
};
};
in
{
options.custom.services.gitea.actions-vm = {
enable = lib.mkEnableOption "VM-based Gitea Actions runners";
instances = lib.mkOption {
type = lib.types.ints.between 1 16;
default = 1;
description = "Number of concurrent VM runners on this host.";
};
labels = lib.mkOption {
type = with lib.types; listOf str;
default = [ "ubuntu-26.04-vm" "ubuntu-vm" ];
description = ''
Labels advertised to Gitea by each runner. Note: no `:docker://...`
suffix — jobs run directly inside the VM, not in a nested Docker
container, since the VM itself provides isolation.
'';
};
memoryMiB = lib.mkOption {
type = lib.types.int;
default = 12 * 1024;
};
vcpus = lib.mkOption {
type = lib.types.int;
default = 6;
};
giteaUrl = lib.mkOption {
type = lib.types.str;
default = "https://gitea.hillion.co.uk";
};
};
config = lib.mkIf cfg.enable {
assertions = [{
assertion = pkgs.stdenv.hostPlatform.system == "x86_64-linux";
message = "custom.services.gitea.actions-vm requires x86_64-linux: the prebuilt image and qemu-system-x86_64 invocation are amd64-only.";
}];
users.users.gitea-actions-vm = {
uid = config.ids.uids.gitea-actions-vm;
group = "gitea-actions-vm";
isSystemUser = true;
};
users.groups.gitea-actions-vm.gid = config.ids.gids.gitea-actions-vm;
age.secrets."gitea-actions-vm/token" = {
rekeyFile = ./token.age;
mode = "0400";
};
# Place the per-instance overlays on /cache (wiped on boot, but on real
# SSD-backed storage in the meantime, not the tmpfs root). The disk-heavy
# qcow2 overlays therefore don't consume host RAM and don't fight the
# guest's virtio-balloon page reclaim.
custom.impermanence.cache.extraDirs = lib.mkIf
(config.custom.impermanence.enable && config.custom.impermanence.cache.enable)
[ "/var/cache/gitea-actions-vm" ];
# Bridge for runner VMs. The host owns ${bridgeAddress}; each VM gets
# a static IP injected via cloud-init's network-config on the cidata ISO.
networking.bridges.${bridgeName}.interfaces = [ ];
networking.interfaces.${bridgeName}.ipv4.addresses = [{
address = bridgeAddress;
prefixLength = bridgePrefix;
}];
networking.nat = {
enable = true;
externalInterface = "eth0";
internalInterfaces = [ bridgeName ];
};
# Drop any traffic from runner VMs to private RFC1918 / CGNAT space.
# Uses iptables extraCommands rather than nftables to coexist with the
# host's existing iptables-based firewall (the Gitea SSH redirect rules
# in modules/services/gitea/gitea.nix use the same mechanism, and mixing
# nftables.enable with networking.firewall.extraCommands fails the
# NixOS firewall assertion).
networking.firewall.extraCommands = ''
iptables -I FORWARD -i ${bridgeName} -d 10.0.0.0/8 -j DROP
iptables -I FORWARD -i ${bridgeName} -d 100.64.0.0/10 -j DROP
iptables -I FORWARD -i ${bridgeName} -d 172.16.0.0/12 -j DROP
iptables -I FORWARD -i ${bridgeName} -d 192.168.0.0/16 -j DROP
'';
networking.firewall.extraStopCommands = ''
iptables -D FORWARD -i ${bridgeName} -d 10.0.0.0/8 -j DROP 2>/dev/null || true
iptables -D FORWARD -i ${bridgeName} -d 100.64.0.0/10 -j DROP 2>/dev/null || true
iptables -D FORWARD -i ${bridgeName} -d 172.16.0.0/12 -j DROP 2>/dev/null || true
iptables -D FORWARD -i ${bridgeName} -d 192.168.0.0/16 -j DROP 2>/dev/null || true
'';
# SUID qemu-bridge-helper so the (DynamicUser) qemu process can attach
# its TAP to the bridge without holding CAP_NET_ADMIN itself.
security.wrappers."qemu-bridge-helper" = {
source = "${pkgs.qemu_kvm}/libexec/qemu-bridge-helper";
capabilities = "cap_net_admin+ep";
owner = "root";
group = "root";
};
environment.etc."qemu/bridge.conf".text = ''
allow ${bridgeName}
'';
systemd.services = lib.listToAttrs (map mkInstanceService instanceIds);
};
}
@@ -0,0 +1,9 @@
age-encryption.org/v1
-> X25519 A15qQYU59WJDxMLNAhDOipiDRkYSion17mFRe89u4VY
U8rCqJhhKgNHRj7dBdypqqG1ax0tglZugpsHuLoJYrE
-> O-grease )vU[} Tn2ihgwy Z-h%v
wuYgc53nyRGZyh48JeDRUHm+rh5c8RoZOwKmmsKlT9w4t6A/itZMHz50yRd0frK8
W0jdI4xTnK86SZ4imPj+dqe3jaZlLgXx6OU
--- kV1GBN38DOWiKUPKz3Q1LjY4qh6OSruBFN6S7uxq6D0
qĐéËŞu›‘Ď
MQˇ%ZK–ŰńV)2Ɇ×3�Őâú~—8q°+}K/#‰Ç~k°Đ×<†!«–b†Ś|Cł™čo lŁMÇËđő
+1
View File
@@ -3,6 +3,7 @@
{
imports = [
./actions.nix
./actions-vm
./gitea.nix
];
}
+136
View File
@@ -0,0 +1,136 @@
# Builds a customised Ubuntu 26.04 LTS qcow2 in the Nix store with the Gitea
# Actions runner binary and a boot-time systemd unit that runs act_runner
# ephemerally (one job, then power off).
#
# The base image is fetched as a fixed-output derivation. It is then mounted
# inside a vmTools.runInLinuxVM build VM, customised, and re-emitted at $out.
# Partition + filesystem auto-grow at first boot via cloud-initramfs-growroot
# (in the initramfs) and systemd-growfs (via the rootfs mount option), so the
# overlay's larger virtual size at runtime is picked up without manual resize.
{ lib
, runCommand
, fetchurl
, vmTools
, qemu
, util-linux
, e2fsprogs
, closureInfo
, gitea-actions-runner
, nodejs_24
,
}:
let
ubuntuImg = fetchurl {
url = "https://cloud-images.ubuntu.com/releases/26.04/release-20260421/ubuntu-26.04-server-cloudimg-amd64.img";
hash = "sha256-jtIoyfCKUBIvpyMHYj2fiNkgm6JufoSe3VhPpnXjSGM=";
};
# Extra tools to expose on the in-VM PATH alongside act_runner. Each package's
# bin/* entries get symlinked into /usr/local/bin/. Node 24 is the floor —
# GitHub Actions removes Node 20 from its hosted runners on 2026-09-16, and
# most JS-based actions (actions/checkout, etc.) refuse to run without it.
extraPaths = [ nodejs_24 ];
toolPaths = [ gitea-actions-runner ] ++ extraPaths;
runnerClosure = closureInfo { rootPaths = toolPaths; };
in
vmTools.runInLinuxVM (runCommand "gitea-actions-vm-image"
{
diskImage = "image.qcow2";
memSize = 1024;
preVM = ''
mkdir -p $out
cp ${ubuntuImg} image.qcow2
chmod +w image.qcow2
'';
postVM = ''
mv image.qcow2 $out/image.qcow2
'';
nativeBuildInputs = [ util-linux e2fsprogs ];
meta = with lib; {
description = "Ubuntu 26.04 LTS qcow2 customised for ephemeral Gitea Actions runners";
platforms = [ "x86_64-linux" ];
};
} ''
set -eu
mkdir -p /mnt
mount /dev/vda1 /mnt
# Add a `runner` user matching GitHub-hosted runners (UID/GID 1001, HOME
# /home/runner, locked password). Most actions assume that name and that
# HOME, and `sudo apt-get install …` is near-universal in workflows. Bake
# the user into the image so it doesn't need recreating on every boot.
echo 'runner:x:1001:1001:Runner:/home/runner:/bin/bash' >> /mnt/etc/passwd
echo 'runner:x:1001:' >> /mnt/etc/group
echo 'runner:!:19500:0:99999:7:::' >> /mnt/etc/shadow
echo 'runner:!::' >> /mnt/etc/gshadow
install -d -m 0755 -o 1001 -g 1001 /mnt/home/runner
install -d -m 0755 -o 1001 -g 1001 /mnt/var/lib/gitea-runner
install -d -m 0755 -o 1001 -g 1001 /mnt/var/lib/gitea-runner-jobs
# cidata mountpoint stays root-owned; the unit's ExecStartPre mounts here
# as root and copies credentials out into runner-owned /var/lib paths.
install -d -m 0755 /mnt/etc/gitea-runner
install -Dm440 /dev/stdin /mnt/etc/sudoers.d/runner <<'EOF'
runner ALL=(ALL:ALL) NOPASSWD:ALL
Defaults env_keep += "DEBIAN_FRONTEND"
EOF
# Copy the act_runner Nix closure into the image's /nix/store. The
# gitea-actions-runner binary is dynamically linked against Nix-store
# glibc, so we need its full closure (glibc, tzdata, iana-etc, mailcap)
# alongside it for the binary to resolve at runtime.
mkdir -p /mnt/nix/store
while read -r storePath; do
cp -a "$storePath" /mnt/nix/store/
done < ${runnerClosure}/store-paths
# Stable user-space entry points: symlink every tool's bin/* into
# /usr/local/bin so the runner unit and the actions it spawns find them
# without needing /nix/store on PATH.
mkdir -p /mnt/usr/local/bin
for pkg in ${toString toolPaths}; do
for f in "$pkg"/bin/*; do
[ -e "$f" ] || continue
ln -sf "$f" "/mnt/usr/local/bin/$(basename "$f")"
done
done
# systemd unit for the runner. The unit runs act_runner directly via
# WorkingDirectory= and ExecStartPre=+ does the mount + credential copy
# as root, so no separate startup shell script is needed.
install -Dm644 ${./runner.service} /mnt/etc/systemd/system/gitea-runner.service
# Wire enable for our service. cloud-init.target.wants (rather than
# multi-user.target.wants) so we order strictly after cloud-final.service.
mkdir -p /mnt/etc/systemd/system/cloud-init.target.wants
ln -sf /etc/systemd/system/gitea-runner.service \
/mnt/etc/systemd/system/cloud-init.target.wants/gitea-runner.service
# Restrict cloud-init to the NoCloud datasource so it doesn't waste boot
# time scanning EC2/Azure/etc. metadata endpoints. The cidata ISO mounted
# at runtime carries network-config (static IP per instance) plus our
# runner credentials.
install -Dm644 /dev/stdin /mnt/etc/cloud/cloud.cfg.d/99-runner.cfg <<'EOF'
datasource_list: [ NoCloud, None ]
EOF
# Fresh machine-id per VM boot (systemd will regenerate on first boot).
: > /mnt/etc/machine-id
# Disable snapd — slow, not needed.
rm -f /mnt/etc/systemd/system/multi-user.target.wants/snapd.service \
/mnt/etc/systemd/system/multi-user.target.wants/snapd.seeded.service \
/mnt/etc/systemd/system/multi-user.target.wants/snapd.socket \
/mnt/etc/systemd/system/sockets.target.wants/snapd.socket
umount /mnt
sync
'')
@@ -0,0 +1,29 @@
[Unit]
Description=Gitea Actions Runner (ephemeral, --once)
# Wait for cloud-init's final stage so the cidata's network-config has been
# applied (static IP on ens3) before act_runner tries to reach Gitea.
# WantedBy=cloud-init.target rather than multi-user.target — cloud-init.target
# is After=multi-user.target, so combining After=cloud-final with
# WantedBy=multi-user creates an ordering cycle.
After=cloud-final.service
Wants=cloud-final.service
ConditionPathExists=/dev/disk/by-label/cidata
[Service]
Type=simple
User=runner
Group=runner
WorkingDirectory=/var/lib/gitea-runner
# `+` runs the command as root despite User=. Mount the cidata ISO and copy
# the credentials into runner's writable workdir with the right ownership;
# act_runner then runs unprivileged from there.
ExecStartPre=+/bin/mount -o ro /dev/disk/by-label/cidata /etc/gitea-runner
ExecStartPre=+/usr/bin/install -m 0600 -o runner -g runner /etc/gitea-runner/.runner /var/lib/gitea-runner/.runner
ExecStartPre=+/usr/bin/install -m 0644 -o runner -g runner /etc/gitea-runner/config.yaml /var/lib/gitea-runner/config.yaml
ExecStart=/usr/local/bin/act_runner daemon --config /var/lib/gitea-runner/config.yaml
ExecStopPost=+/sbin/poweroff -f
Restart=no
TimeoutStartSec=5min
[Install]
WantedBy=cloud-init.target
@@ -0,0 +1,12 @@
age-encryption.org/v1
-> ssh-ed25519 iWiFbA 1jRkLnerGCbwHEDvQQca+9xLGez3eCLbPR7LNqtzinY
xjh1ts2DVEgtpeRrOHW5bREQuZFTMZVUHbdU9TToqTo
-> {}:?YF-grease *>:q+N?* !}eU ~=AF
Ee9lCQ9A8amSjqwjx0emnGWhQE+T2gEEkmuOKJI/dVNkBWM8E465nFFieJNfU3zy
/A8MLO4wifWMd3uxMP66ZuqR34/qo3Dga+a5N/iMLRojCM/59Jqio9eK/mUl+oJi
--- +3GTOP1IGPFXxUqzz2b85Rh8j01lwl0onqi6xq1hDAg
þÍëEë7•ýé␍wÓzl§ÈáV
?훃Éi:Zž¶†Ø]ÑU;°¶‘ØÁ
Sã:ñô•–A š²
+zÞεgkdqW¯Žþm