Files
NixOsConfig/gitea-vm-runners.patch
T
faumaray 6908d4a695 vm gitea runner
Signed-off-by: faumaray <faumaray@gmail.com>
2026-10-29 19:45:23 +03:00

843 lines
38 KiB
Diff

diff --git a/ci/cxx26-feature-probe.cpp b/ci/cxx26-feature-probe.cpp
new file mode 100644
index 0000000..13e6a39
--- /dev/null
+++ b/ci/cxx26-feature-probe.cpp
@@ -0,0 +1,17 @@
+#include <meta>
+
+struct ProbeRecord {
+ int value;
+};
+
+constexpr auto members = std::meta::nonstatic_data_members_of(
+ ^^ProbeRecord, std::meta::access_context::current());
+static_assert(members.size() == 1);
+
+int positive(int value) pre (value > 0) {
+ return value;
+}
+
+int main() {
+ return positive(1) == 1 ? 0 : 1;
+}
diff --git a/docs/gitea-vm-runners.md b/docs/gitea-vm-runners.md
new file mode 100644
index 0000000..21a6a80
--- /dev/null
+++ b/docs/gitea-vm-runners.md
@@ -0,0 +1,160 @@
+# On-demand Gitea Windows/macOS runners
+
+## Behavior and resource use
+
+`gitea-vm-runner-dispatcher.service` polls `https://git.faumaray.com/api/v1/user/actions/jobs` every 15 seconds for `queued`, `pending`, and `in_progress` jobs. When a job's labels include `windows-x64` or `macos-x64`, it starts only that guest's systemd unit. After 90 seconds with no matching jobs, it stops the guest. If Gitea or the network cannot be queried, the controller leaves active guests running rather than risking an active job being interrupted.
+
+Both guests are **not enabled at boot**. Idle means the Docker container is stopped and its guest RAM/CPU usage is released; the persistent disk remains on disk. A running Windows guest is configured with 8 GiB RAM/4 vCPUs; macOS with 8 GiB/2 vCPUs for AMD stability. Only the requested guest starts, unless queued jobs for both labels exist. The services bind the web consoles and RDP/VNC to `127.0.0.1` only.
+
+The API endpoint is documented by Gitea at <https://docs.gitea.com/api/operations/get-user-workflow-jobs/>. The controller uses a separate API access token, not the runner registration token.
+
+## 1. Create the API token secret
+
+Create a dedicated Gitea access token that can read Actions job metadata for every repository whose jobs should wake these guests. Do not reuse the runner registration token for API polling.
+
+Create a local plaintext file in the repository's expected `TOKEN=` format:
+
+```sh
+umask 077
+printf 'TOKEN=%s\n' 'YOUR_GITEA_READ_API_TOKEN' > /tmp/gitea-vm-runner-api-token
+nix run .#secret-from-file -- gitea-vm-runner-api-token.age /tmp/gitea-vm-runner-api-token
+rm -f /tmp/gitea-vm-runner-api-token
+```
+
+Add the encrypted output under `secrets/gitea-vm-runner-api-token.age` to Git. The expected file should be present at flake evaluation time, like the existing `gitea-runner-token.age`, so `agenix` creates `/run/agenix/gitea-vm-runner-api-token` at runtime. If the secret is absent, the module emits a warning and the dispatcher is not enabled.
+
+The Windows runner is auto-registered by the OEM bootstrap when `secrets/gitea-runner-token.age` exists, using your existing registration token. macOS asks for the runner registration token during its one-time bootstrap; the API token is never mounted into either guest.
+
+## 2. Review and activate the Nix change
+
+The added host aspect is imported by `modules/hosts/desktop/host.nix`; it uses the existing rootful Docker configuration. It does not add `virtualisation.oci-containers`, Compose, or a boot dependency on either VM.
+
+Check hardware virtualization and KVM first:
+
+```sh
+lscpu | grep -E 'Architecture|Virtualization|Model name'
+grep -m1 -o 'avx2' /proc/cpuinfo || true
+ls -l /dev/kvm
+```
+
+Then validate the flake and test the new system configuration before making it the default:
+
+```sh
+nix flake check
+sudo nixos-rebuild test --flake .#desktop
+systemctl status gitea-vm-runner-dispatcher
+journalctl -u gitea-vm-runner-dispatcher -f
+```
+
+The dispatcher starts only if the API secret exists. The two VM units intentionally have no `wantedBy` and won't boot automatically. When the API token is configured, you can start them on demand using a matching queued workflow or a keep-awake pin (below).
+
+## 3. Windows first boot
+
+The first matching `windows-x64` queued job wakes Windows. The upstream `/oem/install.bat` hook installs:
+
+- Windows Node.js 24 LTS and Git for Windows (for Gitea Actions prerequisites);
+- Visual Studio Build Tools/C++ and Windows SDK (MSVC platform compatibility lane);
+- MSYS2 UCRT64 GCC 16, CMake, Ninja, Vulkan headers/loader/tools (C++26 contracts/reflection lane);
+- Vulkan SDK and Rust stable.
+
+The script compiles and runs `ci/cxx26-feature-probe.cpp` using GCC 16 with contracts and reflection enabled. It fails closed—registration does not happen until that exact compiler invocation passes. On subsequent boots the startup scheduled task brings up the already-registered runner.
+
+If provisioning fails, check the VM using the local-only console at `http://127.0.0.1:18006` or RDP to `127.0.0.1:13389`; logs are written to `C:\OEM\gitea-runner-install.log`. The first automatic installation can be lengthy, and the matching job remains queued while the guest is provisioned.
+
+## 4. macOS first boot and bootstrap
+
+macOS needs one interactive installation. To hold it awake for setup, run:
+
+```sh
+sudo mkdir -p /var/lib/gitea-vm-runners/keep-awake
+sudo touch /var/lib/gitea-vm-runners/keep-awake/macos-x64
+sudo systemctl start gitea-vm-macos
+```
+
+Open `http://127.0.0.1:18007`, complete the macOS installer, and create a local account. In the macOS guest Terminal, mount the read-only Nix-provided bootstrap share:
+
+```sh
+sudo -S mount_9p shared
+```
+
+Use Finder's Go → Computer view to locate the mounted `shared` volume. In Terminal, change into that volume and run:
+
+```sh
+bash ./bootstrap.sh
+```
+
+The bootstrap installs Homebrew non-interactively if absent (the first run still requires Xcode Command Line Tools and may ask for the local account password), then installs GCC 16, CMake/Ninja, Rust stable, Node, Git, Vulkan headers/loader/tools and MoltenVK. It validates C++26 contracts + reflection, then registers `macos-x64:host` and installs a LaunchDaemon. It prompts for the runner registration token. The runner will start automatically on future guest boots.
+
+When setup is complete, remove the pin. The dispatcher will stop the guest after its idle grace period if no macOS job is queued or running:
+
+```sh
+sudo rm -f /var/lib/gitea-vm-runners/keep-awake/macos-x64
+```
+
+The macOS guest is configured with 8 GiB maximum RAM during installation and 2 virtual CPUs, to stay conservative on AMD. Avoid raising installation RAM above 8 GiB. If performance needs it, test 4 vCPUs after confirming the guest is stable.
+
+## 5. Runner labels and example workflow jobs
+
+Runner labels are registered as `linux` (existing runner, now with GCC 16 tools), `windows-x64`, and `macos-x64`. Use labels without the `:host` executor suffix in `runs-on`:
+
+```yaml
+name: C++26 cross-platform
+on: [push, pull_request]
+jobs:
+ linux:
+ runs-on: linux
+ steps:
+ - uses: actions/checkout@v4
+ - run: g++ --version
+ - run: g++ -std=c++26 -fcontracts -freflection -fcontract-evaluation-semantic=enforce ci/cxx26-feature-probe.cpp -o cxx26-probe
+ - run: ./cxx26-probe
+
+ windows:
+ runs-on: windows-x64
+ steps:
+ - uses: actions/checkout@v4
+ - shell: powershell
+ run: |
+ g++ --version
+ g++ -std=c++26 -fcontracts -freflection -fcontract-evaluation-semantic=enforce ci/cxx26-feature-probe.cpp -o cxx26-probe.exe
+ .\cxx26-probe.exe
+
+ macos:
+ runs-on: macos-x64
+ steps:
+ - uses: actions/checkout@v4
+ - run: g++-16 --version
+ - run: g++-16 -std=c++26 -fcontracts -freflection -fcontract-evaluation-semantic=enforce ci/cxx26-feature-probe.cpp -o cxx26-probe
+ - run: ./cxx26-probe
+```
+
+The probe is an actual compile/run gate, not a check of compiler version text. GCC documents Contracts via `-fcontracts` and P2996 reflection via `-freflection` starting with GCC 16: <https://gcc.gnu.org/gcc-16/changes.html>.
+
+## 6. Vulkan and Rust notes
+
+The Linux host is given native GCC 16, CMake/Ninja, Vulkan headers/loader/tools, and Rust/Cargo through the NixOS runner's `hostPackages`. On Windows the MSVC + Vulkan SDK lane covers Windows SDK/linking behavior; the GCC 16 lane validates the required C++26 features. On macOS, `GPU=Y` exposes the host AMD DRM device to dockur's Reims vGPU, and MoltenVK maps Vulkan onto Metal. This can support basic virtual-GPU testing, but a VM's virtual GPU is not equivalent to testing on a physical Mac/GPU. Keep OS-level platform tests separate from the C++26 compiler feature gate.
+
+Gitea Runner's `host` executor runs workflows as the runner's user without job isolation. These native Windows/macOS runners should only execute trusted repositories and workflows. Do not expose the local console/RDP/VNC ports to the LAN or internet. Docker image tags are currently `latest`; pin image digests if exact VM image reproducibility is required.
+
+## 7. Manual controls and logs
+
+```sh
+# Manually keep a guest awake while preparing it. Remove the marker afterward.
+sudo touch /var/lib/gitea-vm-runners/keep-awake/windows-x64
+sudo systemctl start gitea-vm-windows
+sudo rm -f /var/lib/gitea-vm-runners/keep-awake/windows-x64
+
+# View controller/guest logs and state.
+journalctl -u gitea-vm-runner-dispatcher -f
+journalctl -u gitea-vm-windows -f
+journalctl -u gitea-vm-macos -f
+systemctl is-active gitea-vm-windows gitea-vm-macos
+
+docker ps --filter name=gitea-vm-
+```
+
+Persistent guest disks are under `/var/lib/gitea-vm-runners/windows` and `/var/lib/gitea-vm-runners/macos`. Stopping the guest frees configured guest RAM; it does not delete these disks. Back them up before removing either storage directory.
+
+## Compatibility/legal note
+
+GCC 16 implements the C++26 Contracts feature and P2996 reflection; these are still evolving draft-standard features, so the compile/run probe intentionally decides support based on behavior. Upstream `dockur/macos` documents Linux/KVM + AVX2 as technical requirements, but also states that Apple's macOS EULA permits running macOS only on Apple-branded hardware. This AMD host is therefore not a compliant place to run a macOS guest under that stated EULA. For compliant macOS CI, use an Apple Mac runner. The macOS aspect here is included as a technical configuration, not a statement that its use on non-Apple hardware is permitted.
diff --git a/modules/dev/_gitea-vm-runner-assets/dispatcher.py b/modules/dev/_gitea-vm-runner-assets/dispatcher.py
new file mode 100644
index 0000000..8e147f7
--- /dev/null
+++ b/modules/dev/_gitea-vm-runner-assets/dispatcher.py
@@ -0,0 +1,180 @@
+#!/usr/bin/env python3
+"""Wake dockur guest runners only while matching Gitea jobs are queued/running."""
+from __future__ import annotations
+
+import json
+import logging
+import os
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from pathlib import Path
+
+API_URL = os.environ.get(
+ "GITEA_ACTIONS_JOBS_URL",
+ "https://git.faumaray.com/api/v1/user/actions/jobs",
+)
+POLL_SECONDS = int(os.environ.get("GITEA_VM_POLL_SECONDS", "15"))
+IDLE_SECONDS = int(os.environ.get("GITEA_VM_IDLE_SECONDS", "90"))
+PAGE_SIZE = 50
+MAX_PAGES = 100
+
+GUESTS = {
+ "windows-x64": "gitea-vm-windows.service",
+ "macos-x64": "gitea-vm-macos.service",
+}
+KEEP_AWAKE_DIR = Path("/var/lib/gitea-vm-runners/keep-awake")
+ACTIVE_STATUSES = ("queued", "pending", "in_progress")
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s %(levelname)s gitea-vm-dispatcher: %(message)s",
+)
+
+
+def read_token(path: str) -> str:
+ """Read either the repository's TOKEN=value secret format or a raw token."""
+ for raw_line in Path(path).read_text(encoding="utf-8").splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("#"):
+ continue
+ if line.startswith("TOKEN="):
+ return line.split("=", 1)[1].strip().strip("\"'")
+ return line
+ raise RuntimeError(f"No token found in {path}")
+
+
+def api_get(token: str, status: str, page: int) -> dict:
+ query = urllib.parse.urlencode({"status": status, "page": page, "limit": PAGE_SIZE, "sort": "id", "order": "desc"})
+ request = urllib.request.Request(
+ f"{API_URL}?{query}",
+ headers={"Authorization": f"token {token}", "Accept": "application/json", "User-Agent": "nixos-gitea-vm-dispatcher/1"},
+ method="GET",
+ )
+ with urllib.request.urlopen(request, timeout=12) as response:
+ if response.status != 200:
+ raise RuntimeError(f"Gitea API returned HTTP {response.status}")
+ return json.loads(response.read().decode("utf-8"))
+
+
+def get_jobs(token: str) -> list[dict]:
+ jobs_by_id: dict[int, dict] = {}
+ for status in ACTIVE_STATUSES:
+ for page in range(1, MAX_PAGES + 1):
+ payload = api_get(token, status, page)
+ jobs = payload.get("jobs", [])
+ for job in jobs:
+ if isinstance(job, dict) and isinstance(job.get("id"), int):
+ jobs_by_id[job["id"]] = job
+ total = int(payload.get("total_count", len(jobs)))
+ if not jobs or page * PAGE_SIZE >= total:
+ break
+ else:
+ raise RuntimeError(f"Gitea returned more than {MAX_PAGES * PAGE_SIZE} {status} jobs; refusing incomplete reconciliation")
+ return list(jobs_by_id.values())
+
+
+def needed_guests(jobs: list[dict]) -> set[str]:
+ needed: set[str] = set()
+ for job in jobs:
+ labels = job.get("labels") or []
+ if not isinstance(labels, list):
+ continue
+ labels = {str(label) for label in labels}
+ for label in GUESTS:
+ if label in labels:
+ needed.add(label)
+ return needed
+
+
+def active(unit: str) -> bool:
+ result = subprocess.run(
+ ["/run/current-system/sw/bin/systemctl", "is-active", "--quiet", unit],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ check=False,
+ )
+ return result.returncode == 0
+
+
+def systemctl(action: str, unit: str) -> bool:
+ result = subprocess.run(
+ ["/run/current-system/sw/bin/systemctl", action, unit],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ check=False,
+ )
+ if result.returncode != 0:
+ logging.error("systemctl %s %s failed (exit %s): %s", action, unit, result.returncode, result.stdout.strip())
+ return False
+ return True
+
+
+def main() -> int:
+ if len(sys.argv) != 2:
+ print(f"usage: {sys.argv[0]} /path/to/agenix-api-token", file=sys.stderr)
+ return 2
+
+ token = read_token(sys.argv[1])
+ last_needed: dict[str, float | None] = {key: None for key in GUESTS}
+ logging.info("polling %s every %ss; idle shutdown grace=%ss", API_URL, POLL_SECONDS, IDLE_SECONDS)
+
+ while True:
+ now = time.monotonic()
+ try:
+ jobs = get_jobs(token)
+ needed = needed_guests(jobs)
+ except (OSError, ValueError, KeyError, RuntimeError, urllib.error.URLError, TimeoutError) as exc:
+ # Fail closed: if Gitea cannot be queried, never shut down a possibly busy guest.
+ logging.warning("cannot reconcile Gitea jobs (%s); keeping active guests awake", exc)
+ pinned = {label for label in GUESTS if (KEEP_AWAKE_DIR / label).exists()}
+ for label, unit in GUESTS.items():
+ if label in pinned and not active(unit):
+ logging.info("manual keep-awake pin for %s; starting %s despite API failure", label, unit)
+ systemctl("reset-failed", unit)
+ systemctl("start", unit)
+ if active(unit):
+ last_needed[label] = now
+ time.sleep(POLL_SECONDS)
+ continue
+
+ pinned = {label for label in GUESTS if (KEEP_AWAKE_DIR / label).exists()}
+ needed |= pinned
+ logging.debug("active guest labels from jobs or keep-awake pins: %s", sorted(needed))
+ for label, unit in GUESTS.items():
+ if label in needed:
+ last_needed[label] = None
+ if not active(unit):
+ reason = "manual keep-awake pin" if label in pinned else "queued/running job"
+ logging.info("%s needs %s; starting %s", reason, label, unit)
+ systemctl("reset-failed", unit)
+ systemctl("start", unit)
+ continue
+
+ if not active(unit):
+ last_needed[label] = None
+ continue
+
+ if last_needed[label] is None:
+ last_needed[label] = now
+ logging.info("%s is no longer needed; starting %ss idle grace period", unit, IDLE_SECONDS)
+ continue
+
+ idle_for = now - float(last_needed[label])
+ if idle_for >= IDLE_SECONDS:
+ logging.info("%s idle for %.0fs; stopping guest to release RAM", unit, idle_for)
+ if systemctl("stop", unit):
+ last_needed[label] = None
+
+ time.sleep(POLL_SECONDS)
+
+
+if __name__ == "__main__":
+ try:
+ raise SystemExit(main())
+ except KeyboardInterrupt:
+ raise SystemExit(0)
diff --git a/modules/dev/_gitea-vm-runner-assets/macos/bootstrap.sh b/modules/dev/_gitea-vm-runner-assets/macos/bootstrap.sh
new file mode 100755
index 0000000..0587db8
--- /dev/null
+++ b/modules/dev/_gitea-vm-runner-assets/macos/bootstrap.sh
@@ -0,0 +1,104 @@
+#!/bin/bash
+set -euo pipefail
+
+GITEA_URL='https://git.faumaray.com'
+RUNNER_VERSION='5.0.0'
+WORK_DIR="$HOME/gitea-runner"
+TEMP_TOKEN="$(mktemp)"
+trap 'rm -f "$TEMP_TOKEN"' EXIT
+chmod 600 "$TEMP_TOKEN"
+
+if [[ "$(uname -m)" != "x86_64" ]]; then
+ echo "Expected an x86_64 macOS guest; got $(uname -m)." >&2
+ exit 1
+fi
+
+if ! xcode-select -p >/dev/null 2>&1; then
+ echo 'Install Xcode Command Line Tools first: sudo xcode-select --install'
+ exit 1
+fi
+
+if ! command -v brew >/dev/null 2>&1; then
+ echo 'Installing Homebrew non-interactively; sudo may ask for the guest account password.'
+ NONINTERACTIVE=1 /bin/bash -c "$(curl --fail --location --silent --show-error https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
+fi
+if [[ -x /usr/local/bin/brew ]]; then
+ eval "$(/usr/local/bin/brew shellenv)"
+elif [[ -x /opt/homebrew/bin/brew ]]; then
+ eval "$(/opt/homebrew/bin/brew shellenv)"
+fi
+if ! command -v brew >/dev/null 2>&1; then
+ echo 'Homebrew installation did not provide a brew executable on PATH.' >&2
+ exit 1
+fi
+
+# Homebrew supplies GCC 16.x (contracts + P2996 reflection), build tools and MoltenVK.
+brew update
+brew install gcc cmake ninja rustup-init vulkan-headers vulkan-loader vulkan-tools molten-vk node git git-lfs
+rustup-init -y --default-toolchain stable --no-modify-path
+export PATH="$HOME/.cargo/bin:$(brew --prefix)/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
+"$HOME/.cargo/bin/rustup" toolchain install stable
+"$HOME/.cargo/bin/rustup" default stable
+
+GXX="$(brew --prefix gcc)/bin/g++-16"
+if [[ ! -x "$GXX" ]]; then
+ echo "GCC 16 was not found at $GXX; refusing to register a runner without the required toolchain." >&2
+ exit 1
+fi
+
+"$GXX" --version
+"$GXX" -std=c++26 -fcontracts -freflection -fcontract-evaluation-semantic=enforce \
+ "$(dirname "$0")/cxx26-feature-probe.cpp" -o "$TMPDIR/cxx26-feature-probe"
+"$TMPDIR/cxx26-feature-probe"
+
+mkdir -p "$WORK_DIR" "$HOME/Library/Logs"
+cd "$WORK_DIR"
+curl --fail --location --silent --show-error \
+ "https://dl.gitea.com/gitea-runner/${RUNNER_VERSION}/gitea-runner-${RUNNER_VERSION}-darwin-amd64" \
+ -o "$WORK_DIR/gitea-runner"
+chmod 0755 "$WORK_DIR/gitea-runner"
+
+read -r -s -p 'Gitea runner registration token: ' GITEA_TOKEN
+echo
+printf '%s' "$GITEA_TOKEN" > "$TEMP_TOKEN"
+unset GITEA_TOKEN
+"$WORK_DIR/gitea-runner" register --no-interactive \
+ --instance "$GITEA_URL" --token-file "$TEMP_TOKEN" \
+ --name 'ci-macos-x64' --labels 'macos-x64:host'
+
+# LaunchDaemon runs at guest boot; jobs are executed as the account used to run this script.
+PLIST_TMP="$(mktemp)"
+cat > "$PLIST_TMP" <<PLIST
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key><string>com.gitea.runner</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>${WORK_DIR}/gitea-runner</string>
+ <string>daemon</string>
+ </array>
+ <key>WorkingDirectory</key><string>${WORK_DIR}</string>
+ <key>RunAtLoad</key><true/>
+ <key>KeepAlive</key><true/>
+ <key>StandardOutPath</key><string>${HOME}/Library/Logs/gitea-runner.log</string>
+ <key>StandardErrorPath</key><string>${HOME}/Library/Logs/gitea-runner.err</string>
+ <key>EnvironmentVariables</key>
+ <dict><key>PATH</key><string>${HOME}/.cargo/bin:$(brew --prefix)/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
+ <key>HOME</key><string>${HOME}</string></dict>
+ <key>UserName</key><string>$(id -un)</string>
+</dict>
+</plist>
+PLIST
+sudo install -o root -g wheel -m 0644 "$PLIST_TMP" /Library/LaunchDaemons/com.gitea.runner.plist
+rm -f "$PLIST_TMP"
+sudo launchctl bootout system /Library/LaunchDaemons/com.gitea.runner.plist >/dev/null 2>&1 || true
+sudo launchctl bootstrap system /Library/LaunchDaemons/com.gitea.runner.plist
+
+cat <<'DONE'
+macOS Gitea runner registered and LaunchDaemon installed.
+Runner label: macos-x64
+Compiler gate: GCC 16 C++26 contracts + reflection compile/run passed.
+Vulkan: Vulkan tools + MoltenVK installed. A VM's virtual GPU is not a substitute for physical-GPU validation.
+DONE
diff --git a/modules/dev/_gitea-vm-runner-assets/windows/install.bat b/modules/dev/_gitea-vm-runner-assets/windows/install.bat
new file mode 100644
index 0000000..8db827b
--- /dev/null
+++ b/modules/dev/_gitea-vm-runner-assets/windows/install.bat
@@ -0,0 +1,4 @@
+@echo off
+setlocal
+powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File C:\OEM\install.ps1
+exit /b %ERRORLEVEL%
diff --git a/modules/dev/_gitea-vm-runner-assets/windows/install.ps1 b/modules/dev/_gitea-vm-runner-assets/windows/install.ps1
new file mode 100644
index 0000000..29ef696
--- /dev/null
+++ b/modules/dev/_gitea-vm-runner-assets/windows/install.ps1
@@ -0,0 +1,136 @@
+$ErrorActionPreference = 'Stop'
+$ProgressPreference = 'SilentlyContinue'
+$Log = 'C:\OEM\gitea-runner-install.log'
+Start-Transcript -Path $Log -Append
+
+function Invoke-Installer([string]$File, [string]$Arguments, [int[]]$SuccessCodes = @(0)) {
+ $process = Start-Process -FilePath $File -ArgumentList $Arguments -Wait -PassThru
+ if ($process.ExitCode -notin $SuccessCodes) {
+ throw "$File failed with exit code $($process.ExitCode)"
+ }
+}
+
+function Download([string]$Url, [string]$Path) {
+ Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Path
+}
+
+try {
+ New-Item -ItemType Directory -Force -Path 'C:\ci-tools', 'C:\ci-tools\downloads', 'C:\ci-tools\cargo', 'C:\ci-tools\rustup', 'C:\ci\gitea-runner' | Out-Null
+
+ # Node is needed by JavaScript-based Gitea Actions. Pin to the current Node 24 LTS line.
+ $nodeRelease = Invoke-RestMethod -Uri 'https://nodejs.org/dist/index.json' |
+ Where-Object { $_.version -match '^v24\.' -and $_.lts } |
+ Select-Object -First 1
+ if (-not $nodeRelease) { throw 'Could not find a Node.js 24 LTS release.' }
+ $nodeMsi = "C:\ci-tools\downloads\node-$($nodeRelease.version)-x64.msi"
+ Download "https://nodejs.org/dist/$($nodeRelease.version)/node-$($nodeRelease.version)-x64.msi" $nodeMsi
+ Invoke-Installer "$env:SystemRoot\System32\msiexec.exe" "/i `"$nodeMsi`" /qn /norestart" @(0, 3010)
+
+ # Git's official installer; jobs execute as SYSTEM in this isolated guest.
+ $gitInstaller = 'C:\ci-tools\downloads\Git-64-bit.exe'
+ Download 'https://github.com/git-for-windows/git/releases/latest/download/Git-64-bit.exe' $gitInstaller
+ Invoke-Installer $gitInstaller '/VERYSILENT /NORESTART /SP- /DIR="C:\Program Files\Git"' @(0, 3010)
+
+ # MSVC compatibility lane plus the MSYS2 UCRT64 GCC lane for C++26 reflection/contracts.
+ $vsInstaller = 'C:\ci-tools\downloads\vs_BuildTools.exe'
+ Download 'https://aka.ms/vs/17/release/vs_BuildTools.exe' $vsInstaller
+ Invoke-Installer $vsInstaller '--quiet --wait --norestart --nocache --installPath C:\BuildTools --add Microsoft.VisualStudio.Workload.VCTools --add Microsoft.VisualStudio.Component.VC.Tools.x86.x64 --add Microsoft.VisualStudio.Component.Windows11SDK.22621' @(0, 3010)
+
+ $msysInstaller = 'C:\ci-tools\downloads\msys2-x86_64-latest.exe'
+ Download 'https://github.com/msys2/msys2-installer/releases/latest/download/msys2-x86_64-latest.exe' $msysInstaller
+ Invoke-Installer $msysInstaller '--confirm-command --accept-messages --root C:\msys64 --quiet' @(0, 3010)
+ $bash = 'C:\msys64\usr\bin\bash.exe'
+ if (-not (Test-Path $bash)) { throw 'MSYS2 install did not create C:\msys64\usr\bin\bash.exe' }
+ # The first self-update can close the MSYS2 process. Running it twice is intentional.
+ & $bash -lc 'pacman -Syu --noconfirm'
+ & $bash -lc 'pacman -Syu --noconfirm'
+ if ($LASTEXITCODE -ne 0) { throw 'MSYS2 package database/system update failed.' }
+ & $bash -lc 'pacman -S --needed --noconfirm mingw-w64-ucrt-x86_64-toolchain mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-ninja mingw-w64-ucrt-x86_64-vulkan-headers mingw-w64-ucrt-x86_64-vulkan-loader mingw-w64-ucrt-x86_64-vulkan-tools'
+ if ($LASTEXITCODE -ne 0) { throw 'MSYS2 UCRT64 toolchain installation failed.' }
+
+ # Install the official Vulkan SDK for MSVC builds and validation tools.
+ $vulkanVersion = '1.4.363.0'
+ $vulkanInstaller = "C:\ci-tools\downloads\VulkanSDK-$vulkanVersion-Installer.exe"
+ Download "https://sdk.lunarg.com/sdk/download/$vulkanVersion/windows/VulkanSDK-$vulkanVersion-Installer.exe" $vulkanInstaller
+ Invoke-Installer $vulkanInstaller "--accept-licenses --default-answer --confirm-command --root C:\VulkanSDK\$vulkanVersion --quiet" @(0, 3010)
+
+ # Install Rust in a stable machine-wide location (the runner task uses LocalSystem).
+ [Environment]::SetEnvironmentVariable('CARGO_HOME', 'C:\ci-tools\cargo', 'Machine')
+ [Environment]::SetEnvironmentVariable('RUSTUP_HOME', 'C:\ci-tools\rustup', 'Machine')
+ $env:CARGO_HOME = 'C:\ci-tools\cargo'
+ $env:RUSTUP_HOME = 'C:\ci-tools\rustup'
+ $rustup = 'C:\ci-tools\downloads\rustup-init.exe'
+ Download 'https://win.rustup.rs/x86_64' $rustup
+ Invoke-Installer $rustup '-y --default-toolchain stable --no-modify-path' @(0)
+
+ # Ensure the native toolchain paths are available to jobs launched by Task Scheduler.
+ $machinePath = [Environment]::GetEnvironmentVariable('Path', 'Machine')
+ $additions = @(
+ 'C:\msys64\ucrt64\bin', 'C:\msys64\usr\bin', 'C:\Program Files\Git\cmd',
+ 'C:\Program Files\nodejs', 'C:\ci-tools\cargo\bin',
+ "C:\VulkanSDK\$vulkanVersion\Bin", 'C:\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin'
+ )
+ foreach ($entry in $additions) {
+ if ($machinePath -notlike "*$entry*") { $machinePath = "$entry;$machinePath" }
+ }
+ [Environment]::SetEnvironmentVariable('Path', $machinePath, 'Machine')
+
+ # A registration is permitted only after the real C++26 feature probe compiles and runs.
+ $gxx = 'C:\msys64\ucrt64\bin\g++.exe'
+ $probe = 'C:\OEM\cxx26-feature-probe.cpp'
+ $probeExe = 'C:\ci-tools\cxx26-feature-probe.exe'
+ if (-not (Test-Path $gxx)) { throw 'GCC 16 UCRT64 compiler was not installed.' }
+ & $gxx -std=c++26 -fcontracts -freflection -fcontract-evaluation-semantic=enforce $probe -o $probeExe
+ if ($LASTEXITCODE -ne 0) { throw 'GCC C++26 contracts + reflection probe did not compile; runner intentionally left unregistered.' }
+ & $probeExe
+ if ($LASTEXITCODE -ne 0) { throw 'GCC C++26 contracts + reflection probe failed at runtime; runner intentionally left unregistered.' }
+
+ # The existing repository secret is an agenix EnvironmentFile: TOKEN=<registration token>.
+ # dockur/windows copies this OEM directory to C:\OEM on first automatic installation.
+ $registrationFile = 'C:\OEM\runner-token'
+ if (Test-Path $registrationFile) {
+ $tokenLine = Get-Content $registrationFile | Where-Object { $_ -match '^TOKEN=' } | Select-Object -First 1
+ if (-not $tokenLine) { throw 'C:\OEM\runner-token must contain TOKEN=<registration token>.' }
+ $token = $tokenLine.Substring(6).Trim().Trim('"').Trim("'")
+ if (-not $token) { throw 'The Gitea registration token is empty.' }
+ $tokenFile = 'C:\ci-tools\registration-token.tmp'
+ Set-Content -NoNewline -Path $tokenFile -Value $token
+ $acl = Get-Acl $tokenFile
+ $acl.SetAccessRuleProtection($true, $false)
+ $rule = New-Object System.Security.AccessControl.FileSystemAccessRule('SYSTEM', 'FullControl', 'Allow')
+ $acl.SetAccessRule($rule)
+ Set-Acl -Path $tokenFile -AclObject $acl
+ Push-Location 'C:\ci\gitea-runner'
+ try {
+ $runnerVersion = '5.0.0'
+ $runnerExe = 'C:\ci\gitea-runner\gitea-runner.exe'
+ Download "https://dl.gitea.com/gitea-runner/$runnerVersion/gitea-runner-$runnerVersion-windows-amd64.exe" $runnerExe
+ & $runnerExe register --no-interactive --instance 'https://git.faumaray.com' --token-file $tokenFile --name 'ci-windows-x64' --labels 'windows-x64:host'
+ if ($LASTEXITCODE -ne 0) { throw 'Gitea runner registration failed.' }
+ } finally {
+ Pop-Location
+ Remove-Item -Force -ErrorAction SilentlyContinue $tokenFile
+ Remove-Item -Force -ErrorAction SilentlyContinue $registrationFile
+ }
+
+ @'
+@echo off
+set "CARGO_HOME=C:\ci-tools\cargo"
+set "RUSTUP_HOME=C:\ci-tools\rustup"
+set "VULKAN_SDK=C:\VulkanSDK\1.4.363.0"
+set "PATH=C:\msys64\ucrt64\bin;C:\msys64\usr\bin;C:\Program Files\Git\cmd;C:\Program Files\nodejs;C:\ci-tools\cargo\bin;C:\VulkanSDK\1.4.363.0\Bin;C:\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin;%PATH%"
+cd /d C:\ci\gitea-runner
+C:\ci\gitea-runner\gitea-runner.exe daemon >> C:\ci\gitea-runner\runner.log 2>&1
+'@ | Set-Content -Encoding Ascii 'C:\ci\gitea-runner\run.cmd'
+ & schtasks.exe /Create /TN 'Gitea CI Runner' /SC ONSTART /RU SYSTEM /RL HIGHEST /TR 'cmd.exe /d /c C:\ci\gitea-runner\run.cmd' /F
+ if ($LASTEXITCODE -ne 0) { throw 'Could not create the Gitea runner startup task.' }
+ & schtasks.exe /Run /TN 'Gitea CI Runner'
+ } else {
+ Write-Warning 'No runner token was mounted at C:\OEM\runner-token; toolchains are installed but this Windows guest is not registered.'
+ }
+} catch {
+ Write-Error $_
+ throw
+} finally {
+ Stop-Transcript
+}
diff --git a/modules/dev/gitea-runner.nix b/modules/dev/gitea-runner.nix
index 3329a4f..3d3dec3 100644
--- a/modules/dev/gitea-runner.nix
+++ b/modules/dev/gitea-runner.nix
@@ -40,6 +40,14 @@ in
coreutils
curl
gitMinimal
+ gcc16
+ cmake
+ ninja
+ vulkan-headers
+ vulkan-loader
+ vulkan-tools
+ rustc
+ cargo
nix
nodejs_26
wget
diff --git a/modules/dev/gitea-vm-runners.nix b/modules/dev/gitea-vm-runners.nix
new file mode 100644
index 0000000..5a3a9b0
--- /dev/null
+++ b/modules/dev/gitea-vm-runners.nix
@@ -0,0 +1,168 @@
+# On-demand Windows/macOS Gitea Actions guests. This is a flake-parts aspect;
+# host.nix opts into it, and import-tree ignores the underscore-prefixed assets.
+{ config, lib, ... }:
+let
+ registrationSecret = config.meta.secretsDir + "/gitea-runner-token.age";
+ apiSecret = config.meta.secretsDir + "/gitea-vm-runner-api-token.age";
+ hasRegistrationSecret = builtins.pathExists registrationSecret;
+ hasApiSecret = builtins.pathExists apiSecret;
+in
+{
+ flake.modules.nixos.gitea-vm-runners = { config, lib, pkgs, ... }:
+ let
+ assets = ./_gitea-vm-runner-assets;
+
+ windowsOem = pkgs.runCommand "gitea-vm-windows-oem" { } ''
+ mkdir -p "$out"
+ cp ${assets}/windows/install.bat "$out/install.bat"
+ cp ${assets}/windows/install.ps1 "$out/install.ps1"
+ cp ${../../ci/cxx26-feature-probe.cpp} "$out/cxx26-feature-probe.cpp"
+ '';
+
+ macosShare = pkgs.runCommand "gitea-vm-macos-share" { } ''
+ mkdir -p "$out"
+ cp ${assets}/macos/bootstrap.sh "$out/bootstrap.sh"
+ cp ${../../ci/cxx26-feature-probe.cpp} "$out/cxx26-feature-probe.cpp"
+ '';
+
+ registrationCopy = lib.optionalString hasRegistrationSecret (
+ "${pkgs.coreutils}/bin/install -m 0400 ${config.age.secrets.gitea-runner-token.path} \"$oem/runner-token\""
+ );
+
+ windowsStart = pkgs.writeShellScript "gitea-vm-windows-start" ''
+ set -euo pipefail
+ state=/var/lib/gitea-vm-runners/windows
+ oem=/run/gitea-vm-runners/windows-oem
+ ${pkgs.coreutils}/bin/mkdir -p "$state" /run/gitea-vm-runners
+ ${pkgs.coreutils}/bin/rm -rf "$oem"
+ ${pkgs.coreutils}/bin/mkdir -m 0700 -p "$oem"
+ ${pkgs.coreutils}/bin/cp -R ${windowsOem}/. "$oem/"
+ ${registrationCopy}
+ ${pkgs.docker}/bin/docker rm -f gitea-vm-windows >/dev/null 2>&1 || true
+ exec ${pkgs.docker}/bin/docker run --rm --init \
+ --name gitea-vm-windows \
+ --device=/dev/kvm --device=/dev/net/tun --cap-add=NET_ADMIN \
+ -e VERSION=11 -e RAM_SIZE=8G -e CPU_CORES=4 -e DISK_SIZE=160G \
+ -p 127.0.0.1:18006:8006 \
+ -p 127.0.0.1:13389:3389/tcp \
+ -v /var/lib/gitea-vm-runners/windows:/storage \
+ -v "$oem:/oem:ro" \
+ dockurr/windows:latest
+ '';
+
+ windowsStop = pkgs.writeShellScript "gitea-vm-windows-stop" ''
+ set +e
+ ${pkgs.docker}/bin/docker stop --time 120 gitea-vm-windows >/dev/null 2>&1
+ ${pkgs.coreutils}/bin/rm -rf /run/gitea-vm-runners/windows-oem
+ exit 0
+ '';
+
+ macosStart = pkgs.writeShellScript "gitea-vm-macos-start" ''
+ set -euo pipefail
+ ${pkgs.coreutils}/bin/mkdir -p /var/lib/gitea-vm-runners/macos
+ ${pkgs.docker}/bin/docker rm -f gitea-vm-macos >/dev/null 2>&1 || true
+ exec ${pkgs.docker}/bin/docker run --rm --init \
+ --name gitea-vm-macos \
+ --device=/dev/kvm --device=/dev/net/tun --device=/dev/dri --cap-add=NET_ADMIN \
+ -e VERSION=15 -e RAM_SIZE=8G -e CPU_CORES=2 -e DISK_SIZE=128G -e GPU=Y \
+ -p 127.0.0.1:18007:8006 \
+ -p 127.0.0.1:15900:5900/tcp \
+ -p 127.0.0.1:15900:5900/udp \
+ -v /var/lib/gitea-vm-runners/macos:/storage \
+ -v ${macosShare}:/shared:ro \
+ dockurr/macos:latest
+ '';
+
+ macosStop = pkgs.writeShellScript "gitea-vm-macos-stop" ''
+ set +e
+ ${pkgs.docker}/bin/docker stop --time 120 gitea-vm-macos >/dev/null 2>&1
+ exit 0
+ '';
+ in
+ {
+ # AMD KVM support. The host's existing docker aspect provides docker.service.
+ boot.kernelModules = lib.mkAfter [ "kvm-amd" "tun" ];
+
+ age.secrets = lib.optionalAttrs hasApiSecret {
+ gitea-vm-runner-api-token = {
+ file = apiSecret;
+ mode = "0400";
+ };
+ };
+
+ systemd.tmpfiles.rules = [
+ "d /var/lib/gitea-vm-runners 0750 root root - -"
+ "d /var/lib/gitea-vm-runners/windows 0750 root root - -"
+ "d /var/lib/gitea-vm-runners/macos 0750 root root - -"
+ "d /var/lib/gitea-vm-runners/keep-awake 0750 root root - -"
+ "d /run/gitea-vm-runners 0700 root root - -"
+ ];
+
+ # Intentionally no wantedBy: the dispatcher alone starts/stops these units.
+ systemd.services.gitea-vm-windows = {
+ description = "On-demand Windows Gitea Actions VM";
+ after = [ "docker.service" ] ++ lib.optional hasRegistrationSecret "agenix.service";
+ requires = [ "docker.service" ];
+ serviceConfig = {
+ Type = "simple";
+ ExecStart = windowsStart;
+ ExecStop = windowsStop;
+ Restart = "no";
+ TimeoutStartSec = "infinity";
+ TimeoutStopSec = "150s";
+ KillMode = "mixed";
+ };
+ };
+
+ systemd.services.gitea-vm-macos = {
+ description = "On-demand macOS Gitea Actions VM";
+ after = [ "docker.service" ];
+ requires = [ "docker.service" ];
+ serviceConfig = {
+ Type = "simple";
+ ExecStart = macosStart;
+ ExecStop = macosStop;
+ Restart = "no";
+ TimeoutStartSec = "infinity";
+ TimeoutStopSec = "150s";
+ KillMode = "mixed";
+ };
+ };
+
+ # The API token is read-only and is distinct from the runner registration token.
+ # On API/network failures the controller deliberately keeps guests awake.
+ systemd.services.gitea-vm-runner-dispatcher = lib.mkIf hasApiSecret {
+ description = "Wake Gitea Windows/macOS runners for queued workflow jobs";
+ wantedBy = [ "multi-user.target" ];
+ wants = [ "network-online.target" ];
+ after = [ "network-online.target" "docker.service" "agenix.service" ];
+ requires = [ "docker.service" ];
+ serviceConfig = {
+ Type = "simple";
+ ExecStart = "${pkgs.python3}/bin/python ${assets}/dispatcher.py ${config.age.secrets.gitea-vm-runner-api-token.path}";
+ Restart = "always";
+ RestartSec = "10s";
+ User = "root";
+ UMask = "0077";
+ };
+ };
+ };
+
+ warnings =
+ lib.optional (!hasApiSecret) ''
+ On-demand Gitea VM runners are configured but remain dormant because
+ secrets/gitea-vm-runner-api-token.age is missing. Create a dedicated Gitea
+ API token with permission to read Actions jobs, put it in a file as
+ TOKEN=<api token>, then run:
+ nix run .#secret-from-file -- gitea-vm-runner-api-token.age <file>
+ and add the resulting .age file to the repository. This token is separate
+ from the runner registration token.
+ ''
+ ++ lib.optional (!hasRegistrationSecret) ''
+ The Windows VM will provision its toolchain but cannot auto-register until
+ secrets/gitea-runner-token.age exists. That file should contain
+ TOKEN=<runner registration token>. If adding it after Windows has already
+ completed its first OEM installation, register the runner manually inside
+ the guest or recreate its persistent disk after backing it up.
+ '';
+}
diff --git a/modules/hosts/desktop/host.nix b/modules/hosts/desktop/host.nix
index c3d42a2..710fc8c 100644
--- a/modules/hosts/desktop/host.nix
+++ b/modules/hosts/desktop/host.nix
@@ -29,6 +29,7 @@ in
proxy-suite
docker
gitea-runner
+ gitea-vm-runners
nix-ld
];