1 parent
079cceb554
commit
6908d4a695
12 files changed
+1667
No files matched your search
@@ -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)
|
||||
+104
@@ -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
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
setlocal
|
||||
powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File C:\OEM\install.ps1
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
diff --git a/modules/dev/gitea-runner.nix b/modules/dev/gitea-runner.nix
|
||||
index 7777777..8888888 100644
|
||||
--- a/modules/dev/gitea-runner.nix
|
||||
+++ b/modules/dev/gitea-runner.nix
|
||||
@@ -72,6 +72,14 @@
|
||||
bashInteractive
|
||||
coreutils
|
||||
curl
|
||||
gitMinimal
|
||||
+ gcc16
|
||||
+ cmake
|
||||
+ ninja
|
||||
+ vulkan-headers
|
||||
+ vulkan-loader
|
||||
+ vulkan-tools
|
||||
+ rustc
|
||||
+ cargo
|
||||
nix
|
||||
nodejs_26
|
||||
wget
|
||||
@@ -0,0 +1,151 @@
|
||||
# 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=16G -e CPU_CORES=8 -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=16G -e CPU_CORES=8 -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";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user