runnerversion

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 32 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package runnerversion is the self-healing runner version subsystem: a signed manifest describing the runner the fleet should be on, a verified content-addressed cache of runner archives, a selector that chooses between the embedded runner and a verified cached one, and a detector for runners that register and exit without ever receiving a job.

See docs/arch/self-healing-runner.md. The Controller drives it and cmd/ephemerd/selfheal.go assembles it; it is on by default and [runner.self_heal] enabled = false is the kill-switch.

Index

Constants

View Source
const (
	DefaultZeroWorkWindow    = 120 * time.Second
	DefaultZeroWorkThreshold = 3
	DefaultBreakerCooldown   = 15 * time.Minute
)
View Source
const (
	// DefaultMaxArchiveBytes is 512 MiB; the runner is ~150-200 MB.
	DefaultMaxArchiveBytes int64 = 512 << 20
	// DefaultMinFreeBytes is 5 GiB.
	DefaultMinFreeBytes uint64 = 5 << 30
)
View Source
const DefaultPollInterval = 6 * time.Hour

DefaultPollInterval is the manifest re-check cadence when nothing is failing. It is a BACKSTOP: the primary trigger is the zero-work breaker's OnDegraded -> Kick, which reconciles immediately. The poll only propagates a known-good pin to nodes that have not failed yet and catches a dropped kick, so it can be slow.

View Source
const SchemaVersion = 1

SchemaVersion is the only manifest schema this build understands. An unknown schema is rejected outright rather than best-effort parsed: a manifest is a security input, and "mostly understood" is not understood.

View Source
const SourceGitHubDownloads = "github-runners-downloads"

SourceName is the Candidate.Source value for this source.

View Source
const SourceManifest = "manifest"

SourceManifest is the Candidate.Source value for the signed manifest.

Variables

View Source
var (
	// ErrInsufficientDisk means the cache volume is below MinFreeBytes.
	ErrInsufficientDisk = errors.New("insufficient free disk for runner archive")
	// ErrFetch wraps transport failures.
	ErrFetch = errors.New("runner archive fetch failed")
)
View Source
var (
	// ErrNoPublicKey is returned when a key file holds no key (an empty or
	// comment-only .pub). Every verify fails closed in that state.
	ErrNoPublicKey = errors.New("no runner-manifest public key embedded")
	// ErrBadSignature is returned when a signature does not verify.
	ErrBadSignature = errors.New("runner manifest signature invalid")
	// ErrKeyMismatch is returned when the signature names a different key.
	ErrKeyMismatch = errors.New("runner manifest signed by a different key")
)
View Source
var (
	// ErrChecksumMismatch means the bytes did not hash to what was promised.
	ErrChecksumMismatch = errors.New("runner archive checksum mismatch")
	// ErrTooLarge means the stream exceeded the configured cap.
	ErrTooLarge = errors.New("runner archive exceeds size cap")
	// ErrNotInStore means the blob or its extraction is missing.
	ErrNotInStore = errors.New("runner archive not in store")
)
View Source
var (
	// ErrDisabled is returned when auto_upgrade is off.
	ErrDisabled = errors.New("runner auto-upgrade disabled (runner.self_heal.auto_upgrade = false)")
	// ErrSourcesDisagree means the manifest and GitHub do not describe the
	// same artifact. Either the manifest is stale or someone is lying;
	// both stop the upgrade (unless the break-glass window is open and
	// GitHub is strictly ahead).
	ErrSourcesDisagree = errors.New("runner sources disagree")
	// ErrManifestReplayed means the manifest is not newer than the last applied one.
	ErrManifestReplayed = errors.New("runner manifest not newer than last applied")
	// ErrWrongChannel means the manifest is for another channel.
	ErrWrongChannel = errors.New("runner manifest is for a different channel")
	// ErrDowngradeRefused means the manifest is older than current without rollback=true.
	ErrDowngradeRefused = errors.New("runner manifest would downgrade without rollback=true")
	// ErrBreakGlassCooldown means a break-glass fetch was attempted within
	// the cooldown of the previous one.
	ErrBreakGlassCooldown = errors.New("runner break-glass fetch already attempted within the breaker cooldown")
)
View Source
var ErrBelowFloor = errors.New("selected runner is below the manifest floor")

ErrBelowFloor is a sentinel for callers that turn BootReport.BelowFloor into a refusal to serve.

View Source
var ErrEncryptedSecretKey = errors.New("minisign secret key is password-protected; only unencrypted keys (minisign -G -W, or mage manifest:keygen) are supported")

ErrEncryptedSecretKey is returned for a password-protected key.

View Source
var ErrManifestFetch = errors.New("runner manifest fetch failed")

ErrManifestFetch wraps transport failures so callers can count them separately from signature failures.

View Source
var ErrManifestInvalid = errors.New("runner manifest invalid")

ErrManifestInvalid wraps every validation failure.

View Source
var ErrNoCandidate = errors.New("no runner candidate for platform")

ErrNoCandidate means the source had no entry for the platform.

View Source
var ErrNoRunnerTree = errors.New("not a runner tree")

ErrNoRunnerTree means the directory does not look like a runner tree.

View Source
var ListenerDepsFile = filepath.Join("bin", "Runner.Listener.deps.json")

ListenerDepsFile is the file ProbeRunnerTree reads, relative to the root.

Functions

func ArchiveExt

func ArchiveExt(platform string) string

ArchiveExt is the archive extension the runner ships for a platform key.

func ArchiveFilename

func ArchiveFilename(platform, version string) string

ArchiveFilename is the upstream release asset name for a platform+version.

func GenerateKeypair

func GenerateKeypair(rnd io.Reader) (*PublicKey, *SecretKey, error)

GenerateKeypair makes a fresh minisign keypair with a random key id. rnd may be nil for crypto/rand.

func HashReader

func HashReader(r io.Reader) (string, error)

HashReader hashes a stream (used to verify the embedded archive at boot).

func MatchesDeprecation

func MatchesDeprecation(line string) bool

MatchesDeprecation reports whether a log line carries a refusal marker.

func ParseListenerDepsVersion

func ParseListenerDepsVersion(data []byte) (string, error)

ParseListenerDepsVersion extracts the Listener version from a Runner.Listener.deps.json document.

func PlatformKey

func PlatformKey(goos, goarch string) string

PlatformKey maps GOOS/GOARCH to the manifest platform key.

func PrepareOverrideTree

func PrepareOverrideTree(dir string, image TreeInfo) error

PrepareOverrideTree makes a verified runner tree usable as the lowerdir of an overlay over the image's /home/runner: the image's unprivileged `runner` user (uid/gid from the probe) must own it, or the merged directory inherits root ownership from the lower and the runner cannot create _work/. No-op when the owner is unknown.

func Sign

func Sign(priv ed25519.PrivateKey, keyID [8]byte, data []byte, trustedComment string, prehash bool) string

Sign produces a .minisig file for data with a private key. It exists so tests (and an operator without the minisign binary) can produce signatures this verifier accepts; the fleet's real manifests are signed offline with minisign itself.

Types

type BootReport

type BootReport struct {
	Selected Selection
	// EmbeddedSHA256 is the hash of the embedded archive this boot.
	EmbeddedSHA256 string
	// EmbeddedMatchesManifest is true when the manifest lists the embedded
	// version for this platform and the hashes agree. False with a nil
	// manifest or when the manifest is for a different version.
	EmbeddedMatchesManifest bool
	// EmbeddedTampered is true when the manifest lists the embedded
	// version and the hashes DISAGREE. That is a build or supply-chain
	// problem, not a floor problem.
	EmbeddedTampered bool
	// BelowFloor is true when the selected runner is older than the
	// manifest floor and must not take work.
	BelowFloor bool
	// Cache holds the store's verification results (nil without a store).
	Cache []VerifyResult
	// Image is the official-image probe and override decision (nil when
	// Selector.ProbeImage is nil). ImageErr is a failed probe. ImageInfo
	// is the raw probe (version + owner), kept so the controller can
	// prepare an override tree and re-decide after a fetch without
	// probing again.
	Image     *ImageDecision
	ImageInfo TreeInfo
	ImageErr  error
}

BootReport is the outcome of BootVerify.

type BreakerState

type BreakerState int

BreakerState is the per-platform breaker state.

const (
	BreakerClosed BreakerState = iota
	BreakerOpen
	BreakerHalfOpen
)

func (BreakerState) String

func (b BreakerState) String() string

type Candidate

type Candidate struct {
	Platform string
	Version  string
	Filename string
	URL      string
	SHA256   string
	// Source names who said so ("manifest", "github-runners-downloads").
	Source string
}

Candidate is one source's statement of the current runner for a platform.

type Channel

type Channel string

Channel selects which manifests a node follows.

const (
	ChannelStable Channel = "stable"
	ChannelCanary Channel = "canary"
)

type Controller

type Controller struct {
	// contains filtered or unexported fields
}

Controller drives the subsystem. See the package comment on this file.

func NewController

func NewController(cfg ControllerConfig) (*Controller, error)

NewController validates the wiring and returns a controller that has not run yet.

func (*Controller) Kick

func (c *Controller) Kick(reason string)

Kick requests an out-of-band reconcile. Non-blocking; coalesces.

func (*Controller) OnDegraded

func (c *Controller) OnDegraded(platform string, streak int, reason string)

OnDegraded is the Detector's CLOSED→OPEN hook: wake the loop so the upgrade/override decision runs now rather than at the next poll.

func (*Controller) Reconcile

func (c *Controller) Reconcile(ctx context.Context, trigger string)

Reconcile runs one verify-decide-act pass. Exported for tests and for an operator-triggered re-check; Run calls it at boot, on every poll and on a breaker kick.

func (*Controller) Report

func (c *Controller) Report() (BootReport, *Manifest, error)

Report returns the last reconcile's outcome (for status/healthz).

func (*Controller) Run

func (c *Controller) Run(ctx context.Context)

Run performs the boot reconcile and then polls until ctx is done.

type ControllerConfig

type ControllerConfig struct {
	// Platform is PlatformKey(GOOS, GOARCH) of THIS daemon's runner — the
	// one the mounted paths serve and the one the break-glass fetch
	// downloads.
	Platform string
	// Channel is the node's manifest channel ("" = accept any).
	Channel Channel
	// PollInterval is the backstop manifest re-check cadence. <= 0 =
	// DefaultPollInterval (6h). Failure (a breaker trip) is the primary
	// trigger and reconciles at once regardless of this.
	PollInterval time.Duration
	// BreakGlassCooldown bounds break-glass fetches to one per breaker
	// cooldown. <= 0 = DefaultBreakerCooldown. Normally the detector's
	// Cooldown.
	BreakGlassCooldown time.Duration
	// AutoUpgrade enables the break-glass fetch ([runner.self_heal]
	// auto_upgrade).
	AutoUpgrade bool
	// ImageOverride enables masking a stale official-image runner
	// ([runner.self_heal] image_override).
	ImageOverride bool
	// Image is the official Linux runner image this node runs jobs on;
	// "" = this daemon has no official-image path (Windows/macOS hosts).
	Image string

	Manifest ManifestLoader // required
	Selector *Selector      // required
	Override *ImageOverride // required when Image != ""
	// Store/Fetcher/GitHub are the fetch dependencies; any nil disables
	// the break-glass fetch (logged once at Run).
	Store   *Store
	Fetcher *Fetcher
	GitHub  Source
	// Detector is the zero-work detector (nil on a worker daemon that has
	// no scheduler). The controller installs itself as its OnDegraded.
	Detector *Detector
	// ProbeImage reads the runner baked into Image (runtime.ProbeImageRunner).
	ProbeImage func(ctx context.Context, image string) (TreeInfo, error)
	// SweepProbes removes probe views leaked by a previous boot
	// (runtime.SweepRunnerProbeViews). Optional.
	SweepProbes func(ctx context.Context) int

	Log *slog.Logger
	Now func() time.Time
}

ControllerConfig wires the controller.

type Detector

type Detector struct {
	// Window is the registered→self-exit lifetime below which a runner
	// with no job-started signal is zero-work. Default 120s.
	Window time.Duration
	// Threshold is the consecutive zero-work count per platform that opens
	// the breaker. Default 3.
	Threshold int
	// Cooldown is how long the breaker stays OPEN before allowing one
	// probe (HALF-OPEN). Default 15m.
	Cooldown time.Duration
	// OnDegraded is called once per CLOSED→OPEN transition. Alert + (when
	// enabled) upgrade hook. Called without the lock held.
	OnDegraded func(platform string, streak int, reason string)
	Log        *slog.Logger
	Now        func() time.Time
	// contains filtered or unexported fields
}

Detector is mechanism 2: it recognises a runner that registered and exited on its own, quickly, without any job-started signal, and trips a per-platform circuit breaker after Threshold such runners in a row.

exit_code is deliberately NOT an input: run.sh exits 0 after a refused connection, a completed job and a cancelled job alike.

Wired through scheduler.Config.RunnerHealth: Registered from trackRunning, JobStarted from handleInProgress and the busy probe, Exited from the wait goroutines with killedByUs = (jobCtx.Err() != nil), Allow from admitDispatch. OnDegraded is installed by the Controller.

func (*Detector) Allow

func (d *Detector) Allow(platform string) bool

Allow reports whether the scheduler may provision a runner for platform. CLOSED: yes. OPEN: no until Cooldown elapses, then HALF-OPEN. HALF-OPEN: exactly one probe; further calls say no until that probe exits.

func (*Detector) Exited

func (d *Detector) Exited(runnerName string, killedByUs bool) Verdict

Exited records that a runner's process ended. killedByUs must be true when ephemerd ended it (timeout, drain, orphan sweep, shutdown); such exits are never zero-work. Returns the verdict; the caller does nothing with it except log — the breaker and OnDegraded are driven here.

func (*Detector) JobStarted

func (d *Detector) JobStarted(runnerName string)

JobStarted records a job-started signal for a runner (in_progress webhook naming it, or a busy poll). It resets the platform's streak and closes its breaker: the platform is demonstrably dispatching to our runners.

func (*Detector) Registered

func (d *Detector) Registered(runnerName, platform string)

Registered records that a runner was provisioned on a platform.

func (*Detector) Reset

func (d *Detector) Reset(platform string)

Reset closes a platform's breaker (operator action, or after an upgrade so the next runner is admitted immediately rather than after Cooldown).

func (*Detector) State

func (d *Detector) State(platform string) (BreakerState, int)

State returns the breaker state and streak for a platform.

func (*Detector) Tracked

func (d *Detector) Tracked() int

Tracked is the number of runners registered and not yet exited.

type DiagHit

type DiagHit struct {
	File string
	Line string
}

DiagHit is a corroborating line from a runner diag log.

func ScanDiag

func ScanDiag(runnerDir string) (DiagHit, bool, error)

ScanDiag looks through <runnerDir>/_diag/Runner_*.log for a deprecation marker. Returns the first hit. A missing _diag directory is not an error (dispatched runners keep theirs in the guest), just no hit.

type Fetcher

type Fetcher struct {
	Store *Store
	// Client is the HTTP client; nil uses a 10-minute-timeout default.
	Client *http.Client
	// MaxBytes caps the archive size. 0 = DefaultMaxArchiveBytes.
	MaxBytes int64
	// MinFreeBytes refuses a fetch when the cache volume has less free.
	// 0 = DefaultMinFreeBytes.
	MinFreeBytes uint64
	// DiskCheck is diskspace.Check; replaceable for tests.
	DiskCheck func(path string) (diskspace.Usage, error)
	Log       *slog.Logger
	// contains filtered or unexported fields
}

Fetcher downloads a runner archive into the Store with every guard the design requires: https only, free-space check before the first byte, a size cap on the wire, hash-verify before commit (Store.Put), and single-flight per SHA so concurrent callers share one download.

func (*Fetcher) Fetch

func (f *Fetcher) Fetch(ctx context.Context, url string, meta Sidecar) (string, error)

Fetch downloads url and commits it as meta.SHA256. meta.Platform decides the extension. Returns the blob path. Already-present blobs return at once without touching the network.

type GitHubSource

type GitHubSource struct {
	Client *gh.Client
	Owner  string
	// Repo is optional; empty uses the org endpoint.
	Repo string
	// contains filtered or unexported fields
}

GitHubSource resolves via GET /repos/{owner}/{repo}/actions/runners/downloads (or the /orgs/{org}/ form when Repo is empty). GitHub returns, per platform, download_url, filename and sha256_checksum — its own statement of the current runner's hash, which the upgrader cross-checks against the signed manifest. The call needs the same administration permission JIT registration already uses.

func (*GitHubSource) Resolve

func (g *GitHubSource) Resolve(ctx context.Context, platform string) (Candidate, error)

Resolve picks the entry whose os/architecture match platform.

type HTTPManifestLoader

type HTTPManifestLoader struct {
	URL    string
	Key    *PublicKey
	Client *http.Client
}

HTTPManifestLoader fetches runner-manifest.json and its detached .minisig over HTTPS and verifies the pair with Key.

func (*HTTPManifestLoader) Load

func (l *HTTPManifestLoader) Load(ctx context.Context) (*Manifest, error)

Load fetches, verifies, parses.

type ImageDecision

type ImageDecision struct {
	// Override is true when the image's runner should be masked by the
	// available tree.
	Override bool
	// ImageVersion is what the image ships; AvailableVersion is what would
	// be mounted over it.
	ImageVersion, AvailableVersion string
	// ImageBelowFloor is true when a manifest was given and the image is
	// older than its floor.
	ImageBelowFloor bool
	// NeedFetch is true when nothing on the node is good enough and the
	// break-glass fetch is the only way to an override.
	NeedFetch bool
	Reason    string
}

ImageDecision is DecideImageOverride's output.

func DecideImageOverride

func DecideImageOverride(image TreeInfo, available Selection, m *Manifest, breakerOpen bool) ImageDecision

DecideImageOverride decides whether the runner baked into an official image must be masked. Inputs:

image     — the image's /home/runner probe (version "" = probe failed)
available — the best verified tree on the node (Selector.Select)
m         — the verified manifest, or nil when unavailable
breakerOpen — the linux zero-work breaker has tripped

The image is stale when it is below the manifest floor, or — with no manifest — when the breaker tripped and the available tree is newer, or — with a manifest — when the breaker tripped AND the available tree is newer than the manifest's own version (a break-glass fetch of GitHub's latest; the manifest cannot vouch for a version it does not know, so the breaker's evidence decides). The override engages only when the available tree is strictly newer than the image AND itself at or above the floor; otherwise NeedFetch says the break-glass fetch is required first. A healthy image is never masked on the breaker alone when the manifest is current.

type ImageOverride

type ImageOverride struct {
	// contains filtered or unexported fields
}

ImageOverride holds the currently engaged override, if any. Safe for concurrent use; the runtime reads it on every Create.

func NewImageOverride

func NewImageOverride(log *slog.Logger) *ImageOverride

NewImageOverride returns an inactive override.

func (*ImageOverride) Clear

func (o *ImageOverride) Clear(reason string)

Clear deactivates the override.

func (*ImageOverride) Engage

func (o *ImageOverride) Engage(dir, version, image, reason string)

Engage activates the override with a verified runner tree. Fires the fixed, grep-able alert line; the override stays engaged across jobs until Clear or until a rebuilt image makes it unnecessary.

func (*ImageOverride) OfficialRunnerOverride

func (o *ImageOverride) OfficialRunnerOverride(image string) (string, bool)

OfficialRunnerOverride is the runtime-facing lookup: for an official image it returns the host directory to mount over /home/runner and true, or "", false when no override is engaged. The image argument is recorded for the alert; the override applies to every official image on the node, since all of them are FROM the same upstream runner.

func (*ImageOverride) Status

func (o *ImageOverride) Status() (active bool, dir, version, image, reason string, since time.Time)

Status reports the override for /healthz and logs.

type Manifest

type Manifest struct {
	SchemaVersion int                         `json:"schema_version"`
	Version       string                      `json:"version"`
	Floor         string                      `json:"floor"`
	Channel       Channel                     `json:"channel"`
	Rollback      bool                        `json:"rollback"`
	PublishedAt   time.Time                   `json:"published_at"`
	Platforms     map[string]PlatformArtifact `json:"platforms"`
}

Manifest is the signed runner-manifest.json document.

func ParseManifest

func ParseManifest(data []byte) (*Manifest, error)

ParseManifest decodes and validates a manifest. It does NOT verify a signature — callers must verify the bytes first (see PublicKey.Verify and VerifyAndParse); this is the parsing half only.

func (*Manifest) Artifact

func (m *Manifest) Artifact(platform string) (PlatformArtifact, error)

Artifact returns the entry for a platform key.

func (*Manifest) BelowFloor

func (m *Manifest) BelowFloor(v []int) bool

BelowFloor reports whether v is older than the manifest floor.

func (*Manifest) FloorParts

func (m *Manifest) FloorParts() []int

FloorParts is Floor parsed for comparison.

func (*Manifest) Validate

func (m *Manifest) Validate() error

Validate checks the manifest's internal consistency.

func (*Manifest) VersionParts

func (m *Manifest) VersionParts() []int

VersionParts is Version parsed for comparison.

type ManifestLoader

type ManifestLoader interface {
	Load(ctx context.Context) (*Manifest, error)
}

ManifestLoader produces a VERIFIED manifest. Implementations must not return a manifest whose signature did not check out.

type ManifestSource

type ManifestSource struct{ Manifest *Manifest }

ManifestSource adapts a verified Manifest to the Source interface.

func (ManifestSource) Resolve

func (m ManifestSource) Resolve(_ context.Context, platform string) (Candidate, error)

Resolve returns the manifest's entry for platform.

type PlatformArtifact

type PlatformArtifact struct {
	URL    string `json:"url"`
	SHA256 string `json:"sha256"`
}

PlatformArtifact is one platform's archive in a Manifest.

type Pointer

type Pointer struct {
	SHA256    string    `json:"sha256"`
	Version   string    `json:"version"`
	Ext       string    `json:"ext"`
	Dir       string    `json:"dir"`
	AppliedAt time.Time `json:"applied_at"`
}

Pointer is the content of the current/previous files.

type PublicKey

type PublicKey struct {
	KeyID [8]byte
	Key   ed25519.PublicKey
}

PublicKey is a parsed minisign public key.

func EmbeddedPublicKey

func EmbeddedPublicKey() (*PublicKey, error)

EmbeddedPublicKey returns the key compiled into this binary.

func ParsePublicKey

func ParsePublicKey(text string) (*PublicKey, error)

ParsePublicKey accepts either a whole .pub file or just its base64 line.

func (*PublicKey) EncodeFile

func (pk *PublicKey) EncodeFile(untrustedComment string) string

EncodeFile returns the public key as a minisign .pub file.

func (*PublicKey) String

func (pk *PublicKey) String() string

String renders the key in minisign's base64 form.

func (*PublicKey) Verify

func (pk *PublicKey) Verify(data []byte, sigText string) error

Verify checks sigText (a .minisig file) over data under this key.

func (*PublicKey) VerifyAndParse

func (pk *PublicKey) VerifyAndParse(data []byte, sigText string) (*Manifest, error)

VerifyAndParse verifies the signature FIRST and only then parses the manifest. Unverified bytes never reach the JSON decoder.

type Result

type Result struct {
	Version string
	SHA256  string
	Dir     string
	// Swapped is true when a new runner became current.
	Swapped bool
	// BreakGlass is true when the runner that became current (or was
	// confirmed current) was fetched on GitHub's word alone.
	BreakGlass bool
	// Reason is a short human string for the log/alert.
	Reason string
}

Result describes what Run did.

type SecretKey

type SecretKey struct {
	KeyID [8]byte
	Key   ed25519.PrivateKey
}

SecretKey is a parsed minisign secret key.

func ParseSecretKey

func ParseSecretKey(text string) (*SecretKey, error)

ParseSecretKey accepts a whole .key file or just its base64 line.

func (*SecretKey) Encode

func (sk *SecretKey) Encode(untrustedComment string) string

Encode returns the secret key as an unencrypted minisign .key file.

func (*SecretKey) Public

func (sk *SecretKey) Public() *PublicKey

Public returns the matching public key.

func (*SecretKey) Sign

func (sk *SecretKey) Sign(data []byte, trustedComment string) string

Sign signs data the way current minisign does (pre-hashed, "ED") with a trusted comment, returning the .minisig file text.

type Selection

type Selection struct {
	Dir     string
	Version string
	Parts   []int
	// Source is metrics.RunnerSourceEmbedded, RunnerSourceVerifiedCache or
	// RunnerSourceGitHubBreakGlass.
	Source string
	// BreakGlass is true when the cache entry was fetched on GitHub's word
	// alone and no signed manifest has covered it yet (its sidecar lists
	// no manifest source). Read from the sidecar on every Select, so the
	// label is right across restarts and clears the moment a manifest
	// catches up.
	BreakGlass bool
}

Selection is the chosen runner.

type Selector

type Selector struct {
	Embedded *runner.Manager
	Store    *Store
	Log      *slog.Logger
	// HashEmbedded overrides how BootVerify hashes the embedded archive
	// (tests: the test binary embeds no runner). Nil = read it from the
	// embedded FS.
	HashEmbedded func() (string, error)
	// ProbeImage reads the runner baked into the official Linux image this
	// node dispatches to (runtime.ProbeImageRunner). Nil = no image path on
	// this node (Windows/macOS hosts, or a custom default image). This is
	// the dominant path on the fleet: see override.go.
	ProbeImage func() (TreeInfo, error)
	// BreakerOpen reports whether the linux zero-work breaker has tripped;
	// consulted by the image decision when no manifest is available.
	BreakerOpen func() bool
}

Selector chooses the runner directory to serve: the highest version among the embedded runner and the verified cache's current entry, with the embedded runner as the last-resort floor.

Integration (cmd/ephemerd/selfheal.go): runtime.Config.RunnerDir stays the embedded tree; the runtime consults MountedRunnerDir on every Create (pkg/runtime.MountedRunnerSource) so a verified-cache runner takes effect on the next job. The Selector wraps *runner.Manager; it does not change runner.go's own selection among embedded archives.

func (*Selector) BootVerify

func (s *Selector) BootVerify(m *Manifest, platform string) (BootReport, error)

BootVerify is mechanism 1: re-hash the embedded archive, verify the cache's blobs, select, and compare against the manifest floor. m may be nil (manifest unavailable), in which case only the hash checks run.

func (*Selector) Dir

func (s *Selector) Dir() string

Dir is Select().Dir and also publishes ephemerd_runner_version_info.

func (*Selector) MountedRunnerDir

func (s *Selector) MountedRunnerDir() (string, bool)

MountedRunnerDir is the runtime-facing lookup for the MOUNTED runner paths (custom Linux images, Windows): it returns the verified-cache runner directory and true when the cache holds a runner strictly newer than the embedded one, or "", false when the configured (embedded) tree should be mounted. Consulted on every Create, so a break-glass fetch takes effect on the next job without a restart. It satisfies pkg/runtime.MountedRunnerSource.

func (*Selector) Select

func (s *Selector) Select() Selection

Select picks the runner. It never returns an error: with no usable cache entry the embedded runner wins, which is exactly today's behaviour.

type Sidecar

type Sidecar struct {
	Version   string    `json:"version"`
	Platform  string    `json:"platform"`
	URL       string    `json:"url"`
	SHA256    string    `json:"sha256"`
	Size      int64     `json:"size"`
	FetchedAt time.Time `json:"fetched_at"`
	// Sources names every party that vouched for SHA256 ("manifest",
	// "github-runners-downloads", ...). Informational.
	Sources []string `json:"sources"`
}

Sidecar records where a blob came from and what verified it.

func (Sidecar) HasSource

func (sc Sidecar) HasSource(source string) bool

HasSource reports whether source vouched for this blob.

func (Sidecar) IsBreakGlass

func (sc Sidecar) IsBreakGlass() bool

IsBreakGlass reports whether GitHub's runners/downloads is the ONLY party that vouched for this blob — the audit signature of the break-glass path (Upgrader.breakGlass). It flips to false the moment a signed manifest is recorded as a second source.

type Signature

type Signature struct {
	Prehashed      bool
	KeyID          [8]byte
	Sig            []byte
	TrustedComment string
	GlobalSig      []byte
}

Signature is a parsed minisign .minisig file.

func ParseSignature

func ParseSignature(text string) (*Signature, error)

ParseSignature parses a .minisig file.

type Source

type Source interface {
	Resolve(ctx context.Context, platform string) (Candidate, error)
}

Source resolves the current runner for a platform.

type StaticManifestLoader

type StaticManifestLoader struct{ Manifest *Manifest }

StaticManifestLoader returns a fixed, already-verified manifest. For tests and for the `ephemerd runner-manifest check` style tooling.

func (StaticManifestLoader) Load

Load returns the manifest.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is the content-addressed cache of verified runner archives.

Layout under <dataDir>/runners/verified:

blobs/<sha256>.<ext>      the archive, named by its hash
blobs/<sha256>.json       sidecar (Sidecar)
extracted/<version>-<goos>/   extracted tree, ".extracted" marker last
current                   Pointer: what the selector should serve
previous                  the Pointer that current replaced
applied-manifest          RFC3339 published_at of the last applied manifest

Invariants: nothing is extracted before its hash verified over the whole file (Put); the cache holds at most current+previous (Prune); pointer updates are an atomic rename (Swap).

func NewStore

func NewStore(dataDir string, log *slog.Logger) *Store

NewStore creates a store rooted at <dataDir>/runners/verified. Init must be called before use.

func (*Store) AddSidecarSource

func (s *Store) AddSidecarSource(sha, source string) error

AddSidecarSource records that another party vouched for a blob's hash (a re-signed manifest catching up with a break-glass fetch). No-op when the source is already listed.

func (*Store) Current

func (s *Store) Current() (Pointer, bool, error)

Current returns the current pointer, if any.

func (*Store) Extract

func (s *Store) Extract(sha, version string) (string, error)

Extract unpacks a committed blob into extracted/<version>-<goos>. It is a no-op when the marker already exists. The blob must have been committed through Put (hash verified); Extract re-checks the sidecar exists but does not re-hash — that is Verify's job at boot.

func (*Store) Has

func (s *Store) Has(sha, ext string) bool

Has reports whether a verified blob with this hash is present.

func (*Store) Init

func (s *Store) Init() error

Init creates the directories and removes temp files left by a crash.

func (*Store) LastApplied

func (s *Store) LastApplied() (time.Time, error)

LastApplied is the published_at of the last manifest that caused a swap; manifests at or before it are replays and ignored.

func (*Store) Previous

func (s *Store) Previous() (Pointer, bool, error)

Previous returns the previous pointer, if any.

func (*Store) Prune

func (s *Store) Prune() error

Prune deletes every blob, sidecar and extracted directory not referenced by current or previous. The cache is bounded to those two; the fleet has died from full disks before.

func (*Store) Put

func (s *Store) Put(r io.Reader, meta Sidecar, maxBytes int64) (string, error)

Put streams r into the store, hashing as it goes, and commits the blob ONLY if the hash equals meta.SHA256 and the size stays under maxBytes. On any failure the temp file is removed and nothing is committed. Returns the blob path.

func (*Store) Rollback

func (s *Store) Rollback() error

Rollback makes previous current (and current previous).

func (*Store) Root

func (s *Store) Root() string

Root is the store directory.

func (*Store) SetLastApplied

func (s *Store) SetLastApplied(t time.Time) error

SetLastApplied records a manifest's published_at.

func (*Store) Sidecar

func (s *Store) Sidecar(sha string) (Sidecar, error)

Sidecar reads a blob's sidecar.

func (*Store) Swap

func (s *Store) Swap(sha, version string) error

Swap makes <sha,version> current. The blob must be committed and extracted. The pointer is replaced atomically; the old pointer becomes previous. Swap never deletes anything — call Prune afterwards.

func (*Store) Verify

func (s *Store) Verify() []VerifyResult

Verify re-hashes the blobs behind current and previous. A blob whose hash no longer matches its name is deleted along with its extraction and its pointer, so the selector can never pick it. Returns one result per pointer that existed.

type TreeInfo

type TreeInfo struct {
	Dir     string
	Version string
	Parts   []int
	// UID/GID own the tree's root directory. An overlay mounted over the
	// image's /home/runner must present the same owner, or the image's
	// unprivileged `runner` user cannot create _work/. -1 when unknown
	// (non-Unix host).
	UID, GID int
}

TreeInfo describes a runner tree on disk.

func ProbeRunnerTree

func ProbeRunnerTree(dir string) (TreeInfo, error)

ProbeRunnerTree reads the runner version and ownership of a tree rooted at dir. It works on any runner tree: the embedded extraction, a verified cache entry, or an image's /home/runner mounted read-only.

type Upgrader

type Upgrader struct {
	// AutoUpgrade is [runner.self_heal] auto_upgrade. Default false.
	AutoUpgrade bool
	// Channel is the node's channel; manifests on another are ignored.
	Channel Channel
	// Platform is PlatformKey(GOOS, GOARCH) of the runner this node serves.
	Platform string

	Manifest ManifestLoader
	GitHub   Source
	Fetcher  *Fetcher
	Store    *Store
	Log      *slog.Logger
	Now      func() time.Time

	// BreakGlassOpen reports whether the break-glass window is open: the
	// zero-work breaker for the platform class this runner serves is OPEN,
	// i.e. the fleet is empirically dying on the runner it has. Nil = the
	// window never opens (no detector on this daemon).
	BreakGlassOpen func() bool
	// BreakGlassCooldown is the minimum time between two break-glass
	// attempts (one shot per breaker cooldown). <= 0 = DefaultBreakerCooldown.
	BreakGlassCooldown time.Duration
	// contains filtered or unexported fields
}

Upgrader is the break-glass path: resolve the current runner from TWO independent sources (the operator-signed manifest and GitHub's own runners/downloads statement), require them to agree on version and SHA-256, fetch, verify, extract, swap. It is gated on AutoUpgrade and returns ErrDisabled before touching the network when that is false.

Host daemon only. Nothing here may run inside a job VM or container.

ONE exception to the two-source rule exists, and it is the only path in ephemerd where GitHub's REST API is the sole authority for a binary the fleet runs as root: see breakGlass below. It never applies in steady state.

func (*Upgrader) Run

func (u *Upgrader) Run(ctx context.Context) (Result, error)

Run performs one upgrade attempt. Safe to call repeatedly: when the store is already on the manifest's version it returns Swapped=false.

type Verdict

type Verdict struct {
	Runner   string
	Platform string
	Lifetime time.Duration
	ZeroWork bool
	// Reason: "job-started", "killed-by-us", "lived-past-window",
	// "unknown-runner", or "zero-work".
	Reason string
	// Streak is the platform's consecutive zero-work count after this exit.
	Streak int
	// Opened is true when THIS exit opened the breaker.
	Opened bool
}

Verdict is Exited's judgement of one runner.

type VerifyResult

type VerifyResult struct {
	Pointer Pointer
	OK      bool
	Err     error
}

VerifyResult is one pointer's boot-time verification.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL