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