Skip to main content

runnerd_core/scheduler/
engine.rs

1//! The scheduling loop: polls GitHub, pulls the profiles' images, applies `plan`'s decisions with GitHub and
2//! Docker, removes each runner's container when its job ends, keeps the mirror up while any runner runs, reseeds
3//! idle profiles and recovers runners and containers a previous daemon left. It also feeds the job history: queued
4//! jobs, the job each runner took (from `observe::capture`), steps from GitHub, mirror bytes, cache sizes and slot
5//! and budget changes. It owns slot state; it never serves the API (it publishes `api::Status` and takes commands
6//! through `Control`) and never logs the token or a JIT config.
7//!
8//! This module holds `Engine`'s state, its construction and its loop; the submodules each add one concern's
9//! methods: `recover` (startup), `tick` (polling and planning), `runners` (a slot's runner from start to removal),
10//! `leftovers` (the containers still to read or remove once nothing occupies them), `listing` (what a repository's last listing of queued jobs showed), `listing_pace` (when a repository is listed next), `ledger` (the jobs followed on GitHub, queued or closing), `claims` (what a repository's listings may show that this machine's runners took), `images` (pulling the profiles' images), `caches` (reseeds, the mirror and the shared caches), `upkeep` (what each
11//! profile's measures and reseeds are doing and have due), `presence` (which repositories are listed or draining), `registrations` (what is remembered of a registration with no slot), `watches` (how each runner's container is watched: its log capture and what broken ones left), `mirror` (whether the mirror runs and at what cap), `build_cache` (each runner's side of the shared build cache and whether its job
12//! may write), `history` (what the store records), `warm` (how many warm runners each repository wants), `control` (the
13//! API's commands), `stop` (how far the daemon's stop has got) and `status` (what it publishes).
14
15mod admission;
16mod build_cache;
17mod caches;
18mod claims;
19mod clock;
20mod control;
21mod engagement;
22mod exits;
23mod governor;
24mod history;
25mod images;
26mod ledger;
27mod leftovers;
28mod listing;
29mod listing_pace;
30mod mirror;
31mod open_waits;
32mod pool_health;
33mod presence;
34mod records;
35mod recover;
36mod registrations;
37mod repository_state;
38mod runner_exit;
39mod runners;
40mod running_reads;
41mod slot;
42mod start;
43mod status;
44mod stop;
45mod tick;
46mod unsynced;
47mod upkeep;
48mod warm;
49mod watches;
50
51use std::collections::{BTreeMap, BTreeSet};
52use std::path::PathBuf;
53use std::sync::{Arc, Mutex};
54use std::time::{Duration, SystemTime};
55
56use tokio::sync::{mpsc, watch};
57use tokio::task::JoinHandle;
58use tracing::{info, warn};
59
60use self::claims::Claims;
61use self::clock::Clock;
62pub use self::control::{
63    Author, Command, Commands, Commit, Control, ControlError, RunningJobs, RunningSlots, Shutdown,
64    Target, same_slice,
65};
66use self::engagement::{Engagement, Mark};
67use self::history::{CAPTURE_DRAIN, Found};
68use self::images::Images;
69use self::ledger::Ledger;
70use self::leftovers::Leftovers;
71use self::mirror::Mirror;
72use self::presence::Repositories;
73pub use self::records::RecordSelection;
74use self::registrations::Registrations;
75use self::repository_state::RepositoryState;
76use self::slot::Slot;
77use self::tick::Scope;
78pub use self::unsynced::Durability;
79use self::unsynced::Unsynced;
80use self::upkeep::Upkeep;
81use self::watches::Watches;
82use super::SlotRef;
83use crate::actions::JobActions;
84use crate::admission::Key;
85use crate::api;
86use crate::buildcache::BuildCache;
87use crate::cache::{self, Names, Trimmed};
88use crate::config::Config;
89use crate::docker::{self, Docker, DockerApi};
90use crate::github::{Github, GithubApi};
91use crate::isolation::{self, Isolation};
92use crate::observe::metrics::{self, Paths, Sampler, Tracked};
93use crate::observe::mirror::Leases;
94use crate::store::{Announced, MirrorPosition, Store};
95
96/// This machine as its runner names carry it: `runnerd-<id>-<host>-<profile>-<slot>-<secs>`. Only `runnerd-<id>-`
97/// identifies the machine, so a changed host name still matches the runners started before the change, and two
98/// machines with the same or overlapping host names never take each other's runners for their own.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct HostIdentity {
101    /// 8 hex digits: a hash of the systemd machine ID, never the ID itself, as machine-id(5) asks.
102    id: String,
103    /// The host name in lower case, letters, digits and dashes, at most 20 characters: for people reading names.
104    host: String,
105}
106
107impl HostIdentity {
108    /// This machine's identity, from `/etc/machine-id` and its host name.
109    pub fn read() -> std::io::Result<HostIdentity> {
110        let hostname = std::fs::read_to_string("/proc/sys/kernel/hostname").unwrap_or_default();
111        let machine_id = std::fs::read_to_string("/etc/machine-id")
112            .or_else(|_| std::fs::read_to_string("/var/lib/dbus/machine-id"))
113            .map_err(|error| {
114                std::io::Error::new(
115                    error.kind(),
116                    format!("cannot read /etc/machine-id: {error}"),
117                )
118            })?;
119        HostIdentity::new(&hostname, &machine_id).ok_or_else(|| {
120            std::io::Error::new(
121                std::io::ErrorKind::InvalidData,
122                "/etc/machine-id does not hold a machine ID",
123            )
124        })
125    }
126
127    /// The identity for a host name and a machine ID; `None` unless the ID is 32 hex digits.
128    pub fn new(hostname: &str, machine_id: &str) -> Option<HostIdentity> {
129        let machine_id = machine_id.trim();
130        if machine_id.len() != 32 || !machine_id.chars().all(|c| c.is_ascii_hexdigit()) {
131            return None;
132        }
133        // FNV-1a: stable across Rust releases, unlike std's hasher, so a new build recognizes the runners of the old.
134        let hash = format!("runnerd:{}", machine_id.to_ascii_lowercase())
135            .bytes()
136            .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
137                (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
138            });
139        let host: String = hostname
140            .trim()
141            .chars()
142            .map(|c| {
143                if c.is_ascii_alphanumeric() {
144                    c.to_ascii_lowercase()
145                } else {
146                    '-'
147                }
148            })
149            .take(20)
150            .collect();
151        let host = host.trim_matches('-');
152        Some(HostIdentity {
153            id: format!("{:08x}", hash >> 32),
154            host: if host.is_empty() { "host" } else { host }.to_owned(),
155        })
156    }
157
158    /// What every runner name of this machine starts with. The ID's fixed length keeps it from starting another
159    /// machine's names.
160    pub fn prefix(&self) -> String {
161        format!("runnerd-{}-", self.id)
162    }
163
164    /// The name of a runner, and of its container, started in `slot` (1-based) of `profile` at `secs`.
165    pub fn runner_name(&self, profile: &str, slot: usize, secs: u64) -> String {
166        format!("{}{}-{profile}-{slot}-{secs}", self.prefix(), self.host)
167    }
168}
169
170/// What the API needs from a running engine.
171#[derive(Debug, Clone)]
172pub struct Handle {
173    /// The latest status, replaced after every tick.
174    pub status: watch::Receiver<api::Status>,
175    /// Pause, resume and shutdown requests.
176    pub control: Arc<Control>,
177    /// The job history.
178    pub store: Store,
179    /// Every cache volume of the config, with size 0: the API fills in the sizes it measured. Replaced when the
180    /// config is.
181    pub caches: watch::Receiver<Vec<api::CacheVolume>>,
182    /// The records of failed jobs, replaced whenever one is made or removed.
183    pub records: watch::Receiver<api::Records>,
184    /// The shared build cache, for its size now.
185    pub build_cache: Option<BuildCache>,
186    /// What the slots' Docker Engines may keep together, in bytes, from the last measure (`cache::docker_disk`);
187    /// `None` before the first. Auto sizing adds no slot without it (ADR 0090).
188    pub disk: watch::Receiver<Option<u64>>,
189    /// The owner's job actions, sent through the engine's GitHub client but never on its loop (ADR 0134).
190    pub actions: JobActions,
191}
192
193impl Handle {
194    /// Asks the engine to stop in `mode` and says how it stops now: as asked, unless a stop asked for earlier is more
195    /// urgent, or the stop detaches since Docker stopped answering it. `None` for `Shutdown::No` when nothing stops.
196    pub fn shutdown(&self, mode: Shutdown) -> Option<api::Stopping> {
197        self.control.shutdown(mode).stopping()
198    }
199}
200
201/// Where the engine runs, besides its config and its GitHub and Docker clients.
202#[derive(Debug)]
203pub struct Setup {
204    /// The names of what runnerd creates in Docker.
205    pub names: Names,
206    /// This machine, which names its runners, so a restarted daemon recognizes them.
207    pub identity: HostIdentity,
208    /// The slice's `MemoryMax`.
209    pub memory_max: Option<u64>,
210    /// The CPUs the slice may use, in millicores (`config::slice_cpus`); `None` admits no runner by CPU.
211    pub cpus: Option<u64>,
212    /// The job history.
213    pub store: Store,
214    /// The profiles and repositories as the last run announced them (`Store::announced`), so the first publish
215    /// announces only the difference, including what the config no longer has.
216    pub announced: Announced,
217    /// The repositories recorded paused (`Store::paused_repositories`): they stay paused from the first tick.
218    pub paused: Vec<String>,
219    /// Where the cgroup and proc file systems are.
220    pub paths: Paths,
221    /// The shared build cache, unless the daemon could not open it.
222    pub build_cache: Option<BuildCache>,
223    /// Where the engine keeps whether what runners wrote without syncing may be lost to a host crash (ADR 0141), such
224    /// as `unsynced` beside the job history.
225    pub unsynced: PathBuf,
226    /// Writes what the kernel holds in memory to disk, before the engine says nothing is owed, and tells whether a
227    /// past boot ended in an orderly shutdown: `sync(2)` and the systemd journal.
228    pub durability: Durability,
229}
230
231/// Why a runner starts, as its start's log line and its record say (ADR 0092).
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233enum Purpose {
234    /// For a queued job.
235    Job,
236    /// As one of its repository's configured warm runners, for jobs not queued yet.
237    Warm,
238    /// As a warm runner past those, for a job its runs are expected to queue still.
239    Burst,
240}
241
242impl Purpose {
243    /// How the history stores it.
244    fn as_str(self) -> &'static str {
245        match self {
246            Purpose::Job => "job",
247            Purpose::Warm => "warm",
248            Purpose::Burst => "burst",
249        }
250    }
251}
252
253/// What else the engine does while it waits for a tick's work in `serving`, besides answering commands.
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
255enum Meanwhile {
256    /// Releases runners Docker says stopped and starts runners in their room (`turnover`).
257    Turnover,
258    /// Only answers commands: the work must not see a runner start or go, as a trim of the build cache.
259    Commands,
260}
261
262/// What a runner, or a start in flight, takes of the budgets: what `held_by` and `reserves_cpu` count it by, so a
263/// start counts as the runner it becomes.
264#[derive(Debug, Clone, Copy)]
265struct Footprint<'slot> {
266    runner_name: &'slot str,
267    /// Its container's memory cap.
268    memory: u64,
269    /// What it reserves of memory under measured admission.
270    reserved: u64,
271    /// Its container's CPU limit, in millicores.
272    cpus: u64,
273    /// What it reserves of the CPU budget, in millicores.
274    reserved_cpu: u64,
275    /// When it started, or its start was launched.
276    started_at: SystemTime,
277    /// Its job, as admission tells jobs apart.
278    key: Option<&'slot Key>,
279    /// When it took its job, if this daemon saw it do so.
280    job_found_here: Option<SystemTime>,
281    /// What its reservation went by.
282    basis: Option<api::Basis>,
283    /// Whether it is a runner yet.
284    stage: Stage,
285}
286
287/// Whether a footprint is a runner's or a start's in flight.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289enum Stage {
290    /// Named and admitted, registering its runner or creating its container: there is nothing to sample yet.
291    InFlight,
292    /// A runner in its slot, with its container.
293    Placed,
294}
295
296/// A slot's runner and its container.
297#[derive(Debug, Clone)]
298struct Occupant {
299    repository: String,
300    runner_name: String,
301    runner_id: u64,
302    container: String,
303    started_at: SystemTime,
304    /// Its container's memory cap, which a reload does not change.
305    memory: u64,
306    /// Its container's CPU limit in millicores, which a reload does not change.
307    cpus: u64,
308    /// How it was admitted, with what it reserved of the budget, kept through a restart by its record; `None` for
309    /// one whose record says nothing of it, which reserves its cap.
310    admission: Option<api::Admission>,
311    /// The labels it registered with; `None` for one adopted from a container that does not say.
312    labels: Option<Vec<String>>,
313    /// The image it runs; `None` for one adopted from a container that does not say.
314    image: Option<String>,
315    /// The release whose container spec it runs; `None` for one adopted from a container of a release before the
316    /// label.
317    spec: Option<String>,
318    /// Why it is there, whether it holds a job and which.
319    engagement: Engagement,
320}
321
322impl Occupant {
323    /// Whether it no longer is what `repository`'s runners in `profile` start as: other labels, or other limits than
324    /// the profile's. An unknown label set counts as the same.
325    fn outdated(
326        &self,
327        repository: &crate::config::Repository,
328        profile: &crate::config::Profile,
329    ) -> bool {
330        let differ = self.labels.as_ref().is_some_and(|labels| {
331            let set = |labels: &[String]| -> BTreeSet<String> {
332                labels
333                    .iter()
334                    .map(|label| label.to_ascii_lowercase())
335                    .collect()
336            };
337            set(labels) != set(&repository.labels)
338        });
339        differ || self.memory != profile.memory.0 || self.cpus != u64::from(profile.cpus) * 1000
340    }
341
342    /// Whether it runs another image than `profile` names. An unknown image counts as the same.
343    fn other_image(&self, profile: &crate::config::Profile) -> bool {
344        self.image
345            .as_ref()
346            .is_some_and(|image| *image != profile.image.reference())
347    }
348
349    /// Whether another release started it, with another container spec: one that does not say is older.
350    fn other_spec(&self) -> bool {
351        self.spec.as_deref() != Some(runners::THIS_SPEC)
352    }
353
354    /// What it takes of the budgets.
355    fn footprint(&self) -> Footprint<'_> {
356        Footprint {
357            runner_name: &self.runner_name,
358            memory: self.memory,
359            reserved: self.reserved(),
360            cpus: self.cpus,
361            reserved_cpu: self.reserved_cpu(),
362            started_at: self.started_at,
363            key: self.key(),
364            job_found_here: self.job_found_here(),
365            basis: self.admission.map(|admission| admission.basis),
366            stage: Stage::Placed,
367        }
368    }
369
370    /// What it reserves of the budget under measured admission: its cap if it has no admission.
371    fn reserved(&self) -> u64 {
372        self.admission
373            .map_or(self.memory, |admission| admission.reserved)
374    }
375
376    /// The CPU it reserves, in millicores: its CPU limit unless it was admitted by CPU.
377    fn reserved_cpu(&self) -> u64 {
378        self.admission
379            .and_then(|admission| admission.cpu)
380            .map_or(self.cpus, |cpu| cpu.reserved)
381    }
382
383    /// Whether GitHub's last runners listing showed it busy, or GitHub said so since (`Engagement::listed_busy`).
384    fn listed_busy(&self) -> bool {
385        self.engagement.listed_busy()
386    }
387
388    /// The job its capture or its history row named (`Engagement::named_job`).
389    fn named_job(&self) -> Option<u64> {
390        self.engagement.named_job()
391    }
392
393    /// Whether `job` is the one named for it.
394    fn runs(&self, job: u64) -> bool {
395        self.engagement.runs(job)
396    }
397
398    /// Whether it holds a job as far as this daemon knows (`Engagement::engaged`).
399    fn engaged(&self) -> bool {
400        self.engagement.engaged()
401    }
402
403    /// Whether it waits for a job: not `engaged`.
404    fn idle(&self) -> bool {
405        !self.engaged()
406    }
407
408    /// Whether it may be running one of its pool's listed jobs that no capture named yet
409    /// (`Engagement::claims_a_listed_job`).
410    fn claims_a_listed_job(&self) -> bool {
411        self.engagement.claims_a_listed_job()
412    }
413
414    /// Whether a detaching stop removes it (`Engagement::goes_when_detaching`).
415    fn goes_when_detaching(&self) -> bool {
416        self.engagement.goes_when_detaching()
417    }
418
419    /// Why this daemon started it; `None` for one a restart adopted.
420    fn purpose(&self) -> Option<Purpose> {
421        self.engagement.purpose()
422    }
423
424    /// When this daemon's capture found its job, if it started under this daemon (`Engagement::job_found_here`).
425    fn job_found_here(&self) -> Option<SystemTime> {
426        self.engagement.job_found_here()
427    }
428
429    /// Its job as admission tells jobs apart, once the history had its record.
430    fn key(&self) -> Option<&Key> {
431        self.engagement.key()
432    }
433
434    /// Whether admission can tell its job apart yet. A job named with no record yet has no key.
435    fn has_key(&self) -> bool {
436        self.key().is_some()
437    }
438
439    /// Whether it holds a job admission cannot tell apart yet, as when its log capture failed.
440    fn runs_unknown_job(&self) -> bool {
441        self.engaged() && !self.has_key()
442    }
443
444    fn running_job(&self) -> api::RunningJob {
445        api::RunningJob {
446            repository: self.repository.clone(),
447            runner: self.runner_name.clone(),
448            job: self.named_job(),
449        }
450    }
451}
452
453/// How long a stop that detaches or is forced takes at most, from its request: what Docker and GitHub have not
454/// answered by then is left to the next start (ADR 0091). Well within systemd's default stop timeout of 90s, which
455/// a single Docker request (120s) could otherwise outlast.
456pub const STOP_DEADLINE: Duration = Duration::from_secs(30);
457
458/// How long GitHub and Docker rest at least between the end of a tick and the start of the next, when a tick outlasts
459/// the interval between their starts (ADR 0111).
460const TICK_REST: Duration = Duration::from_secs(2);
461
462/// The scheduler with its side effects, on the real GitHub and Docker unless a test passes fakes.
463#[derive(Debug)]
464pub struct Engine<G = Github, D = Docker> {
465    config: Config,
466    /// Shared with the listings a tick reads while it answers commands.
467    github: Arc<G>,
468    docker: Arc<D>,
469    names: Names,
470    isolation: &'static dyn Isolation,
471    identity: HostIdentity,
472    runner_prefix: String,
473    /// What a sample's or a host reading's age goes by.
474    clock: Clock,
475    memory_max: Option<u64>,
476    /// The CPUs the slice may use, in millicores, read at start.
477    cpus: Option<u64>,
478    slots: BTreeMap<String, Vec<Slot>>,
479    /// The repositories, listed by the config or draining after a reload removed them.
480    repositories: Repositories,
481    /// What each profile's measures and reseeds are doing and have due.
482    upkeep: Upkeep,
483    /// Whether what runners wrote without syncing may be lost to a host crash.
484    unsynced: Unsynced,
485    /// The pulled images of the config's profiles, and the removal of those no profile runs.
486    images: Images,
487    /// The containers still to read or remove once nothing occupies them.
488    leftovers: Leftovers,
489    /// Profiles a reload removed, kept while their runners or reseed still run.
490    retired: BTreeMap<String, crate::config::Profile>,
491    /// The slots whose last start failed preparing its caches. Not kept over a restart.
492    prepare_failures: BTreeMap<SlotRef, runners::PrepareFailures>,
493    /// The job each slot ran last, which left its caches in the slot's layer: what `plan` matches queued jobs to
494    /// (ADR 0080). A slot is absent once its last job is not known, or a reseed dropped its layer.
495    ran: BTreeMap<SlotRef, Key>,
496    /// What the slots' Docker Engines may keep together, from the last check of the caches (`cache::docker_disk`);
497    /// `None` until one measured Docker's disk, when each image keeps its own default.
498    docker_disk: watch::Sender<Option<u64>>,
499    /// The measure of Docker's disk recovery started, in the background: Docker measures every volume.
500    disk: Option<JoinHandle<Result<caches::Disk, docker::Error>>>,
501    /// Whether a job ended since the shared caches were last checked.
502    trim_due: bool,
503    /// The running check of the shared caches: Docker takes many seconds to measure volumes.
504    trim: Option<JoinHandle<Result<Trimmed, docker::Error>>>,
505    /// When the last check of the shared caches started; the daemon's start counts as one, as the first runs then
506    /// unless runners were adopted.
507    checked_at: SystemTime,
508    mirror: Mirror,
509    /// Until when GitHub's rate limit is used up, from the last answer that said so: no runner starts before.
510    github_limited_until: Option<SystemTime>,
511    /// What is known of the registrations with no slot.
512    registrations: Registrations,
513    status: watch::Sender<api::Status>,
514    /// The profiles as the last run announced them, until the first publish compares the profiles with them. Their
515    /// slots are older than the `slot.changed` events clients have, so that publish announces every slot instead.
516    announced_profiles: Option<Vec<api::ProfileStatus>>,
517    control: Arc<Control>,
518    commands: Commands,
519    caches: watch::Sender<Vec<api::CacheVolume>>,
520    store: Store,
521    paths: Paths,
522    /// The containers the sampler reads.
523    tracked: watch::Sender<Vec<Tracked>>,
524    found: (mpsc::UnboundedSender<Found>, mpsc::UnboundedReceiver<Found>),
525    /// How each runner's container is watched: its log capture, and what broken ones left.
526    watches: Watches,
527    /// Who held which address, for the mirror's log.
528    leases: Leases,
529    /// How far the mirror's log was counted.
530    mirror_until: MirrorPosition,
531    /// The jobs followed on GitHub that no runner of this machine runs now: queued, or closing once their runner
532    /// went.
533    ledger: Ledger,
534    last_prune: Option<SystemTime>,
535    /// When the running jobs were last read from GitHub, which is once every `poll_interval` (ADR 0124).
536    running_reads: running_reads::RunningReads,
537    /// The pace of the reads by what is left of GitHub's rate limit (ADR 0127).
538    governor: governor::Governor,
539    /// The records of failed jobs and the shells open in them.
540    records: records::RecordState,
541    /// The predictor, the high-water mark of measured admission, and what admission saw of the host.
542    measured: admission::Measured,
543    /// What warm runners learned from the history, and the workflow runs seen lately.
544    warm: warm::Warm,
545    /// The shared build cache.
546    build_cache: Option<BuildCache>,
547    /// Each repository's default branch, once a job of it needed it: the branch whose builds write to the build
548    /// cache when `[caches.build] branches` names none.
549    default_branches: BTreeMap<String, build_cache::DefaultBranch>,
550    /// Removed runners' build cache uploads held until GitHub decides whether their jobs may write, at most
551    /// `build_cache::ENDED_WAIT`, by runner.
552    ended_uploads: BTreeMap<String, build_cache::EndedUploads>,
553    /// When each repository's visibility is next asked of GitHub, which the asking task updates; the store keeps
554    /// the answers.
555    visibility_due: Arc<Mutex<BTreeMap<String, SystemTime>>>,
556    /// The task asking GitHub repositories' visibility, off the tick (`follow_visibility`).
557    visibility_asking: Option<JoinHandle<()>>,
558    /// Released runners' registration deletes, sent in the background after their containers went (ADR 0113): each
559    /// tick reaps the finished ones, and a stop waits for the rest, up to `STOP_DEADLINE`.
560    deletes: Arc<Mutex<tokio::task::JoinSet<()>>>,
561    /// The runner containers Docker said stopped since the last pass or tick took them (ADR 0095).
562    exits: Arc<exits::Exits>,
563    /// The task following Docker's events into `exits`, while the engine schedules.
564    watcher: Option<exits::Watcher>,
565    /// The runner containers this tick's inspect found stopped and released before Docker's event for them came: a
566    /// pass the event wakes while the tick waits for GitHub starts runners into their room.
567    released: BTreeSet<String>,
568    /// How long the passes this tick's waits for GitHub held took. Each waits for its slowest release: a tick holds
569    /// passes until they took `CAPTURE_DRAIN`, or while slots keep turning over it would take minutes to its plan.
570    passes_in_tick: Duration,
571    /// The listing the engine began last, counted from 1 since its start, and when it began: the listing each answer
572    /// comes from, and how old a claim on a listed job is (`Claims`, `Engagement`).
573    listing: Mark,
574    /// By repository, the jobs its listings may show that this machine's runners took.
575    claims: Claims,
576    /// The second in the name of the last runner the engine named: the next one's is later, so no two runners share
577    /// a name, which GitHub, Docker and the history know them by. The history keeps each before the name is used,
578    /// and a restart takes it from there and the containers, so a name ahead of the clock, or a clock that stepped
579    /// back, is not used again.
580    named: u64,
581    /// The runners each batch launched, in launch order: what a test's reading taken mid-batch binds.
582    #[cfg(test)]
583    launches: start::Launches,
584}
585
586fn unix_secs(time: SystemTime) -> u64 {
587    time.duration_since(SystemTime::UNIX_EPOCH)
588        .unwrap_or_default()
589        .as_secs()
590}
591
592impl<G: GithubApi + 'static, D: DockerApi + 'static> Engine<G, D> {
593    /// An engine for a validated config. `identity` names this machine's runners, so a restarted daemon recognizes
594    /// them; `memory_max` is the slice's.
595    #[allow(
596        clippy::too_many_lines,
597        reason = "one line per field of the engine's state, which split up would only be listed twice"
598    )]
599    pub fn new(config: Config, github: G, docker: D, setup: Setup) -> (Engine<G, D>, Handle) {
600        let Setup {
601            names,
602            identity,
603            memory_max,
604            cpus,
605            store,
606            announced,
607            paused,
608            paths,
609            build_cache,
610            unsynced,
611            durability,
612        } = setup;
613        let unsynced = Unsynced::open(unsynced, &paths.proc, durability);
614        let slots = config
615            .profiles
616            .iter()
617            .map(|(name, profile)| {
618                let mut slots = Vec::new();
619                slots.resize_with(profile.slots as usize, Slot::default);
620                (name.clone(), slots)
621            })
622            .collect();
623        let repositories = Repositories::new(
624            config
625                .repositories
626                .iter()
627                .map(|repository| repository.name.clone()),
628        );
629        let (control, commands) = Control::new(
630            config
631                .repositories
632                .iter()
633                .map(|repository| repository.name.clone()),
634            paused,
635            store.clone(),
636        );
637        let control = Arc::new(control);
638        control.set_action_policy(
639            api::JobActions::configured(config.github.job_actions),
640            config
641                .repositories
642                .iter()
643                .map(|repository| repository.name.clone())
644                .collect(),
645        );
646        let github = Arc::new(github);
647        let actions = JobActions::new(
648            github.clone(),
649            store.clone(),
650            control.clone(),
651            crate::actions::LIMITS,
652        );
653        let (status, receiver) = watch::channel(api::Status {
654            job_actions: api::JobActions::configured(config.github.job_actions),
655            version: env!("CARGO_PKG_VERSION").to_owned(),
656            shutting_down: false,
657            stopping: None,
658            github_limited_until: None,
659            budget: api::Budget {
660                slice: config.host.slice.clone(),
661                memory_max,
662                ..api::Budget::default()
663            },
664            profiles: Vec::new(),
665            // What clients resuming after the last run's events have, so the first publish announces the difference.
666            repositories: announced.repositories,
667            queued: Vec::new(),
668        });
669        let (caches, caches_receiver) = watch::channel(cache::volumes(&names, &config));
670        let (records, records_receiver) = records::RecordState::new();
671        let (docker_disk, disk_receiver) = watch::channel(None);
672        let mut engine = Engine {
673            clock: Clock::default(),
674            isolation: isolation::backend(config.host.isolation),
675            // An earlier run may have left the mirror up, so the first idle tick stops it.
676            mirror: Mirror::unknown(config.mirror_memory()),
677            config,
678            github,
679            docker: Arc::new(docker),
680            names,
681            runner_prefix: identity.prefix(),
682            identity,
683            memory_max,
684            cpus,
685            slots,
686            repositories,
687            upkeep: Upkeep::default(),
688            unsynced,
689            images: Images::new(),
690            retired: BTreeMap::new(),
691            leftovers: Leftovers::default(),
692            prepare_failures: BTreeMap::new(),
693            ran: BTreeMap::new(),
694            docker_disk,
695            disk: None,
696            // So the caches are measured once at start.
697            trim_due: true,
698            trim: None,
699            checked_at: SystemTime::now(),
700            github_limited_until: None,
701            registrations: Registrations::default(),
702            status,
703            announced_profiles: Some(announced.profiles),
704            control: control.clone(),
705            commands,
706            caches,
707            store: store.clone(),
708            paths,
709            tracked: watch::channel(Vec::new()).0,
710            found: mpsc::unbounded_channel(),
711            watches: Watches::default(),
712            leases: Leases::default(),
713            mirror_until: MirrorPosition::default(),
714            ledger: Ledger::default(),
715            last_prune: None,
716            running_reads: running_reads::RunningReads::default(),
717            governor: governor::Governor::default(),
718            measured: admission::Measured::new(SystemTime::now()),
719            warm: warm::Warm::default(),
720            records,
721            build_cache: build_cache.clone(),
722            default_branches: BTreeMap::new(),
723            ended_uploads: BTreeMap::new(),
724            visibility_due: Arc::default(),
725            visibility_asking: None,
726            deletes: Arc::default(),
727            exits: Arc::default(),
728            watcher: None,
729            released: BTreeSet::new(),
730            passes_in_tick: Duration::ZERO,
731            listing: Mark {
732                listing: 0,
733                at: tokio::time::Instant::now(),
734            },
735            named: 0,
736            #[cfg(test)]
737            launches: start::Launches::default(),
738            claims: Claims::default(),
739        };
740        engine.publish();
741        (
742            engine,
743            Handle {
744                status: receiver,
745                control,
746                store,
747                caches: caches_receiver,
748                records: records_receiver,
749                build_cache,
750                disk: disk_receiver,
751                actions,
752            },
753        )
754    }
755
756    /// Runs until a shutdown request is carried out, or `STOP_DEADLINE` after a stop that detaches or is forced
757    /// began, whichever comes first. Either way it returns, so the daemon still closes its history.
758    pub async fn run(mut self) {
759        tokio::spawn(metrics::run(
760            Sampler::new(self.paths.clone(), &self.config.host.slice),
761            self.tracked.subscribe(),
762            self.store.clone(),
763        ));
764        let control = self.control.clone();
765        let deadline = async {
766            control.hurried().await;
767            tokio::time::sleep(STOP_DEADLINE).await;
768        };
769        tokio::select! {
770            () = self.serve() => {}
771            () = deadline => warn!(
772                "stopped after {}s with Docker or GitHub still busy; the next start takes over what is left",
773                STOP_DEADLINE.as_secs()
774            ),
775        }
776    }
777
778    /// Recovers, then schedules until a shutdown request is carried out.
779    async fn serve(&mut self) {
780        // Until Docker answers: scheduling without knowing the containers already running would start a second
781        // runner on a slot's volume and delete the running one's registration.
782        while let Err(error) = self.recover().await {
783            warn!("cannot list the containers an earlier run left; trying again in 5s: {error}");
784            if self.control.mode() != Shutdown::No {
785                return;
786            }
787            tokio::select! {
788                () = tokio::time::sleep(Duration::from_secs(5)) => {}
789                () = self.control.wake.notified() => {}
790            }
791        }
792        self.schedule().await;
793    }
794
795    /// Schedules until a shutdown request is carried out, from a recovered engine. A tick is due when the first
796    /// repository is, each an interval after its last listing started, and at least `TICK_REST` after the last tick
797    /// ended (ADR 0111, 0128); it lists the repositories due. One a command or a wake-up brings sooner lists every
798    /// repository. Between ticks, a runner whose container Docker says stopped is released at once, and its slot taken
799    /// by a job the last poll listed (`turnover`, ADR 0095); that leaves the next tick when it was due.
800    async fn schedule(&mut self) {
801        self.watcher = Some(exits::Watcher::start(
802            self.docker.clone(),
803            self.exits.clone(),
804        ));
805        let mut shown = Shutdown::No;
806        // The first tick lists every repository: none was listed yet.
807        let mut scope = Scope::Every;
808        let mode = loop {
809            let mode = self.control.mode();
810            // A stop shows before it removes idle runners, which can take until `STOP_DEADLINE` on a slow GitHub or
811            // Docker: until then status would show a daemon that is not stopping.
812            if mode != shown {
813                self.publish();
814                shown = mode;
815            }
816            // What the next tick's due time counts from: this one's listing, or, in a detach, which lists nothing,
817            // its start.
818            let anchor = if mode == Shutdown::Detach {
819                let began = tokio::time::Instant::now();
820                self.remove_every_idle().await;
821                self.collect_recordings().await;
822                began
823            } else {
824                self.tick_listing(mode, scope).await
825            };
826            self.publish();
827            // A stop asked for or changed meanwhile goes on at once, before this one counts as done: a second signal
828            // while a detach removed idle runners kills the running jobs, and one Docker failed turns into a detach.
829            if self.control.mode() != mode {
830                continue;
831            }
832            if self.stopped(mode) {
833                break mode;
834            }
835            // From the listings' starts, so the tick's own length does not push the next listing out, and two listings
836            // of a repository are never closer than its interval, however long either tick took to collect before
837            // listing.
838            let due = if mode == Shutdown::No {
839                self.next_tick_due(anchor)
840            } else {
841                let interval = Duration::from_secs(5);
842                (anchor + interval).max(tokio::time::Instant::now() + interval.min(TICK_REST))
843            };
844            scope = self.wait_for_tick(mode, due).await;
845        };
846        // Nothing more is started or released: what Docker says now is the next start's.
847        self.watcher = None;
848        // A reseed that finished meanwhile says so; one still running is the next start's (`recover_reseeds`).
849        self.collect_reseeds().await;
850        self.finish_deletes().await;
851        if self.control.docker_gone() {
852            info!("stopped; the next start removes or adopts what Docker did not answer for");
853            return;
854        }
855        self.close_shells().await;
856        // What the runners wrote without syncing is on disk once the stop leaves none running (ADR 0141).
857        if self.occupied().next().is_none()
858            && let Err(error) = self.unsynced.stopped_clean()
859        {
860            warn!(
861                "cannot note that what runners wrote is on disk; the next boot empties their caches: {error}"
862            );
863        }
864        if mode == Shutdown::Detach {
865            // The mirror stays up only for the busy runners left behind.
866            let mirror = if self.config.caches.mirror.enabled {
867                " and the mirror"
868            } else {
869                ""
870            };
871            match self.occupied().count() {
872                0 => info!("stopped; no job was running"),
873                1 => info!("stopped, leaving 1 busy runner{mirror} to the next start"),
874                runners => {
875                    info!("stopped, leaving {runners} busy runners{mirror} to the next start");
876                }
877            }
878            return;
879        }
880        if let Err(error) = cache::mirror_down(&*self.docker, &self.names).await {
881            warn!("cannot stop the mirror: {error}");
882        }
883        info!("stopped");
884    }
885
886    /// Looks at what GitHub's rate limit says before a tick and moves the pace of the reads a step if it calls for it
887    /// (ADR 0127). Registrations and deletes do not ask.
888    fn pace_by_limit(&mut self) {
889        let spend = self.github.spend();
890        if let Some(change) =
891            self.governor
892                .observe(tokio::time::Instant::now(), SystemTime::now(), spend)
893        {
894            info!("{}", change.line(self.config.host.poll_interval));
895        }
896    }
897
898    /// Waits until the next tick in `mode` is `due`, or something calls for one sooner: a wake-up or a command.
899    /// Runners Docker says stopped meanwhile are released by passes, finished records collected and the jobs
900    /// captures name noted, all leaving `due` as it is; during a stop they call for the tick instead, which a detach does not wait for runners.
901    /// Says what the tick lists: the repositories due when it came when due, and every repository when it came sooner.
902    async fn wait_for_tick(&mut self, mode: Shutdown, due: tokio::time::Instant) -> Scope {
903        loop {
904            let exits = self.exits.clone();
905            // A due tick and a command go before a pass: passes back to back would otherwise hold them while slots
906            // keep turning over.
907            tokio::select! {
908                biased;
909                () = tokio::time::sleep_until(due) => return Scope::Due,
910                () = self.control.wake.notified() => return Scope::Every,
911                // A detaching stop changes nothing more: a command waiting for it fails once the engine is gone.
912                Some(command) = self.commands.recv(), if mode != Shutdown::Detach => {
913                    self.command(command).await;
914                    self.publish();
915                    return Scope::Every;
916                }
917                // Running on, a record's end changes nothing GitHub must be asked about: the next poll stays when
918                // it was due. A stop returns to see whether it is done.
919                Some(()) = self.records.finished.recv() => {
920                    self.collect_recordings().await;
921                    self.publish();
922                    if mode != Shutdown::No || self.control.mode() != mode {
923                        return Scope::Every;
924                    }
925                }
926                // A capture named its runner's job: status says the runner runs it now, not after the next poll.
927                Some(found) = self.found.1.recv() => {
928                    self.note_found(&found);
929                    self.publish();
930                }
931                () = exits.noted(), if mode != Shutdown::Detach => {
932                    if mode != Shutdown::No {
933                        return Scope::Every;
934                    }
935                    self.turnover().await;
936                    self.publish();
937                    if self.control.mode() != mode {
938                        return Scope::Every;
939                    }
940                }
941            }
942        }
943    }
944
945    /// Whether a stop in `mode` is done: what it waits for has ended. A record being made is waited for; a reseed and
946    /// a check of the caches are not, as the next start adopts the reseed and checks the caches first.
947    fn stopped(&self, mode: Shutdown) -> bool {
948        let idle = self.slots.values().flatten().all(Slot::is_free);
949        let recorded = !self.records.is_recording();
950        match mode {
951            Shutdown::No => false,
952            Shutdown::Detach => recorded,
953            Shutdown::Graceful | Shutdown::Force => idle && recorded,
954        }
955    }
956
957    /// Notes that Docker failed a call a stop needed. If it did not answer at all, as when it is gone during a
958    /// machine's shutdown, the stop calls it no more and leaves the rest to the next start, which removes or adopts
959    /// every container by its labels. An answer that is an error, or a timeout, is tried again as any failed call:
960    /// `runnerd stop` must not leave runners behind for one busy moment of Docker's.
961    fn docker_failed(&self, error: &docker::Error) {
962        if docker::is_unreachable(error) && self.control.note_docker_gone() {
963            warn!("Docker does not answer during the stop; leaving the rest to the next start");
964        }
965    }
966
967    /// Runs `work` as a task of its own, answering commands and publishing after each until it is done, so a command
968    /// waits for a slow GitHub no longer than for the command before it. A tick follows each such command, as one
969    /// follows a command answered between ticks. The task goes on while a command runs: a request's timeout runs on
970    /// the clock, not on polls. With `Meanwhile::Turnover`, runners Docker says stopped are released and their slots
971    /// taken meanwhile too (`turnover`, ADR 0095), so a tick's wait for GitHub does not hold them, for a
972    /// while, and the jobs captures name are noted as they come.
973    async fn serving<T: Send + 'static>(
974        &mut self,
975        work: impl Future<Output = T> + Send + 'static,
976        meanwhile: Meanwhile,
977    ) -> T {
978        let mut task = tokio::spawn(work);
979        loop {
980            let exits = self.exits.clone();
981            tokio::select! {
982                biased;
983                done = &mut task => match done.map_err(tokio::task::JoinError::try_into_panic) {
984                    Ok(output) => return output,
985                    // As if it had panicked here.
986                    Err(Ok(panic)) => std::panic::resume_unwind(panic),
987                    // Only while the runtime shuts down, which drops this task too.
988                    Err(Err(_)) => std::future::pending::<()>().await,
989                },
990                Some(command) = self.commands.recv() => {
991                    self.command(command).await;
992                    self.publish();
993                    // A tick follows it, as one follows a command answered between ticks: a config it replaced
994                    // polls its repositories then, not a poll interval later.
995                    self.control.wake.notify_one();
996                }
997                () = exits.noted(), if meanwhile == Meanwhile::Turnover && self.passes_in_tick < CAPTURE_DRAIN => {
998                    let began = tokio::time::Instant::now();
999                    self.turnover().await;
1000                    self.passes_in_tick += began.elapsed();
1001                    self.publish();
1002                }
1003                Some(found) = self.found.1.recv(), if meanwhile == Meanwhile::Turnover => {
1004                    self.note_found(&found);
1005                    self.publish();
1006                }
1007            }
1008        }
1009    }
1010
1011    /// The jobs this machine's runners took, as their slots' occupants name them: computed where it is read, as a
1012    /// runner may take a job, or go, while the engine waits for GitHub.
1013    fn taken(&self) -> BTreeSet<u64> {
1014        self.occupied()
1015            .filter_map(|(_, occupant)| occupant.named_job())
1016            .collect()
1017    }
1018
1019    fn occupied(&self) -> impl Iterator<Item = (SlotRef, &Occupant)> {
1020        self.slots.iter().flat_map(|(profile, slots)| {
1021            slots.iter().enumerate().filter_map(|(index, slot)| {
1022                slot.occupant().map(|occupant| {
1023                    (
1024                        SlotRef {
1025                            profile: profile.clone(),
1026                            index,
1027                        },
1028                        occupant,
1029                    )
1030                })
1031            })
1032        })
1033    }
1034
1035    /// What each runner and each start in flight takes of the budgets.
1036    fn footprints(&self) -> impl Iterator<Item = Footprint<'_>> {
1037        self.slots.values().flatten().filter_map(Slot::footprint)
1038    }
1039
1040    /// Each runner and each start in flight with its slot.
1041    fn slot_footprints(&self) -> impl Iterator<Item = (SlotRef, Footprint<'_>)> {
1042        self.slots.iter().flat_map(|(profile, slots)| {
1043            slots.iter().enumerate().filter_map(|(index, slot)| {
1044                slot.footprint().map(|footprint| {
1045                    (
1046                        SlotRef {
1047                            profile: profile.clone(),
1048                            index,
1049                        },
1050                        footprint,
1051                    )
1052                })
1053            })
1054        })
1055    }
1056
1057    /// The runner in `slot`, if one is.
1058    fn occupant(&self, slot: &SlotRef) -> Option<&Occupant> {
1059        self.slots
1060            .get(&slot.profile)
1061            .and_then(|slots| slots.get(slot.index))
1062            .and_then(Slot::occupant)
1063    }
1064
1065    /// Drops the free slots past each profile's configured number, and the profiles a reload removed once nothing
1066    /// runs in them.
1067    fn drop_closed_slots(&mut self) {
1068        for (name, slots) in &mut self.slots {
1069            let count = self
1070                .config
1071                .profiles
1072                .get(name)
1073                .map_or(0, |profile| profile.slots as usize);
1074            while slots.len() > count && slots.last().is_some_and(Slot::is_free) {
1075                slots.pop();
1076            }
1077        }
1078        let profiles = &self.config.profiles;
1079        self.slots
1080            .retain(|name, slots| !slots.is_empty() || profiles.contains_key(name));
1081        // The volumes of the slots dropped go at the next check of the caches.
1082        let slots = &self.slots;
1083        self.ran.retain(|slot, _| {
1084            slots
1085                .get(&slot.profile)
1086                .is_some_and(|slots| slot.index < slots.len())
1087        });
1088        let (slots, upkeep) = (&self.slots, &self.upkeep);
1089        self.retired
1090            .retain(|name, _| slots.contains_key(name) || upkeep.reseed_runs(name));
1091    }
1092}
1093
1094#[cfg(test)]
1095mod tests;