Skip to content
infrahousePublic

About

Ephemeral GitHub Actions runners in Multipass VMs on a workstation.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

runnerd

Ephemeral GitHub Actions runners for a GitHub organization, in Ubuntu 24.04 VMs on a workstation.

Each slot is a Multipass VM built once from base.yaml (Docker CE, the pinned runner, pre-pulled images) and snapshotted, stopped, as clean. For every job runnerd restores the slot to that snapshot, boots it, registers a one-job runner with GitHub's just-in-time (JIT) API, and starts the runner in the slot. The runner takes one job and exits, and the slot is restored again. Nothing a job leaves behind reaches the next job, and the GitHub token that registers runners stays on the host: a slot only ever sees its own one-job registration.

runnerd runs on macOS (Multipass on QEMU) and on Windows 11 Pro (Multipass on Hyper-V). It is one Python file with no dependencies outside the standard library.

Security: keep these runners away from public repositories

runnerd registers its runners for the whole organization, in the runner group runner_group_id names (1, the Default group, if left out). Any repository the group serves can send jobs to your workstation. GitHub doesn't let a runner group serve public repositories unless you turn on Allow public repositories for it: leave that off. A pull request from a fork of a public repository would otherwise run its code on your machine.

Labels: who gets these runners

The slots carry the labels in the config's labels. The example configs give them ci, ephemeral, their architecture (X64 or ARM64), and location: / host: labels, and leave out self-hosted, Linux and any OS release label. A job lands on these slots only when every label in its runs-on is among them, so existing workflows that ask for self-hosted keep their runners.

To share jobs between these slots and runners elsewhere (in the cloud, say), give both a common label (ci in the examples) and have the jobs that may run anywhere ask for just that one. A job that needs a particular architecture adds X64 or ARM64.

A laptop pool sleeps and travels with the laptop, so a job there can die midway. Send it only jobs that are safe to rerun and that don't create cloud resources.

Hosts

The example configs, for a Mac and a Windows desktop with 128 GB each:

mac.json windows.json
Slots 3 × 4 vCPU, 16 GB, 60 GB disk 5 × 8 vCPU, 2–16 GB (Dynamic Memory), 60 GB disk
Arch label ARM64 X64
Multipass driver qemu hyperv (see Setup: Windows)
Power runs only on AC power; idle runners are released on battery always on

Dynamic Memory (Windows)

By default a Hyper-V VM holds all of its memory for as long as it runs, used or not: five idle 16 GB slots hold 80 GB. dynamic_memory in windows.json hands the slots Hyper-V Dynamic Memory instead:

"dynamic_memory": {"minimum": "2G", "startup": "4G", "maximum": "16G", "buffer": 20}

A slot boots with startup. Hyper-V adds memory as the job needs it, up to maximum, and takes back what it stops using, down to minimum. buffer is the percentage it keeps spare on top of what the slot uses (5 to 2000; 20 if left out). Sizes take M or G. runnerd sets this on every slot after every restore, while the slot is off, because restoring a snapshot can bring back the memory settings the snapshot was taken with.

So dynamic_memory works with reset: "snapshot" (the default) only. There, memory sizes the slot at build and has no effect after that. With reset: "relaunch", every launch gives the slot its fixed memory, and runnerd doesn't set Dynamic Memory.

Leave dynamic_memory out to give every slot its fixed memory. Multipass on the Mac has nothing like it.

Configuration

org, host, multipass, slots, labels and exactly one of token_file and token_command are required; the other keys have defaults.

Key Meaning
org The GitHub organization the runners register with.
host Names the slots (<host>-1, <host>-2, ...) and their runners. Unique per host.
multipass Full path of the multipass CLI.
slots, cpus, memory, disk How many slots, and each one's size: 4 CPUs, 16G and 60G if left out.
image The Multipass image; noble if left out.
cloud_init The slots' cloud-init file, relative to the config file; base.yaml if left out.
labels The runners' labels.
runner_group_id The runner group; 1 (Default) if left out.
token_file or token_command Exactly one: the token's file, or a command (an argument list) that prints it.
require_ac_power macOS: serve jobs only on AC power; false if left out.
reset snapshot (default) or relaunch (see Operating).
dynamic_memory Windows, with reset: "snapshot": see above. Left out, every slot has its fixed memory.

base.yaml pre-pulls postgres:18 and sets the AWS SDKs' default region to us-west-1. Change both (PREPULL_IMAGES and the region line) to suit your jobs, then rebuild.

GitHub token

runnerd needs a token that may register and remove the organization's self-hosted runners: a fine-grained personal access token, resource owner your organization, organization permission Self-hosted runners: Read and write, nothing else. The account that creates it must have admin access to the organization: GitHub refuses runner registration to anyone else, whatever the token's permissions. Keep the token on the host only.

  • Mac, in the login keychain (token_command in mac.json reads it):

    /usr/bin/security add-generic-password -U -a "$USER" -s runnerd-github-token -w
  • Windows, in a file only you and SYSTEM can open (token_file in windows.json). This makes C:\ProgramData\runnerd private, checks that it is, and only then asks for the token, without echoing it. If any step fails, it stops before the token is written:

    & {
        $ErrorActionPreference = 'Stop'
        $dir = 'C:\ProgramData\runnerd'
        $me = [Security.Principal.WindowsIdentity]::GetCurrent().User
        $system = New-Object Security.Principal.SecurityIdentifier 'S-1-5-18'
        New-Item -ItemType Directory -Force -Path $dir | Out-Null
        # On the directory and what is created in it: you may change, SYSTEM may read, nothing is inherited.
        & 'C:\Windows\System32\icacls.exe' $dir /inheritance:r `
            /grant:r "*$($me.Value):(OI)(CI)M" "*$($system.Value):(OI)(CI)R"
        if ($LASTEXITCODE -ne 0) { throw "icacls failed (exit $LASTEXITCODE); the token was not stored" }
        $acl = Get-Acl -Path $dir
        $others = $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) |
            Where-Object { $_.IdentityReference -ne $me -and $_.IdentityReference -ne $system }
        if (-not $acl.AreAccessRulesProtected -or $others) { throw "$dir is not private; the token was not stored" }
        # A token file from before may carry other permissions. The token goes into a new file, which inherits the
        # directory's; if the old one can't be deleted, or the new one can't be created, this stops here.
        $file = "$dir\github-token"
        if (Test-Path -LiteralPath $file) { Remove-Item -Force -LiteralPath $file }
        New-Item -ItemType File -Path $file | Out-Null
        $token = Read-Host -AsSecureString -Prompt 'GitHub token'
        Set-Content -NoNewline -LiteralPath $file -Value (New-Object Net.NetworkCredential '', $token).Password
    }

runnerd reads the token every time it registers a runner, so a rotated token needs no restart: store the new one with the same commands.

Setup: Mac

  1. Install Multipass from https://canonical.com/multipass/install. It installs /usr/local/bin/multipass.

    runnerd runs on /usr/bin/python3, which comes with Apple's Command Line Tools, as does /usr/bin/git. If /usr/bin/python3 --version doesn't print a version, install them (/usr/bin/xcode-select --install) and try again.

  2. Clone this repository to ~/runnerd (a clone, so that it can be upgraded: see Upgrading), and set org in mac.json:

    /usr/bin/git clone https://github.com/infrahouse/runnerd.git "$HOME/runnerd"
  3. Store the token (above).

  4. Build the slots (takes several minutes; they build in parallel):

    /usr/bin/python3 "$HOME/runnerd/runnerd.py" build --config "$HOME/runnerd/mac.json"
  5. Try it in the foreground, then stop it with Ctrl-C:

    /usr/bin/python3 "$HOME/runnerd/runnerd.py" run --config "$HOME/runnerd/mac.json"
  6. Run it at login:

    /bin/mkdir -p "$HOME/Library/LaunchAgents"
    /usr/bin/python3 - "$HOME" <<'EOF'
    import plistlib, sys
    home = sys.argv[1]
    with open(f"{home}/runnerd/com.infrahouse.runnerd.plist", "rb") as template:
        agent = plistlib.load(template)
    # __HOME__ is replaced in the parsed values, not in the file's text: any home path works.
    agent["ProgramArguments"] = [arg.replace("__HOME__", home) for arg in agent["ProgramArguments"]]
    for key in ("StandardOutPath", "StandardErrorPath"):
        agent[key] = agent[key].replace("__HOME__", home)
    with open(f"{home}/Library/LaunchAgents/com.infrahouse.runnerd.plist", "wb") as agent_file:
        plistlib.dump(agent, agent_file)
    EOF
    /bin/launchctl bootstrap "gui/$(/usr/bin/id -u)" "$HOME/Library/LaunchAgents/com.infrahouse.runnerd.plist"

    Its log is ~/Library/Logs/runnerd.log. While it runs, it keeps the Mac awake on AC power (caffeinate -s). A closed lid without an external display still puts the Mac to sleep.

Setup: Windows

  1. Turn on Hyper-V, in an elevated PowerShell, and restart Windows when it asks:

    Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All

    Then install Python, Git, and Multipass 1.17.2 from Canonical's installer, checked against the SHA-256 GitHub lists for it. If any step fails, the block stops:

    & "$env:LOCALAPPDATA\Microsoft\WindowsApps\winget.exe" install --exact --id Python.Python.3.13 --scope machine
    & "$env:LOCALAPPDATA\Microsoft\WindowsApps\winget.exe" install --exact --id Git.Git --scope machine
    & {
        $ErrorActionPreference = 'Stop'
        $ProgressPreference = 'SilentlyContinue'  # Invoke-WebRequest's progress bar slows the download down
        $release = 'https://github.com/canonical/multipass/releases/download/v1.17.2'
        $msi = "$env:TEMP\multipass-1.17.2+win-win64.msi"
        Invoke-WebRequest -UseBasicParsing -Uri "$release/multipass-1.17.2%2Bwin-win64.msi" -OutFile $msi
        $sha256 = 'F4E5E1C0055D3A8C87DB14B28681A4980F131013C8CA6A751B28A4A956B0B837'
        if ((Get-FileHash -Algorithm SHA256 -LiteralPath $msi).Hash -ne $sha256) { throw "${msi}: wrong SHA-256" }
        $install = Start-Process -Wait -PassThru -FilePath "$env:SystemRoot\System32\msiexec.exe" `
            -ArgumentList '/i', "`"$msi`""
        if ($install.ExitCode -notin 0, 3010) { throw "the Multipass installer exited $($install.ExitCode)" }
    }

    Then, before building any slot, switch Multipass to its Hyper-V driver:

    & 'C:\Program Files\Multipass\bin\multipass.exe' version
    & 'C:\Program Files\Multipass\bin\multipass.exe' set local.driver=hyperv
    & 'C:\Program Files\Multipass\bin\multipass.exe' get local.driver

    version must show 1.17.2, and the last command must print hyperv. Since 1.17, a new Multipass install on Windows uses the hcs driver, and hyperv is deprecated. runnerd needs hyperv: on Windows it manages the slots' VMs with Hyper-V's PowerShell cmdlets as well (save and resume off, Dynamic Memory, and turning the VMs off to bring back a stuck multipassd).

    Why 1.17.2, and not winget's Canonical.Multipass: Multipass 1.17.0 and earlier are open to GHSA-pp54-9c8c-vp5g (an instance can make multipass transfer -r write anywhere you can), fixed in 1.17.1, and winget's catalog can lag Canonical's releases. A later release works too, as long as it still has the hyperv driver: change the version and the SHA-256 above, and check that set local.driver=hyperv still succeeds.

    The commands below don't assume where Python and Git are: each block that runs them reads it from the registry, where their installers record an install for all users (--scope machine). Python's python.exe is the value ExecutablePath of HKLM:\SOFTWARE\Python\PythonCore\3.13\InstallPath, and Git's git.exe is in the cmd folder of the value InstallPath of HKLM:\SOFTWARE\GitForWindows. If a key or its value is missing, or the file isn't there, the block stops before it runs anything, and says what is missing. Once runnerd's scheduled task exists (step 6), the blocks that run runnerd's Python take its path from the task instead.

  2. Clone this repository to C:\runnerd (a clone, so that it can be upgraded: see Upgrading), and set org in windows.json:

    & {
        $ErrorActionPreference = 'Stop'
        $key = 'HKLM:\SOFTWARE\GitForWindows'
        $dir = (Get-ItemProperty -ErrorAction Ignore -LiteralPath $key).InstallPath
        $git = "$dir\cmd\git.exe"
        if (-not $dir -or -not (Test-Path -LiteralPath $git -PathType Leaf)) {
            throw "No git.exe in ${key} ('$dir'): install Git with --scope machine (setup step 1)"
        }
        & $git clone https://github.com/infrahouse/runnerd.git C:\runnerd
    }
  3. Store the token (above).

  4. Build the slots:

    & {
        $ErrorActionPreference = 'Stop'
        $key = 'HKLM:\SOFTWARE\Python\PythonCore\3.13\InstallPath'
        $python = (Get-ItemProperty -ErrorAction Ignore -LiteralPath $key).ExecutablePath
        if (-not $python -or -not (Test-Path -LiteralPath $python -PathType Leaf)) {
            throw "No python.exe in ${key} ('$python'): install Python 3.13 with --scope machine (setup step 1)"
        }
        & $python C:\runnerd\runnerd.py build --config C:\runnerd\windows.json
    }
  5. Try it in the foreground, then stop it with Ctrl-C:

    & {
        $ErrorActionPreference = 'Stop'
        $key = 'HKLM:\SOFTWARE\Python\PythonCore\3.13\InstallPath'
        $python = (Get-ItemProperty -ErrorAction Ignore -LiteralPath $key).ExecutablePath
        if (-not $python -or -not (Test-Path -LiteralPath $python -PathType Leaf)) {
            throw "No python.exe in ${key} ('$python'): install Python 3.13 with --scope machine (setup step 1)"
        }
        & $python C:\runnerd\runnerd.py run --config C:\runnerd\windows.json
    }
  6. Run it at boot, as you: Multipass instances belong to the user that created them. In an elevated PowerShell (it asks for your password):

    & {
        $ErrorActionPreference = 'Stop'
        $key = 'HKLM:\SOFTWARE\Python\PythonCore\3.13\InstallPath'
        $python = (Get-ItemProperty -ErrorAction Ignore -LiteralPath $key).ExecutablePath
        if (-not $python -or -not (Test-Path -LiteralPath $python -PathType Leaf)) {
            throw "No python.exe in ${key} ('$python'): install Python 3.13 with --scope machine (setup step 1)"
        }
        $user = "$env:USERDOMAIN\$env:USERNAME"
        $task = New-Object Xml.XmlDocument
        $task.Load('C:\runnerd\runnerd-task.xml')
        $ns = New-Object Xml.XmlNamespaceManager $task.NameTable
        $ns.AddNamespace('t', $task.DocumentElement.NamespaceURI)
        # As the elements' text, so that XML escapes them: a path such as C:\R&D\python.exe is fine.
        $task.SelectSingleNode('/t:Task/t:Principals/t:Principal/t:UserId', $ns).InnerText = $user
        $task.SelectSingleNode('/t:Task/t:Actions/t:Exec/t:Command', $ns).InnerText = $python
        # Save writes the encoding the declaration names: UTF-16, as in Task Scheduler's own exports.
        $task.FirstChild.Encoding = 'UTF-16'
        $task.Save("$env:TEMP\runnerd-task.xml")
        & 'C:\Windows\System32\schtasks.exe' /Create /F /TN runnerd /XML "$env:TEMP\runnerd-task.xml" /RU $user /RP *
        & 'C:\Windows\System32\schtasks.exe' /Run /TN runnerd
    }

    The task starts a minute after boot, without a logon, and restarts runnerd if it fails. Its log is C:\runnerd\runnerd.log. It runs the python.exe the block read from the registry: the task's command is that file's full path, and the Windows blocks in Upgrading that run runnerd's Python read it from there.

  7. Keep the box from sleeping on AC, and keep Windows Update from restarting it whenever it likes:

    & 'C:\Windows\System32\powercfg.exe' /change standby-timeout-ac 0

    Then set active hours in Settings → Windows Update → Advanced options. A restart fails the jobs in progress.

Operating

  • runnerd.py status --config <host>.json shows the slots.
  • Stopping run: the first Ctrl-C or SIGTERM drains it (idle runners are deregistered, busy ones finish their job). A second one stops it at once, without waiting for a slot that is restoring, booting or stopping its VM. It doesn't stop the VMs, though, and ending runnerd's multipass exec sessions doesn't end the runners in them: a job in progress can run on, unwatched, until the next run stops and restores every slot before it serves. On Windows, schtasks /End /TN runnerd stops it at once, the same way. On the Mac, launchctl bootout "gui/$(id -u)/com.infrahouse.runnerd" drains it and keeps launchd from starting it again, as KeepAlive does after any other exit; busy runners get the plist's ExitTimeOut (600 s).
  • Rebuild the slots (build --force, with runnerd stopped) when GitHub releases a new runner (bump the version and both SHA-256s in base.yaml first), and once a month for Ubuntu's security updates. Between rebuilds every job boots the same snapshot, so its packages get no newer. A runner that is behind updates itself at the start of every job, which costs time. Upgrading runnerd itself is below.
  • reset: "relaunch" in the config deletes and relaunches a slot from base.yaml for every job, instead of restoring the snapshot. It's slower (minutes per job). Use it only if the host's Multipass can't snapshot.
  • runnerd.py destroy --config <host>.json deletes the slots.

What runnerd does on its own, and logs:

  • At start, runnerd removes this host's runners from an earlier run (named <host>-<slot>-<8 hex>), which a run that was stopped at once, crashed or lost power left registered. One that GitHub doesn't report busy goes at once, online or offline, so that no job reaches it before its slot is restored. A busy one goes once runnerd has restored its slot, which ends it, or once GitHub no longer reports it busy. If GitHub refuses a removal, or doesn't answer, runnerd logs it and tries again a minute later, or as soon as a slot is restored; no slot waits for it. Once it has removed every leftover it found, runnerd asks GitHub again, and stops when GitHub lists none. If GitHub can't be reached at start, runnerd asks again every minute, and leaves alone the runners it has registered by then. A drain stops the removal; the next start takes it up again.
  • On Windows, before any slot starts, runnerd asks multipassd for one multipass list, and gives it 60 s. If it doesn't answer in that time, runnerd recovers it at once: it ends multipassd, turns the slots' VMs off in Hyper-V, and starts the service again. Without the check, each slot's first command would wait its own 120 s, one slot after another, before three timeouts in a row brought the recovery. If multipassd still doesn't answer after the recovery, the slots start all the same, and their timeouts bring the next recovery, 10 minutes after this one at the earliest.
  • When the multipass exec session to a runner ends, runnerd asks the slot whether the runner still runs (whether the run.sh --jitconfig that runnerd started is still a process there) before it restores the slot. A session that dropped (multipassd restarting, say) while the job goes on is followed again ("following it again" in the log). A slot whose VM has booted since runnerd started the runner has no runner left, whatever brought the VM back up (a recovery, multipass exec, a job that rebooted it): runnerd reads the VM's boot ID (/proc/sys/kernel/random/boot_id) before it starts a runner, and the runner starts only in that boot. When the boot ID has changed by the time runnerd asks, the slot restores at once ("has booted since its runner started" in the log). Until multipass can answer, the slot waits and asks again every minute; it never restores a slot on a guess, nor because GitHub no longer lists the runner, nor because a recovery turned its VM off: it asks the VM as it is then. On Windows, when multipass can't say how a slot's VM is (Unknown, or multipass list failing, as a recovery can leave it), Hyper-V is asked, and a VM that is off runs no runner.
  • A slot that multipass reports Unknown, Suspended or Starting, as a multipassd recovery on Windows can leave it, or one that doesn't stop gracefully, is forced off (multipass stop --force, Multipass 1.14 or later) before it's restored. build never forces: the clean snapshot must come from a clean shutdown.
  • If a slot stops on an error runnerd can't retry, run drains the other slots and exits 1, with the traceback in the log; launchd or the scheduled task starts it again.

Upgrading

An upgrade is a git pull of main in the clone the setup made, with runnerd stopped. A copy that isn't a clone (a ZIP download, say) can't pull: stop runnerd, clone the repository next to it, carry your config over, and swap the two folders.

  1. Fetch, and see what the upgrade would change:

    /usr/bin/git -C "$HOME/runnerd" fetch
    /usr/bin/git -C "$HOME/runnerd" log --oneline HEAD..origin/main
    /usr/bin/git -C "$HOME/runnerd" diff --stat HEAD origin/main
    & {
        $ErrorActionPreference = 'Stop'
        $key = 'HKLM:\SOFTWARE\GitForWindows'
        $dir = (Get-ItemProperty -ErrorAction Ignore -LiteralPath $key).InstallPath
        $git = "$dir\cmd\git.exe"
        if (-not $dir -or -not (Test-Path -LiteralPath $git -PathType Leaf)) {
            throw "No git.exe in ${key} ('$dir'): install Git with --scope machine (setup step 1)"
        }
        & $git -C C:\runnerd fetch
        & $git -C C:\runnerd log --oneline HEAD..origin/main
        & $git -C C:\runnerd diff --stat HEAD origin/main
    }

    The files that change say what else the upgrade takes:

    Changed Also
    base.yaml Rebuild the slots (step 4).
    mac.json or windows.json, which you edited Keep your settings (step 3).
    com.infrahouse.runnerd.plist or runnerd-task.xml Install it again (step 6 of the setup) after step 4.

    Anything else, runnerd.py included, needs only steps 2, 3 and 5.

  2. Stop runnerd.

    On the Mac, this drains it: idle runners are deregistered, busy ones finish their job (up to 600 s):

    /bin/launchctl bootout "gui/$(/usr/bin/id -u)/com.infrahouse.runnerd"

    Past the 600 s, launchd kills runnerd. A job still running then goes on in its slot, unwatched, until it ends, or until the slot is rebuilt (step 4) or restored by the start in step 5. If the job ends first, its one-job runner goes with it; if not, the start in step 5 removes the runner once it has restored the slot (see What runnerd does on its own).

    On Windows, schtasks /End stops runnerd at once, without a drain, and turning the slots off then fails a job in progress. First check that the host's runners are idle: the organization's settings list them, with their status, under Actions → Runners. Then, in an elevated PowerShell, stop runnerd and turn the slots' VMs off. A stopped runnerd leaves its runners registered and listening in the slots; turning the slots off keeps GitHub from handing one of them a job that the next start would kill. Hyper-V turns them off rather than multipass stop shutting them down: the next start restores every slot from its clean snapshot (or, with reset: "relaunch", launches it anew) before it serves, so a clean shutdown buys nothing, and multipass stop hangs when multipassd does (see step 4):

    & {
        $ErrorActionPreference = 'Stop'
        & 'C:\Windows\System32\schtasks.exe' /End /TN runnerd
        if ($LASTEXITCODE -ne 0) { throw "schtasks /End exited $LASTEXITCODE" }
        $config = Get-Content -Raw -LiteralPath C:\runnerd\windows.json | ConvertFrom-Json
        $slots = 1..$config.slots | ForEach-Object { "$($config.host)-$_" }
        Get-VM -Name $slots | Where-Object State -ne 'Off' | Stop-VM -TurnOff -Force
        Get-VM -Name $slots | Select-Object Name, State
    }

    GitHub shows those runners offline a minute or two later, and they take no jobs. The start in step 5 removes them at once: at start, runnerd removes an idle runner from an earlier run whether GitHub shows it online or offline (see What runnerd does on its own).

  3. Pull:

    /usr/bin/git -C "$HOME/runnerd" pull --ff-only
    & {
        $ErrorActionPreference = 'Stop'
        $key = 'HKLM:\SOFTWARE\GitForWindows'
        $dir = (Get-ItemProperty -ErrorAction Ignore -LiteralPath $key).InstallPath
        $git = "$dir\cmd\git.exe"
        if (-not $dir -or -not (Test-Path -LiteralPath $git -PathType Leaf)) {
            throw "No git.exe in ${key} ('$dir'): install Git with --scope machine (setup step 1)"
        }
        & $git -C C:\runnerd pull --ff-only
    }

    If git refuses because your changes to the config "would be overwritten by merge", it has changed nothing. Set your changes aside, pull, and bring them back:

    /usr/bin/git -C "$HOME/runnerd" stash
    /usr/bin/git -C "$HOME/runnerd" pull --ff-only
    /usr/bin/git -C "$HOME/runnerd" stash pop
    & {
        $ErrorActionPreference = 'Stop'
        $key = 'HKLM:\SOFTWARE\GitForWindows'
        $dir = (Get-ItemProperty -ErrorAction Ignore -LiteralPath $key).InstallPath
        $git = "$dir\cmd\git.exe"
        if (-not $dir -or -not (Test-Path -LiteralPath $git -PathType Leaf)) {
            throw "No git.exe in ${key} ('$dir'): install Git with --scope machine (setup step 1)"
        }
        & $git -C C:\runnerd stash
        & $git -C C:\runnerd pull --ff-only
        & $git -C C:\runnerd stash pop
    }

    If stash pop reports a conflict, the config has conflict markers in it, and runnerd can't read it: edit it to keep your settings and the new ones, then git reset -q and git stash drop. git pull --autostash is no shortcut here: when it conflicts, it leaves the markers in the config and exits 0 all the same.

  4. If base.yaml changed, rebuild the slots. On Windows, the block reads the path of the Python that runs runnerd from the scheduled task (setup step 6), and builds with it:

    /usr/bin/python3 "$HOME/runnerd/runnerd.py" build --force --config "$HOME/runnerd/mac.json"
    & {
        $ErrorActionPreference = 'Stop'
        $python = (Get-ScheduledTask -TaskName runnerd).Actions[0].Execute
        & $python C:\runnerd\runnerd.py build --force --config C:\runnerd\windows.json
    }

    On Windows, run brings back a multipassd that stopped answering, at start and while it serves (see What runnerd does on its own), but build doesn't. Hyper-V moves its Default Switch to a new subnet now and then, and multipassd then waits for the slots on the old one: every multipass command hangs, multipass list included. build then gives up on each slot once its command times out (120 s for multipass list, its first), logs the slot's failure with is multipassd responding? in it, and exits 1. When it fails that way, do what run does, in an elevated PowerShell: end multipassd, turn off the slots' VMs that aren't off (a build can have started some), and start the service again. A slot whose VM the build deleted is passed over. The block stops at the first command that fails:

    & {
        $ErrorActionPreference = 'Stop'
        $config = Get-Content -Raw -LiteralPath C:\runnerd\windows.json | ConvertFrom-Json
        $slots = 1..$config.slots | ForEach-Object { "$($config.host)-$_" }
        Get-Process -Name multipassd -ErrorAction SilentlyContinue | Stop-Process -Force
        Get-VM -Name $slots -ErrorAction SilentlyContinue | Where-Object State -ne 'Off' | Stop-VM -TurnOff -Force
        Start-Service -Name Multipass
        & 'C:\Program Files\Multipass\bin\multipass.exe' list
        if ($LASTEXITCODE -ne 0) { throw "multipass list exited $LASTEXITCODE" }
    }

    If multipass list fails or hangs right after the start, multipassd may not be up yet (run's recovery gives it up to 5 minutes): run & 'C:\Program Files\Multipass\bin\multipass.exe' list on its own again, not the block, which would end multipassd again.

    Once multipass list answers, run build --force again. The service starts again any slot it had as running when it ended, so multipass may report a slot Running or Unknown, not only Stopped. build --force deletes each slot that exists and launches it anew. A start of run, before a slot serves, leaves it as it is if it's Stopped, stops it if it's Running (forcing it off if it doesn't stop gracefully), and forces it off if it's Unknown; then it restores the slot's clean snapshot. With reset: "relaunch", the start deletes and relaunches each slot instead.

  5. Start runnerd, and check that every slot registers a runner and reports Listening for Jobs:

    /bin/launchctl bootstrap "gui/$(/usr/bin/id -u)" "$HOME/Library/LaunchAgents/com.infrahouse.runnerd.plist"
    /usr/bin/tail -f "$HOME/Library/Logs/runnerd.log"
    & 'C:\Windows\System32\schtasks.exe' /Run /TN runnerd
    Get-Content -Encoding UTF8 -Wait -Tail 30 -LiteralPath C:\runnerd\runnerd.log

Development

runnerd itself needs nothing outside Python's standard library. The tests and the linters (pytest, black, pylint) go in a virtualenv:

python3 -m venv .venv
. .venv/bin/activate
make bootstrap
make lint
make test

The tests stand in for multipass and GitHub: none of them starts a VM or calls GitHub. The ones in tests/test_runner_script.py run the slots' runner script, so they need a POSIX host (bash, /bin/bash and pgrep): on Windows they're skipped. make alone lists the targets.

Files

File What
runnerd.py The host side: build, run, status, destroy. Python 3.9+, standard library only.
base.yaml cloud-init for a slot.
mac.json, windows.json Example host settings.
com.infrahouse.runnerd.plist The Mac's LaunchAgent (a template).
runnerd-task.xml The Windows scheduled task (a template).
tests/ The tests (pytest).
Makefile, pyproject.toml, .pylintrc, requirements-dev.txt Development targets and the tools' settings.

License

Apache License 2.0; see LICENSE.

About

Ephemeral GitHub Actions runners in Multipass VMs on a workstation.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages