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