Skip to main content

greengate_runtime/
cluster.rs

1//! A `platform=any` gate run on the homelab cluster, as one Kubernetes Job
2//! (ADR-0016).
3//!
4//! A trusted manifest marks a gate whose verdict does not depend on the
5//! platform (`platform=any`) and says `set executor cluster`; the machine
6//! names a kubeconfig and an image pinned by digest. Then the gate runs in a
7//! pod instead of on this laptop, and takes no host slot (ADR-0014).
8//!
9//! **The cluster proves only passes.** The verdict is read from what
10//! Kubernetes recorded — the Job's `Complete` condition, each container's
11//! exit code, `fetch`'s termination message naming the tree, the pod's
12//! `imageID` — never from the logs. Anything else, a failure of the gate
13//! included, re-runs the gate here, unchanged, and the local outcome is the
14//! verdict: a gate never fails because of the cluster. Each such fallback
15//! appends `<epoch> <gate> <reason>` to `greengate/cluster.log` in the common git
16//! directory.
17//!
18//! A pass is recorded under its own identity
19//! ([`crate::gate_identity::cluster_token`]) in its own ref
20//! ([`crate::gate_stamp::CLUSTER_REF`]) and never as a local token: the
21//! hooks consult [`proved`] so a cluster-derived pass never reaches the
22//! commit marker, a push stamp or the laptop's attestation.
23//!
24//! Every `kubectl` call goes through `--kubeconfig <path>` (never the default
25//! context), with stdin null — except the one `exec -i` that streams the
26//! bundle — and under one deadline taken before the Job is created.
27
28use std::collections::BTreeSet;
29use std::path::{Path, PathBuf};
30use std::process::{Command, Stdio};
31use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
32use std::sync::Mutex;
33use std::time::{Duration, Instant};
34
35use crate::json_read::Value;
36use crate::manifest::{External, Kind};
37
38mod detached;
39#[cfg(test)]
40pub(crate) use detached::sample_pending_file;
41pub(crate) use detached::{
42    collect, lists_live, settled_lines, status_lines, stop_pending, PENDING_FILE,
43};
44pub use detached::{collect_command, detach, wanted, Ask, Detached};
45
46/// [`collect`] for the hooks and `amont stamps`, which run in every repository:
47/// only where the manifest declares a `platform=any` gate, the only kind a
48/// Workflow can hold a pass for, so a repository without one pays nothing.
49pub fn collect_if_declared(manifest: &crate::manifest::Manifest) {
50    if manifest.externals.iter().any(is_platform_any) {
51        collect();
52    }
53}
54
55/// The node the gate pods run on, and the names the homelab contract fixes.
56const NODE: &str = "talos-wk-3-gpu";
57const PRIORITY_CLASS: &str = "gate-batch";
58const PULL_SECRET: &str = "forgejo-registry-pull";
59const JOB_PREFIX: &str = crate::names::JOB_PREFIX;
60const CACHE_PREFIX: &str = "gate-cache-";
61const TEMP_REF_PREFIX: &str = "refs/amont/cluster/";
62/// The platform a cluster pass is recorded under.
63pub(crate) const PLATFORM: &str = "x86_64-linux";
64/// The main container's memory, request equal to limit, and CPU limit.
65const MEMORY: &str = "4Gi";
66const CPU_LIMIT: &str = "2";
67/// One short kubectl call: its own request timeout plus room for the exec
68/// credential plugin. Never more than the time left.
69const CALL_SECS: u64 = 20;
70/// The shared budget for deleting live Jobs when amont is interrupted.
71const CANCEL_SECS: u64 = 10;
72/// The bound on a quiet clean-up by label after a `create` timed out.
73const LABEL_DELETE_SECS: u64 = 5;
74/// The label every Job carries, valued by its run ([`run_label`]).
75const RUN_LABEL_KEY: &str = crate::names::RUN_LABEL;
76const POLL: Duration = Duration::from_millis(500);
77const MIB: u64 = 1024 * 1024;
78
79/// Passes the cluster proved in this process, by (check id, tree): run there,
80/// or reused from a cluster token. Such a pass never becomes a local token,
81/// stamp or attestation for that tree.
82static PROVED: Mutex<BTreeSet<(String, String)>> = Mutex::new(BTreeSet::new());
83/// Set once the apiserver did not answer: the later gates of this hook
84/// process run here without asking it again.
85static UNREACHABLE: AtomicBool = AtomicBool::new(false);
86/// A misconfiguration is said once per run, not once per gate.
87static WARNED: AtomicBool = AtomicBool::new(false);
88/// An unreachable apiserver is said once per run; each gate still logs it.
89static UNREACHABLE_SAID: AtomicBool = AtomicBool::new(false);
90/// What an interrupt must clean up, by run.
91static LIVE: Mutex<Vec<LiveRun>> = Mutex::new(Vec::new());
92/// Serialises writes of the cluster note: concurrent gates of one stage each
93/// read, merge and rewrite it.
94static STAMP_LOCK: Mutex<()> = Mutex::new(());
95static SEQ: AtomicU64 = AtomicU64::new(0);
96/// Temporary manifest files of detached submissions, for an interrupt to
97/// delete. Files only: a detached Workflow outlives amont on purpose.
98static TEMP_FILES: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
99
100fn track_temp_file(path: &Path) {
101    TEMP_FILES
102        .lock()
103        .unwrap_or_else(|p| p.into_inner())
104        .push(path.to_path_buf());
105}
106
107fn untrack_temp_file(path: &Path) {
108    TEMP_FILES
109        .lock()
110        .unwrap_or_else(|p| p.into_inner())
111        .retain(|p| p != path);
112}
113
114/// Did the cluster prove the check `id` on `tree` in this process?
115pub fn proved(id: &str, tree: &str) -> bool {
116    PROVED
117        .lock()
118        .unwrap_or_else(|p| p.into_inner())
119        .contains(&(id.to_string(), tree.to_string()))
120}
121
122/// Did the cluster prove the check `id` on any tree in this process? For a
123/// caller that covers several trees at once (an attestation of a push).
124pub fn proved_anywhere(id: &str) -> bool {
125    PROVED
126        .lock()
127        .unwrap_or_else(|p| p.into_inner())
128        .iter()
129        .any(|(i, _)| i == id)
130}
131
132/// Did the cluster prove the check `id` on the index's tree? Spawns nothing
133/// unless the cluster proved `id` somewhere; when git cannot name the index's
134/// tree, the answer is yes, so no local token is written on a guess.
135pub fn proved_on_index(id: &str) -> bool {
136    proved_anywhere(id) && tree_of(Judged::Index).map_or(true, |tree| proved(id, &tree))
137}
138
139/// The ids of the manifest's `platform=any` gates. A `Runnable` exists only
140/// for a trusted manifest, so these are the trusted declarations.
141pub(crate) fn platform_any_ids(manifest: &crate::manifest::Manifest) -> Vec<String> {
142    manifest
143        .externals
144        .iter()
145        .filter(|e| is_platform_any(e))
146        .map(|e| e.id.clone())
147        .collect()
148}
149
150fn mark_proved(id: &str, tree: &str) {
151    PROVED
152        .lock()
153        .unwrap_or_else(|p| p.into_inner())
154        .insert((id.to_string(), tree.to_string()));
155}
156
157/// One cluster run, as an interrupt sees it.
158#[derive(Clone)]
159struct LiveRun {
160    run: u64,
161    kubeconfig: PathBuf,
162    namespace: String,
163    scratch: PathBuf,
164    /// The `greengate.run` label of every Job this run creates: how a Job whose
165    /// `create` is still in flight, or whose answer was lost, is found.
166    run_label: String,
167    /// Where this run's Job stands, as a cancel must know it.
168    created: Created,
169    gate_ref: Option<String>,
170}
171
172/// A run's Job, as far as an interrupt can tell.
173#[derive(Clone, Debug, PartialEq, Eq)]
174enum Created {
175    /// No `create` sent, or the Job already deleted: nothing on the cluster
176    /// is this run's.
177    NotSent,
178    /// A `create` was sent; its Job, if any, is found by the run's label.
179    Sent,
180    /// The Job this run holds, by name.
181    Named(String),
182}
183
184fn live_update(run: u64, update: impl FnOnce(&mut LiveRun)) {
185    let mut live = LIVE.lock().unwrap_or_else(|p| p.into_inner());
186    if let Some(entry) = live.iter_mut().find(|l| l.run == run) {
187        update(entry);
188    }
189}
190
191/// The signal watcher's hook, after the index is restored: say so, ask the
192/// apiserver to drop every live Job without waiting for it, all under one
193/// shared budget, and remove the temporary files and refs. A second signal
194/// meanwhile ends amont at once and leaves the Job to its own deadline.
195pub fn cancel_live() {
196    for file in std::mem::take(&mut *TEMP_FILES.lock().unwrap_or_else(|p| p.into_inner())) {
197        let removed = std::fs::remove_file(&file); // amont is dying: nothing to tell
198        drop(removed);
199    }
200    let live: Vec<LiveRun> = std::mem::take(&mut *LIVE.lock().unwrap_or_else(|p| p.into_inner()));
201    if live.is_empty() {
202        return;
203    }
204    let _leaving = crate::staged_only::leave_on_second_signal();
205    let deadline = Instant::now() + Duration::from_secs(CANCEL_SECS);
206    for run in live {
207        if let Some(gate_ref) = &run.gate_ref {
208            let _ = crate::git::succeeds(&["update-ref", "-d", gate_ref]); // best-effort: amont is dying
209        }
210        let _ = std::fs::remove_dir_all(&run.scratch); // best-effort: amont is dying
211        let kube = Kube {
212            kubeconfig: run.kubeconfig.clone(),
213            namespace: run.namespace.clone(),
214        };
215        let left = secs_left(deadline, CANCEL_SECS);
216        match &run.created {
217            Created::NotSent => {}
218            Created::Named(job) => {
219                eprintln!("cancelling cluster Job {job}; Ctrl-C again to leave it");
220                if let Err(why) = kube.bounded(&["delete", "job", job, "--wait=false"], left) {
221                    eprintln!(
222                        "could not cancel cluster Job {job}: {}",
223                        crate::ui::sanitize(&why)
224                    );
225                }
226            }
227            // Not named yet: `create` may be in flight or its answer lost. The
228            // label finds the Job if it exists, and deletes nothing otherwise.
229            Created::Sent => {
230                let selector = run_selector(&run.run_label);
231                eprintln!("cancelling cluster Jobs of this run; Ctrl-C again to leave them");
232                if let Err(why) =
233                    kube.bounded(&["delete", "job", "-l", &selector, "--wait=false"], left)
234                {
235                    eprintln!(
236                        "could not cancel the cluster Jobs of this run: {}",
237                        crate::ui::sanitize(&why)
238                    );
239                }
240            }
241        }
242    }
243}
244
245/// Whole seconds until `deadline`, at most `cap`, at least 1.
246fn secs_left(deadline: Instant, cap: u64) -> u64 {
247    deadline
248        .saturating_duration_since(Instant::now())
249        .as_secs()
250        .clamp(1, cap.max(1))
251}
252
253/// Why the cluster did not prove a gate. Every one runs the gate here.
254#[derive(Debug, Clone, PartialEq, Eq)]
255enum Fallback {
256    /// A required machine key is unset: this machine has no cluster. Silent
257    /// on the terminal, so a repository that says `set executor cluster`
258    /// does not warn on every hook of a machine without one.
259    Unconfigured(&'static str),
260    /// A machine key is set but cannot be used. Said once per run, with the
261    /// fix.
262    Misconfigured {
263        why: String,
264        fix: String,
265    },
266    /// The apiserver did not answer, or kubectl could not run.
267    Unreachable(String),
268    /// The apiserver did not answer an earlier gate of this run.
269    UnreachableEarlier,
270    SlotsTaken,
271    QuotaFull,
272    BundleTooBig {
273        mib: u64,
274        cap: u64,
275    },
276    /// The gate itself exited non-zero in the pod.
277    GateFailed(String),
278    /// Anything else the recorded facts do not prove.
279    NotProved(String),
280}
281
282impl std::fmt::Display for Fallback {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        match self {
285            Fallback::Unconfigured(why) => write!(f, "{why}"),
286            Fallback::Misconfigured { why, .. } => write!(f, "{why}"),
287            Fallback::Unreachable(why) => write!(f, "the cluster did not answer: {why}"),
288            Fallback::UnreachableEarlier => {
289                write!(f, "the cluster did not answer earlier in this run")
290            }
291            Fallback::SlotsTaken => write!(f, "all slots taken"),
292            Fallback::QuotaFull => write!(f, "the quota refused every slot"),
293            Fallback::BundleTooBig { mib, cap } => {
294                write!(f, "bundle-too-big: {mib} MiB, over the {cap} MiB cap")
295            }
296            Fallback::GateFailed(detail) => write!(f, "failed on the cluster ({detail})"),
297            Fallback::NotProved(why) => write!(f, "{why}"),
298        }
299    }
300}
301
302/// What the cluster needs from this machine and this repository.
303#[derive(Debug, Clone, PartialEq, Eq)]
304struct ClusterConfig {
305    kubeconfig: PathBuf,
306    namespace: String,
307    slots: u32,
308    image: String,
309    digest: String,
310    max_bundle_mib: u64,
311    start_wait: Duration,
312    timeout_secs: u64,
313    prepare: Option<String>,
314}
315
316/// The machine's `greengate.cluster.*` keys, lowercased as git prints them.
317/// `--type=path` expands a leading `~`, which is how the kubeconfig is set.
318fn machine_keys() -> Vec<(String, String)> {
319    crate::git::stdout(&[
320        "config",
321        "--type=path",
322        "--get-regexp",
323        r"^greengate\.cluster\.",
324    ])
325    .unwrap_or_default()
326    .lines()
327    .map(|l| {
328        let (k, v) = l.split_once(' ').unwrap_or((l, ""));
329        (k.to_ascii_lowercase(), v.trim().to_string())
330    })
331    .collect()
332}
333
334fn key<'a>(keys: &'a [(String, String)], name: &str) -> Option<&'a str> {
335    keys.iter()
336        .rev()
337        .find(|(k, _)| k == name)
338        .map(|(_, v)| v.as_str())
339        .filter(|v| !v.is_empty())
340}
341
342fn number(keys: &[(String, String)], name: &str, default: u64, max: u64) -> u64 {
343    key(keys, name)
344        .and_then(|v| v.parse::<u64>().ok())
345        .filter(|n| *n >= 1)
346        .map_or(default, |n| n.min(max))
347}
348
349/// The digest of a pinned image reference, `sha256:<hex>`, or `None` for a
350/// reference that is not pinned by digest.
351fn digest_of(image: &str) -> Option<&str> {
352    let (_, digest) = image.split_once('@')?;
353    let hex = digest.strip_prefix("sha256:")?;
354    (hex.len() == 64 && hex.chars().all(|c| c.is_ascii_hexdigit())).then_some(digest)
355}
356
357/// A DNS-1123 label: what a namespace may be called.
358fn is_label(s: &str) -> bool {
359    !s.is_empty()
360        && s.len() <= 63
361        && s.chars()
362            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
363        && !s.starts_with('-')
364        && !s.ends_with('-')
365}
366
367/// The trusted `set clusterPrepare` command, if any. Policy only: a local
368/// git config cannot hand the pod a command the manifest did not declare.
369fn prepare(settings: &crate::config::Settings) -> Option<String> {
370    settings
371        .policy()
372        .settings
373        .get("greengate.clusterPrepare")
374        .cloned()
375}
376
377/// Whether this repository's TRUSTED policy says `set executor cluster`, and
378/// no local `git config greengate.executor local` turned it off. Reading the
379/// policy map spawns nothing, so a repository that says nothing pays nothing.
380fn executor_is_cluster(settings: &crate::config::Settings) -> bool {
381    settings
382        .policy()
383        .settings
384        .get("greengate.executor")
385        .is_some_and(|v| v == "cluster")
386        && crate::config::enumerated_or(
387            settings,
388            "greengate.executor",
389            &["cluster", "local"],
390            "local",
391        ) == "cluster"
392}
393
394fn misconfigured(why: String, key_fix: &str) -> Fallback {
395    Fallback::Misconfigured {
396        why,
397        fix: format!("{key_fix}, or `git config greengate.executor local`"),
398    }
399}
400
401/// The full configuration, or why the gate runs here instead.
402fn cluster_config(settings: &crate::config::Settings) -> Result<ClusterConfig, Fallback> {
403    let keys = machine_keys();
404    let kubeconfig = key(&keys, "greengate.cluster.kubeconfig").ok_or(Fallback::Unconfigured(
405        "greengate.cluster.kubeconfig is not set: `git config --global greengate.cluster.kubeconfig ~/.config/greengate/kube/homelab.yaml` (homelab scripts/greengate-gates-kubeconfig.sh writes it)",
406    ))?;
407    let kubeconfig = PathBuf::from(kubeconfig);
408    if !kubeconfig.is_file() {
409        return Err(misconfigured(
410            format!("kubeconfig {} does not exist", kubeconfig.display()),
411            "`git config --global greengate.cluster.kubeconfig <path>`",
412        ));
413    }
414    let image = key(&keys, "greengate.cluster.image")
415        .ok_or(Fallback::Unconfigured(
416        "greengate.cluster.image is not set: `git config --global greengate.cluster.image 'name:tag@sha256:<digest>'`",
417    ))?;
418    let digest = digest_of(image)
419        .ok_or_else(|| {
420            misconfigured(
421                format!("greengate.cluster.image {image:?} is not pinned by @sha256: digest"),
422                "`git config --global greengate.cluster.image <name>:<tag>@sha256:<digest>`",
423            )
424        })?
425        .to_string();
426    let namespace =
427        key(&keys, "greengate.cluster.namespace").unwrap_or(crate::names::CLUSTER_NAMESPACE);
428    if !is_label(namespace) {
429        return Err(misconfigured(
430            format!("greengate.cluster.namespace {namespace:?} is not a namespace name"),
431            "`git config --global greengate.cluster.namespace <name>`",
432        ));
433    }
434    let timeout_secs = crate::hooks::common::check_timeout(settings);
435    if timeout_secs == 0 {
436        return Err(misconfigured(
437            "greengate.timeout is 0 (unbounded), and a Job needs a deadline".into(),
438            "`git config greengate.timeout <seconds>`",
439        ));
440    }
441    Ok(ClusterConfig {
442        kubeconfig,
443        namespace: namespace.to_string(),
444        slots: u32::try_from(number(&keys, "greengate.cluster.slots", 2, 2)).unwrap_or(2),
445        image: image.to_string(),
446        digest,
447        max_bundle_mib: number(&keys, "greengate.cluster.maxbundlemib", 50, 4096),
448        start_wait: Duration::from_secs(number(&keys, "greengate.cluster.startwait", 30, 600)),
449        timeout_secs,
450        prepare: prepare(settings),
451    })
452}
453
454fn is_platform_any(ext: &External) -> bool {
455    matches!(
456        ext.kind,
457        Kind::Runnable {
458            runs_on: crate::manifest::RunsOn::AnyPlatform,
459            ..
460        }
461    )
462}
463
464/// The cluster token for `ext` as configured now — the image digest and the
465/// prepare command included — or `None` where no cluster token can apply: a
466/// gate that is not `platform=any`, or no pinned image on this machine.
467/// Never inspects the laptop's executable.
468fn token(settings: &crate::config::Settings, ext: &External) -> Option<String> {
469    token_from(&machine_keys(), settings, ext, &ext.id)
470}
471
472/// [`token`] from machine keys already read, for `ext`'s program, arguments
473/// and file scope under the name `name`: a caller that needs several tokens
474/// reads the keys (one `git config`) once.
475fn token_from(
476    keys: &[(String, String)],
477    settings: &crate::config::Settings,
478    ext: &External,
479    name: &str,
480) -> Option<String> {
481    if !is_platform_any(ext) {
482        return None;
483    }
484    let digest = digest_of(key(keys, "greengate.cluster.image")?)?;
485    crate::gate_identity::cluster_token(ext, name, prepare(settings).as_deref(), digest)
486}
487
488/// What the cluster is asked to judge.
489#[derive(Debug, Clone, Copy)]
490pub enum Judged<'a> {
491    /// The index: the tree `git commit` is about to seal.
492    Index,
493    /// A commit's tree: a pushed tip.
494    Commit(&'a str),
495}
496
497/// The tree object `judged` names, or `None` when git cannot say, or when
498/// the file set is not the index and the working tree differs from it (an
499/// `amont run` over a dirty tree judges content no tree holds).
500fn tree_of(judged: Judged) -> Option<String> {
501    match judged {
502        Judged::Index => {
503            if crate::hooks::common::not_the_index() {
504                let dirty = crate::git::stdout(&["status", "--porcelain", "--untracked-files=no"])?;
505                if !dirty.trim().is_empty() {
506                    return None;
507                }
508            }
509            write_tree()
510        }
511        Judged::Commit(c) => crate::git::stdout(&["rev-parse", &format!("{c}^{{tree}}")]),
512    }
513}
514
515/// `git write-tree` of the index, one at a time: concurrent gates of one
516/// stage each ask, and git refuses a second writer while the first holds
517/// `index.lock` (it refreshes the cache-tree), so a refusal is retried.
518fn write_tree() -> Option<String> {
519    static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());
520    let _held = ONE_AT_A_TIME.lock().unwrap_or_else(|p| p.into_inner());
521    for _ in 0..20 {
522        if let Some(tree) = crate::git::stdout(&["write-tree"]) {
523            return Some(tree);
524        }
525        std::thread::sleep(Duration::from_millis(50));
526    }
527    None
528}
529
530/// pre-commit (and `run --stamp`): is the tree about to be committed already
531/// proved on the cluster for this gate, as it is declared and configured
532/// now? A hit counts as a cluster pass ([`proved`]).
533pub fn vouched(settings: &crate::config::Settings, ext: &External, judged: Judged) -> bool {
534    let Some(token) = token(settings, ext) else {
535        return false;
536    };
537    let Some(tree) = tree_of(judged) else {
538        return false;
539    };
540    let hit = crate::gate_stamp::cluster_tokens(&tree).contains(&token);
541    if hit {
542        mark_proved(&ext.id, &tree);
543    }
544    hit
545}
546
547/// pre-push: does every tip carry this gate's cluster token on its tree?
548pub fn vouched_on_every(
549    settings: &crate::config::Settings,
550    ext: &External,
551    tips: &[String],
552) -> bool {
553    if tips.is_empty() {
554        return false;
555    }
556    let Some(token) = token(settings, ext) else {
557        return false;
558    };
559    vouched_trees(ext, tips, &token).is_some()
560}
561
562/// The trees of `tips`, when every one carries `token`, `ext`'s cluster token;
563/// each is marked proved under `ext`'s id.
564fn vouched_trees(ext: &External, tips: &[String], token: &str) -> Option<Vec<String>> {
565    let stamps = crate::gate_stamp::cluster_stamps_for(tips);
566    let hit = tips.iter().all(|t| {
567        stamps
568            .get(t)
569            .is_some_and(|(_, tokens)| tokens.iter().any(|held| held == token))
570    });
571    if !hit {
572        return None;
573    }
574    let trees: Vec<String> = stamps.values().map(|(tree, _)| tree.clone()).collect();
575    for tree in &trees {
576        mark_proved(&ext.id, tree);
577    }
578    Some(trees)
579}
580
581/// pre-push, a `platform=any` gate `push` whose commit-time twin `twin` is
582/// also `platform=any` and declares the same suite (the same cluster identity
583/// under one name: program, arguments, file scope, prepare and image): when
584/// `twin`'s cluster token sits on every tip's tree, claim that pass for `push`
585/// too. An action, not a lookup: it marks `push`'s id proved on those trees,
586/// which is what puts it in the linux block. A twin that runs anything else
587/// claims nothing, so the push gate runs.
588pub(crate) fn claim_twin_cluster_pass(
589    settings: &crate::config::Settings,
590    push: &External,
591    twin: &External,
592    tips: &[String],
593) -> bool {
594    if tips.is_empty() || !is_platform_any(push) || !is_platform_any(twin) {
595        return false;
596    }
597    let keys = machine_keys();
598    let Some(twin_token) = token_from(&keys, settings, twin, &twin.id) else {
599        return false;
600    };
601    // `push` as it would read under the twin's name: equal tokens mean the
602    // same cluster identity.
603    if token_from(&keys, settings, push, &twin.id).as_deref() != Some(twin_token.as_str()) {
604        return false;
605    }
606    let Some(trees) = vouched_trees(twin, tips, &twin_token) else {
607        return false;
608    };
609    for tree in &trees {
610        mark_proved(&push.id, tree);
611    }
612    true
613}
614
615/// `amont stamps`: does `tree` carry a cluster token for any of `ids`, each
616/// a trusted `platform=any` declaration?
617pub fn stamped_on_tree(
618    settings: &crate::config::Settings,
619    externals: &[External],
620    ids: &[String],
621    tree: &str,
622) -> bool {
623    let tokens: Vec<String> = externals
624        .iter()
625        .filter(|e| ids.contains(&e.id))
626        .filter_map(|e| token(settings, e))
627        .collect();
628    if tokens.is_empty() {
629        return false;
630    }
631    let on_tree = crate::gate_stamp::cluster_tokens(tree);
632    tokens.iter().any(|t| on_tree.contains(t))
633}
634
635/// post-commit: the blocking commit-time scripts whose cluster token is on
636/// HEAD's tree. The bypass ledger reads them as stamped: their pass is
637/// recorded, only not as a local token. Spawns nothing in a repository with
638/// no `platform=any` gate.
639pub fn covered_at_head(
640    settings: &crate::config::Settings,
641    manifest: &crate::manifest::Manifest,
642) -> Vec<String> {
643    if !manifest.externals.iter().any(is_platform_any) {
644        return Vec::new();
645    }
646    let Some(tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
647        return Vec::new();
648    };
649    let on_tree = crate::gate_stamp::cluster_tokens(&tree);
650    crate::hooks::run_tests::blocking_commit_decls(settings, &manifest.externals)
651        .into_iter()
652        .filter(|d| {
653            manifest
654                .externals
655                .iter()
656                .find(|e| e.id == d.id)
657                .and_then(|e| token(settings, e))
658                .is_some_and(|t| on_tree.contains(&t))
659        })
660        .map(|d| d.script)
661        .collect()
662}
663
664/// Run `ext` on the cluster if it is the cluster's to run. `true`: it passed
665/// there and the pass is recorded; the caller reports `Passed`. `false`: the
666/// caller runs it here, as it always has — either it was never the
667/// cluster's (no line logged), or the cluster did not prove it (the reason is
668/// logged).
669pub fn try_run(
670    settings: &crate::config::Settings,
671    ext: &External,
672    program: &str,
673    args: &[String],
674    judged: Judged,
675) -> bool {
676    if !is_platform_any(ext) || !executor_is_cluster(settings) {
677        return false;
678    }
679    let outcome = cluster_config(settings).and_then(|config| {
680        // Not announced once the apiserver has not answered: `run` refuses
681        // it at once and the gate runs here.
682        if !UNREACHABLE.load(Ordering::SeqCst) {
683            crate::say!(
684                "{}: running on the cluster",
685                crate::ui::highlight(&ext.short_name)
686            );
687        }
688        run(&config, ext, program, args, judged)
689    });
690    match outcome {
691        Ok(tree) => {
692            mark_proved(&ext.id, &tree);
693            true
694        }
695        Err(fallback) => {
696            // A signal killed the kubectl children: amont is dying, so no
697            // local re-run may start behind the signal cleanup.
698            crate::tree_run::park_if_dying();
699            if matches!(fallback, Fallback::Unreachable(_)) {
700                UNREACHABLE.store(true, Ordering::SeqCst);
701            }
702            say_fallback(&ext.short_name, &fallback);
703            log_line(&ext.id, &fallback.to_string());
704            false
705        }
706    }
707}
708
709/// The one terminal line a fallback earns, if any.
710fn say_fallback(short_name: &str, fallback: &Fallback) {
711    let name = crate::ui::highlight(short_name);
712    match fallback {
713        Fallback::Unconfigured(_) => {}
714        Fallback::Misconfigured { why, fix } => {
715            if !WARNED.swap(true, Ordering::SeqCst) {
716                crate::hooks::common::warn(&format!(
717                    "{name} runs here: {} — fix with {fix}",
718                    crate::ui::sanitize(why)
719                ));
720            }
721        }
722        Fallback::GateFailed(detail) => crate::hooks::common::warn(&format!(
723            "{name} failed on the cluster ({}); running it here for the verdict",
724            crate::ui::sanitize(detail)
725        )),
726        Fallback::Unreachable(why) => {
727            if !UNREACHABLE_SAID.swap(true, Ordering::SeqCst) {
728                crate::hooks::common::warn(&format!(
729                    "{name} and this hook's other cluster gates run here: the cluster did not answer ({})",
730                    crate::ui::sanitize(why)
731                ));
732            }
733        }
734        Fallback::UnreachableEarlier => {
735            if !UNREACHABLE_SAID.swap(true, Ordering::SeqCst) {
736                crate::hooks::common::warn(&format!(
737                    "the cluster did not answer earlier in this hook: {name} runs here"
738                ));
739            }
740        }
741        Fallback::BundleTooBig { mib, cap } => crate::hooks::common::warn(&format!(
742            "{name} runs here: its bundle is {mib} MiB, over the {cap} MiB cap — raise it with `git config greengate.cluster.maxBundleMiB <MiB>`"
743        )),
744        Fallback::SlotsTaken | Fallback::QuotaFull | Fallback::NotProved(_) => {
745            warn_unavailable(&name, fallback)
746        }
747    }
748}
749
750fn warn_unavailable(name: &str, fallback: &Fallback) {
751    crate::hooks::common::warn(&format!(
752        "{name} runs here: the cluster is unavailable ({})",
753        crate::ui::sanitize(&fallback.to_string())
754    ));
755}
756
757/// Append `<epoch> <gate> <reason>` to `greengate/cluster.log` in the common git
758/// directory. Best-effort: the log is evidence, never a verdict.
759fn log_line(gate: &str, reason: &str) {
760    // The log goes to the common dir of the process's own repository. A unit
761    // test runs inside a worktree of this repository, whose common dir is the
762    // live checkout's `.git`: it appended there on every run that settled a
763    // pass it could not record. No unit test reads the log.
764    if cfg!(test) {
765        return;
766    }
767    let reason: String = reason
768        .chars()
769        .map(|c| if c.is_control() { ' ' } else { c })
770        .collect();
771    let Some(dir) =
772        crate::git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])
773    else {
774        return;
775    };
776    let dir = Path::new(&dir).join(crate::names::STATE_DIR);
777    let line = format!("{} {gate} {reason}\n", crate::gate_evidence::now());
778    let written = std::fs::create_dir_all(&dir).and_then(|()| {
779        let mut f = std::fs::OpenOptions::new()
780            .create(true)
781            .append(true)
782            .open(dir.join("cluster.log"))?;
783        std::io::Write::write_all(&mut f, line.as_bytes())
784    });
785    if let Err(e) = written {
786        crate::hooks::common::warn(&format!("could not append to greengate/cluster.log: {e}"));
787    }
788}
789
790/// What a pass carries into its record.
791struct Proof {
792    image_id: String,
793    uid: String,
794    job: String,
795    bundle_bytes: u64,
796}
797
798/// Run on the cluster and record the pass. The judged tree on a pass.
799fn run(
800    config: &ClusterConfig,
801    ext: &External,
802    program: &str,
803    args: &[String],
804    judged: Judged,
805) -> Result<String, Fallback> {
806    // A signal that killed a kubectl child must not reach a local run.
807    crate::tree_run::park_if_dying();
808    if UNREACHABLE.load(Ordering::SeqCst) {
809        return Err(Fallback::UnreachableEarlier);
810    }
811    let tree = tree_of(judged)
812        .ok_or_else(|| Fallback::NotProved("git would not name the tree to judge".into()))?;
813    let commit = parentless_commit(&tree)
814        .ok_or_else(|| Fallback::NotProved("git commit-tree failed".into()))?;
815    let deadline = Instant::now() + Duration::from_secs(config.timeout_secs + 60);
816    let kube = Kube::new(config);
817    let scratch = Scratch::new(&ext.id, &kube)?;
818    let mut argv = vec![program.to_string()];
819    argv.extend(args.iter().cloned());
820    let spec = Spec {
821        config,
822        gate: &ext.id,
823        tree: &tree,
824        repo_dir: &repo_dir(),
825        argv: &argv,
826        run_label: &scratch.run_label(),
827    };
828    // The gate runs on the cluster and takes no host slot (ADR-0016): a slot
829    // parked for the next local gate would sit idle for the whole run.
830    crate::host_slots::release_parked();
831    let job = claim_slot(&kube, &spec, &scratch, deadline)?;
832    let outcome = run_in(&kube, config, &job, &scratch, &commit, &tree, deadline);
833    job.delete(&kube, &ext.id, deadline);
834    let proof = outcome?;
835    record(ext, config, &tree, &proof)?;
836    Ok(tree)
837}
838
839/// Write the cluster token, with its provenance. A pass with no record is no
840/// pass: the caller runs the gate here.
841fn record(
842    ext: &External,
843    config: &ClusterConfig,
844    tree: &str,
845    proof: &Proof,
846) -> Result<(), Fallback> {
847    let token = crate::gate_identity::cluster_token(
848        ext,
849        &ext.id,
850        config.prepare.as_deref(),
851        &config.digest,
852    )
853    .ok_or_else(|| Fallback::NotProved("git would not hash the cluster identity".into()))?;
854    let provenance = format!(
855        "platform={PLATFORM} image={} job={} name={} bundle={}",
856        proof.image_id, proof.uid, proof.job, proof.bundle_bytes
857    );
858    record_token(tree, &token, &provenance)
859}
860
861/// Write `token`, as given, on `tree`'s cluster note with its provenance. The
862/// detached lane passes the token it froze at submission, never one worked out
863/// from today's configuration.
864fn record_token(tree: &str, token: &str, provenance: &str) -> Result<(), Fallback> {
865    let _held = STAMP_LOCK.lock().unwrap_or_else(|p| p.into_inner());
866    if crate::gate_stamp::stamp_cluster(tree, token, provenance) {
867        Ok(())
868    } else {
869        Err(Fallback::NotProved(
870            "git refused to write the cluster stamp".into(),
871        ))
872    }
873}
874
875/// Everything after the Job exists: the bundle in, the logs out, the verdict.
876fn run_in(
877    kube: &Kube,
878    config: &ClusterConfig,
879    job: &Job,
880    scratch: &Scratch,
881    commit: &str,
882    tree: &str,
883    deadline: Instant,
884) -> Result<Proof, Fallback> {
885    let bundle = Bundle::create(scratch, job.slot, commit)?;
886    let cap = config.max_bundle_mib;
887    if bundle.bytes > cap * MIB {
888        return Err(Fallback::BundleTooBig {
889            mib: bundle.bytes.div_ceil(MIB),
890            cap,
891        });
892    }
893    let fetch_until = deadline.min(Instant::now() + config.start_wait);
894    let pod = wait_for_fetch(kube, &job.uid, fetch_until, config.start_wait)?;
895    kube.send_bundle(&pod, &bundle, deadline)?;
896    wait_for_gate(kube, &job.uid, deadline)?;
897    kube.stream_logs(&pod, deadline);
898    let end = wait_for_job(kube, job, deadline)?;
899    let pod = pod_facts(kube, &job.uid, deadline)?
900        .ok_or_else(|| Fallback::NotProved("the pod is gone".into()))?;
901    let image_id = judge(&end, &pod, tree, config.prepare.as_deref())?;
902    Ok(Proof {
903        image_id,
904        uid: job.uid.clone(),
905        job: job.name.clone(),
906        bundle_bytes: bundle.bytes,
907    })
908}
909
910/// A commit with no parent holding `tree`, fixed identity and date, so the
911/// same tree is the same commit. Nothing refers to it once the bundle is
912/// written.
913fn parentless_commit(tree: &str) -> Option<String> {
914    let out = Command::new("git")
915        .args(["commit-tree", tree, "-m", "greengate cluster gate"])
916        .env("GIT_AUTHOR_NAME", crate::names::GIT_AUTHOR)
917        .env("GIT_AUTHOR_EMAIL", crate::names::GIT_EMAIL)
918        .env("GIT_COMMITTER_NAME", crate::names::GIT_AUTHOR)
919        .env("GIT_COMMITTER_EMAIL", crate::names::GIT_EMAIL)
920        .env("GIT_AUTHOR_DATE", "@0 +0000")
921        .env("GIT_COMMITTER_DATE", "@0 +0000")
922        .stdin(Stdio::null())
923        .output()
924        .ok()?;
925    let oid = String::from_utf8_lossy(&out.stdout).trim().to_string();
926    (out.status.success() && !oid.is_empty()).then_some(oid)
927}
928
929/// The repository's name as a plain `[A-Za-z0-9._-]` word with no leading
930/// dot: the cache subPath, so one repository's code cannot plant a cache
931/// another's gate reads. From the COMMON git directory, so every worktree of
932/// one repository shares it.
933fn repo_dir() -> String {
934    let common = crate::git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])
935        .map(PathBuf::from)
936        .unwrap_or_default();
937    let name = if common.file_name().is_some_and(|n| n == ".git") {
938        common.parent().and_then(Path::file_name)
939    } else {
940        common.file_name()
941    };
942    sanitize_repo_dir(
943        &name
944            .map(|n| n.to_string_lossy().into_owned())
945            .unwrap_or_default(),
946    )
947}
948
949/// See [`repo_dir`]. Pure.
950fn sanitize_repo_dir(raw: &str) -> String {
951    let raw = raw.strip_suffix(".git").unwrap_or(raw);
952    let clean: String = raw
953        .chars()
954        .map(|c| {
955            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
956                c
957            } else {
958                '-'
959            }
960        })
961        .collect();
962    let clean = clean.trim_start_matches('.');
963    if clean.is_empty() {
964        "repo".to_string()
965    } else {
966        clean.to_string()
967    }
968}
969
970struct Kube {
971    kubeconfig: PathBuf,
972    namespace: String,
973}
974
975/// How a kubectl call ended.
976enum Call {
977    Ok(String),
978    /// Exit non-zero, with its stderr.
979    Refused(String),
980    /// Could not start: nothing reached the apiserver.
981    NotStarted(String),
982    /// Outlived its deadline, or its wait failed: the request may have
983    /// reached the apiserver all the same.
984    TimedOut(String),
985}
986
987impl Kube {
988    fn new(config: &ClusterConfig) -> Kube {
989        Kube {
990            kubeconfig: config.kubeconfig.clone(),
991            namespace: config.namespace.clone(),
992        }
993    }
994
995    /// `kubectl --kubeconfig <path> <request timeout> -n <ns> <args>`, stdin
996    /// null, git's environment removed.
997    fn command(&self, request_timeout: &str, args: &[&str]) -> Command {
998        let mut cmd = Command::new(crate::hooks::common::program("kubectl"));
999        cmd.arg("--kubeconfig")
1000            .arg(&self.kubeconfig)
1001            .arg(request_timeout)
1002            .args(["-n", &self.namespace])
1003            .args(args)
1004            .stdin(Stdio::null());
1005        crate::hooks::common::strip_git_env(&mut cmd);
1006        cmd
1007    }
1008
1009    /// One request, under kubectl's own 10 s request timeout.
1010    fn short_call(&self, args: &[&str]) -> Command {
1011        self.command("--request-timeout=10s", args)
1012    }
1013
1014    /// `exec` and `logs -f`, whose stream kubectl's request timeout would
1015    /// cut: the ceiling is ours.
1016    fn stream_call(&self, args: &[&str]) -> Command {
1017        self.command("--request-timeout=0", args)
1018    }
1019
1020    fn capture(&self, args: &[&str], secs: u64) -> Call {
1021        capture(&mut self.short_call(args), secs)
1022    }
1023
1024    /// A call whose output does not matter, only that it worked.
1025    fn bounded(&self, args: &[&str], secs: u64) -> Result<(), String> {
1026        match self.capture(args, secs) {
1027            Call::Ok(_) => Ok(()),
1028            Call::Refused(e) | Call::NotStarted(e) | Call::TimedOut(e) => Err(last_line(&e)),
1029        }
1030    }
1031
1032    /// The bundle, on the one stdin that is not null; its stderr is the
1033    /// reason when it fails.
1034    fn send_bundle(&self, pod: &str, bundle: &Bundle, deadline: Instant) -> Result<(), Fallback> {
1035        let file = std::fs::File::open(&bundle.path)
1036            .map_err(|e| Fallback::NotProved(format!("bundle: {e}")))?;
1037        let bytes = format!("EXPECTED_BYTES={}", bundle.bytes);
1038        let mut cmd = self.stream_call(&[
1039            "exec",
1040            "-i",
1041            "-c",
1042            "fetch",
1043            pod,
1044            "--",
1045            "env",
1046            &bytes,
1047            "fetch-receive",
1048        ]);
1049        cmd.stdin(file);
1050        let secs = secs_left(deadline, u64::MAX);
1051        match capture(&mut cmd, secs) {
1052            Call::Ok(_) => Ok(()),
1053            Call::Refused(e) => Err(Fallback::NotProved(format!(
1054                "fetch-receive failed: {}",
1055                last_line(&e)
1056            ))),
1057            Call::NotStarted(e) | Call::TimedOut(e) => Err(Fallback::Unreachable(e)),
1058        }
1059    }
1060
1061    /// The gate's output, as it runs, under the ceiling clock only: the
1062    /// silence budget does not apply to a pod. What the logs say decides
1063    /// nothing, so a log stream that fails is not a reason to fall back.
1064    fn stream_logs(&self, pod: &str, deadline: Instant) {
1065        let mut cmd = self.stream_call(&["logs", "-f", pod, "-c", "gate"]);
1066        let secs = secs_left(deadline, u64::MAX);
1067        match crate::live::current_sink() {
1068            Some((stage, idx)) => {
1069                cmd.stdout(Stdio::piped()).stderr(Stdio::null());
1070                let Ok(mut child) = cmd.spawn() else {
1071                    return;
1072                };
1073                if let Some(mut out) = child.stdout.take() {
1074                    // Detached: it ends with the pipe, and the pipe with kubectl.
1075                    std::thread::spawn(move || {
1076                        let mut buf = [0u8; 8192];
1077                        while let Ok(n) = std::io::Read::read(&mut out, &mut buf) {
1078                            if n == 0 {
1079                                break;
1080                            }
1081                            stage.append_raw(idx, &buf[..n]);
1082                        }
1083                    });
1084                }
1085                let waited = crate::hooks::common::wait_within(
1086                    &mut child,
1087                    crate::hooks::common::Clocks::ceiling_only(secs),
1088                    None,
1089                );
1090                drop(waited); // the logs decide nothing; see above
1091            }
1092            None => {
1093                let shown = crate::hooks::common::status_within_secs(&mut cmd, secs);
1094                drop(shown); // the logs decide nothing; see above
1095            }
1096        }
1097    }
1098}
1099
1100/// Run `cmd` with stdout and stderr captured apart, under a ceiling of
1101/// `secs`, through the hooks' bounded wait. Takes no host slot.
1102fn capture(cmd: &mut Command, secs: u64) -> Call {
1103    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
1104    let mut child = match cmd.spawn() {
1105        Ok(c) => c,
1106        Err(e) => return Call::NotStarted(format!("kubectl: {e}")),
1107    };
1108    let out = drain(child.stdout.take());
1109    let err = drain(child.stderr.take());
1110    let ran = crate::hooks::common::wait_within(
1111        &mut child,
1112        crate::hooks::common::Clocks::ceiling_only(secs),
1113        None,
1114    );
1115    let collect = |rx: std::sync::mpsc::Receiver<Vec<u8>>| {
1116        rx.recv_timeout(Duration::from_secs(2))
1117            .map(|b| String::from_utf8_lossy(&b).into_owned())
1118            .unwrap_or_default()
1119    };
1120    match ran {
1121        Ok(crate::hooks::common::Ran::Status(s)) if s.success() => Call::Ok(collect(out)),
1122        Ok(crate::hooks::common::Ran::Status(_)) => Call::Refused(collect(err)),
1123        Ok(crate::hooks::common::Ran::TimedOut(_)) => Call::TimedOut("kubectl timed out".into()),
1124        Err(e) => Call::TimedOut(format!("kubectl: {e}")),
1125    }
1126}
1127
1128/// Read a pipe to its end on a thread, handing the bytes over once.
1129fn drain(pipe: Option<impl std::io::Read + Send + 'static>) -> std::sync::mpsc::Receiver<Vec<u8>> {
1130    let (tx, rx) = std::sync::mpsc::channel();
1131    if let Some(mut pipe) = pipe {
1132        std::thread::spawn(move || {
1133            let mut buf = Vec::new();
1134            // A read error ends the pipe early; what was read still counts.
1135            let read = pipe.read_to_end(&mut buf);
1136            drop(read);
1137            // The receiver gave up after its own timeout: nobody to tell.
1138            let sent = tx.send(buf);
1139            drop(sent);
1140        });
1141    }
1142    rx
1143}
1144
1145/// What a refused `kubectl create` means for the slot.
1146#[derive(Debug, PartialEq, Eq)]
1147enum Refusal {
1148    /// The Job name is taken: the next slot.
1149    Taken,
1150    /// The quota is full: the next slot, then local.
1151    Quota,
1152    /// Anything else: the apiserver failing.
1153    Other,
1154}
1155
1156fn refusal(stderr: &str) -> Refusal {
1157    if stderr.contains("exceeded quota") {
1158        Refusal::Quota
1159    } else if stderr.contains("AlreadyExists") || stderr.contains("already exists") {
1160        Refusal::Taken
1161    } else {
1162        Refusal::Other
1163    }
1164}
1165
1166/// A Job amont created.
1167struct Job {
1168    run: u64,
1169    slot: u32,
1170    name: String,
1171    uid: String,
1172    gate: String,
1173}
1174
1175impl Job {
1176    /// Foreground and waited for, so no old pod still holds the slot's PVC
1177    /// when the next Job takes it — within the time left; past the deadline
1178    /// it is only asked to go. A delete that fails is said and logged: the
1179    /// slot stays taken until its TTL.
1180    fn delete(&self, kube: &Kube, gate: &str, deadline: Instant) {
1181        let left = deadline.saturating_duration_since(Instant::now()).as_secs();
1182        let timeout = format!("--timeout={}s", left.max(1));
1183        let deleted = if left >= 5 {
1184            let args = [
1185                "delete",
1186                "job",
1187                &self.name,
1188                "--cascade=foreground",
1189                "--wait",
1190                &timeout,
1191            ];
1192            kube.bounded(&args, left)
1193        } else {
1194            kube.bounded(&["delete", "job", &self.name, "--wait=false"], 5)
1195        };
1196        if let Err(why) = deleted {
1197            let reason = format!("could not delete Job {}: {why}", self.name);
1198            crate::hooks::common::warn(&reason);
1199            log_line(gate, &reason);
1200        }
1201        live_update(self.run, |l| l.created = Created::NotSent);
1202    }
1203}
1204
1205/// What the Job spec is built from.
1206struct Spec<'a> {
1207    config: &'a ClusterConfig,
1208    gate: &'a str,
1209    tree: &'a str,
1210    repo_dir: &'a str,
1211    argv: &'a [String],
1212    /// The value of the Job's `greengate.run` label.
1213    run_label: &'a str,
1214}
1215
1216/// Create `greengate-gate-slot-<k>` for the first free `k`.
1217fn claim_slot(
1218    kube: &Kube,
1219    spec: &Spec,
1220    scratch: &Scratch,
1221    deadline: Instant,
1222) -> Result<Job, Fallback> {
1223    crate::staged_only::install_signal_handler();
1224    let mut refusals = Vec::new();
1225    for slot in 0..spec.config.slots {
1226        let path = scratch.write(
1227            &format!("job-{slot}.json"),
1228            job_manifest(spec, slot).as_bytes(),
1229        )?;
1230        let path = path.to_string_lossy().into_owned();
1231        let name = format!("{JOB_PREFIX}{slot}");
1232        let args = ["create", "-f", &path, "-o", "jsonpath={.metadata.uid}"];
1233        live_update(scratch.run, |l| l.created = Created::Sent);
1234        let created = kube.capture(&args, secs_left(deadline, CALL_SECS));
1235        if crate::tree_run::is_dying() {
1236            // The signal watcher may have cleaned up before this `create`
1237            // landed: whatever it made is ours to drop, then park.
1238            delete_by_label(kube, &scratch.run_label(), spec.gate);
1239            crate::tree_run::park_if_dying();
1240        }
1241        match created {
1242            Call::Ok(uid) if !uid.trim().is_empty() => {
1243                live_update(scratch.run, |l| l.created = Created::Named(name.clone()));
1244                return Ok(Job {
1245                    run: scratch.run,
1246                    slot,
1247                    name,
1248                    uid: uid.trim().to_string(),
1249                    gate: spec.gate.to_string(),
1250                });
1251            }
1252            Call::Ok(_) => {
1253                // The Job exists, only unnamed by its UID: take it down by
1254                // name rather than hold the slot until its deadline.
1255                live_update(scratch.run, |l| l.created = Created::Named(name.clone()));
1256                delete_by_name(kube, &name, spec.gate);
1257                live_update(scratch.run, |l| l.created = Created::NotSent);
1258                return Err(Fallback::NotProved(
1259                    "kubectl create printed no Job UID".into(),
1260                ));
1261            }
1262            Call::Refused(err) => match refusal(&err) {
1263                Refusal::Taken | Refusal::Quota => refusals.push(refusal(&err)),
1264                Refusal::Other => return Err(Fallback::Unreachable(last_line(&err))),
1265            },
1266            Call::NotStarted(err) => return Err(Fallback::Unreachable(err)),
1267            // The request may have landed: drop whatever it made, briefly and
1268            // quietly; the Job's deadline bounds what a failed delete leaves.
1269            Call::TimedOut(err) => {
1270                delete_by_label(kube, &scratch.run_label(), spec.gate);
1271                return Err(Fallback::Unreachable(err));
1272            }
1273        }
1274    }
1275    if refusals.iter().all(|r| *r == Refusal::Quota) {
1276        Err(Fallback::QuotaFull)
1277    } else {
1278        Err(Fallback::SlotsTaken)
1279    }
1280}
1281
1282/// Ask the apiserver to drop the Job `name`, without waiting for it, for a Job
1283/// whose UID is unknown. A delete that fails is said and logged.
1284fn delete_by_name(kube: &Kube, name: &str, gate: &str) {
1285    if let Err(why) = kube.bounded(&["delete", "job", name, "--wait=false"], CALL_SECS) {
1286        say_delete_failed(&format!("Job {name}"), &why, gate);
1287    }
1288}
1289
1290/// Ask the apiserver to drop every Job carrying this run's label, without
1291/// waiting: for a `create` whose answer was lost. Bounded short and logged
1292/// only: the person was already told the cluster did not answer, and a Job
1293/// left behind ends at its own deadline.
1294fn delete_by_label(kube: &Kube, label: &str, gate: &str) {
1295    let selector = run_selector(label);
1296    let args = ["delete", "job", "-l", &selector, "--wait=false"];
1297    if let Err(why) = kube.bounded(&args, LABEL_DELETE_SECS) {
1298        log_line(
1299            gate,
1300            &format!(
1301                "could not delete the Jobs of this run: {}",
1302                crate::ui::sanitize(&why)
1303            ),
1304        );
1305    }
1306}
1307
1308/// The label selector of one run's Jobs.
1309fn run_selector(label: &str) -> String {
1310    format!("{RUN_LABEL_KEY}={label}")
1311}
1312
1313fn say_delete_failed(what: &str, why: &str, gate: &str) {
1314    let reason = format!("could not delete {what}: {}", crate::ui::sanitize(why));
1315    crate::hooks::common::warn(&reason);
1316    log_line(gate, &reason);
1317}
1318
1319fn last_line(s: &str) -> String {
1320    s.lines()
1321        .rev()
1322        .map(str::trim)
1323        .find(|l| !l.is_empty())
1324        .unwrap_or("no output")
1325        .to_string()
1326}
1327
1328fn json_string(v: &str) -> String {
1329    format!("\"{}\"", crate::json::escape(v))
1330}
1331
1332fn env_var(name: &str, value: &str) -> String {
1333    format!(
1334        "{{\"name\":{},\"value\":{}}}",
1335        json_string(name),
1336        json_string(value)
1337    )
1338}
1339
1340fn mount(name: &str, path: &str) -> String {
1341    format!(
1342        "{{\"name\":{},\"mountPath\":{}}}",
1343        json_string(name),
1344        json_string(path)
1345    )
1346}
1347
1348fn mount_sub(name: &str, path: &str, sub: &str) -> String {
1349    format!(
1350        "{{\"name\":{},\"mountPath\":{},\"subPath\":{}}}",
1351        json_string(name),
1352        json_string(path),
1353        json_string(sub)
1354    )
1355}
1356
1357fn args_json(argv: &[String]) -> String {
1358    format!(
1359        "[{}]",
1360        argv.iter()
1361            .map(|a| json_string(a))
1362            .collect::<Vec<_>>()
1363            .join(",")
1364    )
1365}
1366
1367const SECURITY: &str = "{\"allowPrivilegeEscalation\":false,\"capabilities\":{\"drop\":[\"ALL\"]}}";
1368
1369fn container(name: &str, image: &str, argv: &[String], extra: &str) -> String {
1370    format!(
1371        "{{\"name\":{},\"image\":{},\"args\":{},\"securityContext\":{SECURITY},{extra}}}",
1372        json_string(name),
1373        json_string(image),
1374        args_json(argv)
1375    )
1376}
1377
1378fn resources(memory: &str, cpu: &str) -> String {
1379    format!(
1380        "\"resources\":{{\"requests\":{{\"memory\":{m},\"cpu\":\"500m\"}},\
1381         \"limits\":{{\"memory\":{m},\"cpu\":{c}}}}}",
1382        m = json_string(memory),
1383        c = json_string(cpu)
1384    )
1385}
1386
1387/// The Job, as JSON `kubectl create -f` reads. `args`, never `command`: the
1388/// image's ENTRYPOINT is tini.
1389fn job_manifest(spec: &Spec, slot: u32) -> String {
1390    let config = spec.config;
1391    let gate_ref = format!("{TEMP_REF_PREFIX}{slot}");
1392    let fetch = container(
1393        "fetch",
1394        &config.image,
1395        &["/usr/local/bin/fetch".to_string()],
1396        &format!(
1397            "\"env\":[{},{},{}],\"volumeMounts\":[{},{},{}],{}",
1398            env_var("EXPECTED_TREE", spec.tree),
1399            env_var("GATE_REF", &gate_ref),
1400            env_var("REPO_DIR", spec.repo_dir),
1401            mount("cache", "/cache"),
1402            mount("work", "/work"),
1403            mount("checkout", "/checkout"),
1404            resources("512Mi", "1"),
1405        ),
1406    );
1407    let work_mounts = format!(
1408        "\"workingDir\":\"/checkout\",\"volumeMounts\":[{},{}],{}",
1409        mount_sub("cache", "/cache", spec.repo_dir),
1410        mount("checkout", "/checkout"),
1411        resources(MEMORY, CPU_LIMIT),
1412    );
1413    let mut init = vec![fetch];
1414    if let Some(prepare) = &config.prepare {
1415        let argv = ["sh".to_string(), "-c".to_string(), prepare.clone()];
1416        init.push(container("prepare", &config.image, &argv, &work_mounts));
1417    }
1418    let gate = container("gate", &config.image, spec.argv, &work_mounts);
1419    let managed_by = crate::names::MANAGED_BY;
1420    format!(
1421        "{{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\
1422         \"metadata\":{{\"name\":{name},\"labels\":{{\"app.kubernetes.io/managed-by\":\"{managed_by}\",{run_label_key}:{run_label}}},\
1423         \"annotations\":{{\"greengate.dev/gate\":{gate_id},\"greengate.dev/tree\":{tree}}}}},\
1424         \"spec\":{{\"backoffLimit\":0,\"activeDeadlineSeconds\":{deadline},\
1425         \"ttlSecondsAfterFinished\":300,\"template\":{{\"spec\":{{\
1426         \"restartPolicy\":\"Never\",\"priorityClassName\":{prio},\
1427         \"nodeSelector\":{{\"kubernetes.io/hostname\":{node}}},\
1428         \"imagePullSecrets\":[{{\"name\":{pull}}}],\
1429         \"automountServiceAccountToken\":false,\
1430         \"securityContext\":{{\"runAsNonRoot\":true,\"runAsUser\":1000,\"runAsGroup\":1000,\
1431         \"fsGroup\":1000,\"seccompProfile\":{{\"type\":\"RuntimeDefault\"}}}},\
1432         \"volumes\":[{{\"name\":\"cache\",\"persistentVolumeClaim\":{{\"claimName\":{pvc}}}}},\
1433         {{\"name\":\"work\",\"emptyDir\":{{}}}},{{\"name\":\"checkout\",\"emptyDir\":{{}}}}],\
1434         \"initContainers\":[{init}],\"containers\":[{gate}]}}}}}}}}",
1435        name = json_string(&format!("{JOB_PREFIX}{slot}")),
1436        run_label_key = json_string(RUN_LABEL_KEY),
1437        run_label = json_string(spec.run_label),
1438        gate_id = json_string(spec.gate),
1439        tree = json_string(spec.tree),
1440        deadline = config.timeout_secs + 60,
1441        prio = json_string(PRIORITY_CLASS),
1442        node = json_string(NODE),
1443        pull = json_string(PULL_SECRET),
1444        pvc = json_string(&format!("{CACHE_PREFIX}{slot}")),
1445        init = init.join(","),
1446    )
1447}
1448
1449/// Unique to this process and run, across every host sharing the namespace
1450/// (pids repeat from host to host, and in containers): the pid, a random
1451/// per-process nonce and the run. 45 characters at most (a 7-digit pid, 16
1452/// hex digits, a 20-digit run), inside a label value's 63, alphanumeric at
1453/// both ends.
1454fn run_label(run: u64) -> String {
1455    format!("{}-{:016x}-{run}", std::process::id(), process_nonce())
1456}
1457
1458/// 64 random bits, drawn once per process from the standard library's
1459/// randomly seeded hasher: no dependency, no file to read.
1460fn process_nonce() -> u64 {
1461    use std::hash::{BuildHasher, Hasher};
1462    static NONCE: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
1463    *NONCE.get_or_init(|| {
1464        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
1465        hasher.write_u128(
1466            std::time::SystemTime::now()
1467                .duration_since(std::time::UNIX_EPOCH)
1468                .map_or(0, |d| d.as_nanos()),
1469        );
1470        hasher.finish()
1471    })
1472}
1473
1474/// A private scratch directory for one cluster run — the Job manifests and
1475/// the bundle — created fresh (mode 0700 on unix), so no other user can guess,
1476/// pre-create or redirect a path in it. Removed on drop, with its entry in
1477/// the interrupt list.
1478struct Scratch {
1479    run: u64,
1480    dir: PathBuf,
1481}
1482
1483impl Scratch {
1484    fn new(gate: &str, kube: &Kube) -> Result<Scratch, Fallback> {
1485        let run = SEQ.fetch_add(1, Ordering::SeqCst);
1486        let gate: String = gate
1487            .chars()
1488            .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
1489            .collect();
1490        let dir = std::env::temp_dir().join(format!(
1491            "greengate-cluster-{}-{run}-{gate}",
1492            std::process::id()
1493        ));
1494        #[cfg(unix)]
1495        let builder = {
1496            let mut builder = std::fs::DirBuilder::new();
1497            std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
1498            builder
1499        };
1500        #[cfg(not(unix))]
1501        let builder = std::fs::DirBuilder::new();
1502        builder
1503            .create(&dir)
1504            .map_err(|e| Fallback::NotProved(format!("scratch directory: {e}")))?;
1505        LIVE.lock()
1506            .unwrap_or_else(|p| p.into_inner())
1507            .push(LiveRun {
1508                run,
1509                kubeconfig: kube.kubeconfig.clone(),
1510                namespace: kube.namespace.clone(),
1511                scratch: dir.clone(),
1512                run_label: run_label(run),
1513                created: Created::NotSent,
1514                gate_ref: None,
1515            });
1516        Ok(Scratch { run, dir })
1517    }
1518
1519    /// The `greengate.run` label value of this run's Jobs.
1520    fn run_label(&self) -> String {
1521        run_label(self.run)
1522    }
1523
1524    /// A new file in the scratch directory; refused if it exists.
1525    fn write(&self, name: &str, bytes: &[u8]) -> Result<PathBuf, Fallback> {
1526        let path = self.dir.join(name);
1527        let mut options = std::fs::OpenOptions::new();
1528        options.write(true).create_new(true);
1529        #[cfg(unix)]
1530        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
1531        options
1532            .open(&path)
1533            .and_then(|mut f| std::io::Write::write_all(&mut f, bytes))
1534            .map_err(|e| Fallback::NotProved(format!("scratch file: {e}")))?;
1535        Ok(path)
1536    }
1537}
1538
1539impl Drop for Scratch {
1540    fn drop(&mut self) {
1541        if let Err(e) = std::fs::remove_dir_all(&self.dir) {
1542            crate::hooks::common::warn(&format!("could not remove {}: {e}", self.dir.display()));
1543        }
1544        LIVE.lock()
1545            .unwrap_or_else(|p| p.into_inner())
1546            .retain(|l| l.run != self.run);
1547    }
1548}
1549
1550/// The judged commit as a git bundle of one temporary ref.
1551struct Bundle {
1552    path: PathBuf,
1553    bytes: u64,
1554}
1555
1556impl Bundle {
1557    fn create(scratch: &Scratch, slot: u32, commit: &str) -> Result<Bundle, Fallback> {
1558        let gate_ref = format!("{TEMP_REF_PREFIX}{slot}");
1559        if !crate::git::succeeds(&["update-ref", &gate_ref, commit]) {
1560            return Err(Fallback::NotProved(format!(
1561                "git update-ref {gate_ref} failed"
1562            )));
1563        }
1564        live_update(scratch.run, |l| l.gate_ref = Some(gate_ref.clone()));
1565        let path = scratch.dir.join(format!("{slot}.bundle"));
1566        let path_text = path.to_string_lossy().into_owned();
1567        let made = crate::git::succeeds(&["bundle", "create", "-q", &path_text, &gate_ref]);
1568        let dropped = crate::git::succeeds(&["update-ref", "-d", &gate_ref]);
1569        live_update(scratch.run, |l| l.gate_ref = None);
1570        if !dropped {
1571            crate::hooks::common::warn(&format!("could not delete the temporary ref {gate_ref}"));
1572        }
1573        if !made {
1574            return Err(Fallback::NotProved("git bundle create failed".into()));
1575        }
1576        let bytes = std::fs::metadata(&path)
1577            .map_err(|e| Fallback::NotProved(format!("bundle: {e}")))?
1578            .len();
1579        Ok(Bundle { path, bytes })
1580    }
1581}
1582
1583/// One container's state.
1584#[derive(Debug, Clone, PartialEq, Eq)]
1585enum State {
1586    Absent,
1587    Waiting,
1588    Running,
1589    Terminated {
1590        exit: Option<i64>,
1591        reason: String,
1592        message: String,
1593    },
1594}
1595
1596impl State {
1597    fn of(status: Option<&Value>) -> State {
1598        let Some(state) = status.and_then(|s| s.get("state")) else {
1599            return State::Absent;
1600        };
1601        if let Some(t) = state.get("terminated") {
1602            let text = |k: &str| t.get(k).and_then(Value::as_str).unwrap_or("").to_string();
1603            let exit = match t.get("exitCode") {
1604                Some(Value::Num(n)) => n.parse().ok(),
1605                _ => None,
1606            };
1607            return State::Terminated {
1608                exit,
1609                reason: text("reason"),
1610                message: text("message"),
1611            };
1612        }
1613        if state.get("running").is_some() {
1614            return State::Running;
1615        }
1616        State::Waiting
1617    }
1618
1619    fn started(&self) -> bool {
1620        match self {
1621            State::Running | State::Terminated { .. } => true,
1622            State::Absent | State::Waiting => false,
1623        }
1624    }
1625
1626    fn passed(&self) -> bool {
1627        matches!(self, State::Terminated { exit: Some(0), .. })
1628    }
1629
1630    /// `exit N` or `exit N, <reason>` for a container that ended badly.
1631    fn failed(&self) -> Option<String> {
1632        let State::Terminated { exit, reason, .. } = self else {
1633            return None;
1634        };
1635        if *exit == Some(0) {
1636            return None;
1637        }
1638        let code = exit.map_or("an unknown code".to_string(), |c| c.to_string());
1639        Some(match reason.as_str() {
1640            "" | "Error" | "Completed" => format!("exit {code}"),
1641            r => format!("exit {code}, {r}"),
1642        })
1643    }
1644}
1645
1646/// The pod's phase.
1647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1648enum Phase {
1649    Pending,
1650    Running,
1651    Succeeded,
1652    Failed,
1653    Unknown,
1654}
1655
1656impl Phase {
1657    fn parse(s: &str) -> Phase {
1658        match s {
1659            "Pending" => Phase::Pending,
1660            "Running" => Phase::Running,
1661            "Succeeded" => Phase::Succeeded,
1662            "Failed" => Phase::Failed,
1663            _ => Phase::Unknown,
1664        }
1665    }
1666
1667    fn ended(self) -> bool {
1668        match self {
1669            Phase::Succeeded | Phase::Failed => true,
1670            Phase::Pending | Phase::Running | Phase::Unknown => false,
1671        }
1672    }
1673}
1674
1675/// The pod's recorded facts.
1676#[derive(Debug, Clone, PartialEq, Eq)]
1677struct PodFacts {
1678    name: String,
1679    phase: Phase,
1680    disrupted: bool,
1681    fetch: State,
1682    prepare: State,
1683    gate: State,
1684    image_id: Option<String>,
1685}
1686
1687fn named<'a>(list: Option<&'a Value>, name: &str) -> Option<&'a Value> {
1688    list?
1689        .items()
1690        .iter()
1691        .find(|c| c.get("name").and_then(Value::as_str) == Some(name))
1692}
1693
1694fn str_at<'a>(v: Option<&'a Value>, key: &str) -> Option<&'a str> {
1695    v?.get(key).and_then(Value::as_str)
1696}
1697
1698/// The first pod of `kubectl get pods -o json`, as facts. Pure. The gate's
1699/// container is `gate`: a Job's.
1700fn parse_pod(json: &str) -> Option<PodFacts> {
1701    let doc = crate::json_read::parse(json)?;
1702    parse_pod_object(doc.get("items")?.items().first()?, "gate")
1703}
1704
1705/// One Pod object, as facts, the gate being the container `gate_container`:
1706/// `gate` in a Job's pod, `main` in an Argo Workflow's (Argo names the main
1707/// container itself). Pure.
1708fn parse_pod_object(pod: &Value, gate_container: &str) -> Option<PodFacts> {
1709    let status = pod.get("status");
1710    let inits = status.and_then(|s| s.get("initContainerStatuses"));
1711    let mains = status.and_then(|s| s.get("containerStatuses"));
1712    let gate = named(mains, gate_container);
1713    let disrupted = status.and_then(|s| s.get("conditions")).is_some_and(|c| {
1714        c.items().iter().any(|c| {
1715            str_at(Some(c), "type") == Some("DisruptionTarget")
1716                && str_at(Some(c), "status") == Some("True")
1717        })
1718    });
1719    Some(PodFacts {
1720        name: str_at(pod.get("metadata"), "name")?.to_string(),
1721        phase: Phase::parse(str_at(status, "phase").unwrap_or("")),
1722        disrupted,
1723        fetch: State::of(named(inits, "fetch")),
1724        prepare: State::of(named(inits, "prepare")),
1725        gate: State::of(gate),
1726        image_id: str_at(gate, "imageID")
1727            .filter(|s| !s.is_empty())
1728            .map(str::to_string),
1729    })
1730}
1731
1732/// The Job's terminal condition, if it has one.
1733#[derive(Debug, Clone, PartialEq, Eq)]
1734enum JobEnd {
1735    Running,
1736    Complete,
1737    Failed(String),
1738}
1739
1740/// `kubectl get job -o json`: its UID, its gate annotation, its end. Pure.
1741#[derive(Debug, Clone, PartialEq, Eq)]
1742struct JobFacts {
1743    uid: Option<String>,
1744    gate: Option<String>,
1745    end: JobEnd,
1746}
1747
1748fn parse_job(json: &str) -> Option<JobFacts> {
1749    let doc = crate::json_read::parse(json)?;
1750    let metadata = doc.get("metadata");
1751    let conditions = doc.get("status").and_then(|s| s.get("conditions"));
1752    let truthy = |c: &&Value| str_at(Some(c), "status") == Some("True");
1753    let mut end = JobEnd::Running;
1754    for c in conditions
1755        .map(Value::items)
1756        .unwrap_or(&[])
1757        .iter()
1758        .filter(truthy)
1759    {
1760        match str_at(Some(c), "type") {
1761            Some("Failed") => {
1762                let reason = str_at(Some(c), "reason").unwrap_or("Failed");
1763                end = JobEnd::Failed(reason.to_string());
1764                break;
1765            }
1766            Some("Complete") => end = JobEnd::Complete,
1767            _ => {}
1768        }
1769    }
1770    Some(JobFacts {
1771        uid: str_at(metadata, "uid").map(str::to_string),
1772        gate: str_at(
1773            metadata.and_then(|m| m.get("annotations")),
1774            crate::names::GATE_ANNOTATION,
1775        )
1776        .map(str::to_string),
1777        end,
1778    })
1779}
1780
1781/// The verdict, from recorded facts only: the observed imageID on a pass,
1782/// else why not. Pure.
1783fn judge(
1784    end: &JobEnd,
1785    pod: &PodFacts,
1786    expected_tree: &str,
1787    prepare: Option<&str>,
1788) -> Result<String, Fallback> {
1789    let not = |why: String| Err(Fallback::NotProved(why));
1790    if pod.disrupted {
1791        return not("the pod was disrupted (DisruptionTarget)".into());
1792    }
1793    match end {
1794        JobEnd::Complete => {}
1795        JobEnd::Failed(reason) => {
1796            return match pod.gate.failed() {
1797                Some(detail) => Err(Fallback::GateFailed(detail)),
1798                None => not(format!("the Job failed ({reason})")),
1799            }
1800        }
1801        JobEnd::Running => return not("the Job has no terminal condition".into()),
1802    }
1803    let want = format!("tree {expected_tree}");
1804    match &pod.fetch {
1805        State::Terminated {
1806            exit: Some(0),
1807            message,
1808            ..
1809        } if message.trim() == want => {}
1810        State::Terminated { message, .. } => {
1811            return not(format!("fetch reported {:?}, not {want:?}", message.trim()))
1812        }
1813        State::Absent | State::Waiting | State::Running => {
1814            return not("fetch did not terminate".into())
1815        }
1816    }
1817    if prepare.is_some() && !pod.prepare.passed() {
1818        return not("prepare did not exit 0".into());
1819    }
1820    if !pod.gate.passed() {
1821        return match pod.gate.failed() {
1822            Some(detail) => Err(Fallback::GateFailed(detail)),
1823            None => not("the gate did not finish".into()),
1824        };
1825    }
1826    match &pod.image_id {
1827        Some(id) => Ok(id.clone()),
1828        None => not("the pod recorded no imageID".into()),
1829    }
1830}
1831
1832/// The pod of the Job `uid`, by its controller label only — never by name,
1833/// which an older Job's pod could share.
1834fn pod_facts(kube: &Kube, uid: &str, deadline: Instant) -> Result<Option<PodFacts>, Fallback> {
1835    let selector = format!("controller-uid={uid}");
1836    let args = ["get", "pods", "-l", &selector, "-o", "json"];
1837    match kube.capture(&args, secs_left(deadline, CALL_SECS)) {
1838        Call::Ok(json) => Ok(parse_pod(&json)),
1839        Call::Refused(e) => Err(Fallback::NotProved(format!(
1840            "kubectl get pods: {}",
1841            last_line(&e)
1842        ))),
1843        Call::NotStarted(e) | Call::TimedOut(e) => Err(Fallback::Unreachable(e)),
1844    }
1845}
1846
1847/// Poll until `done` answers, or `until` passes.
1848fn poll<T>(
1849    until: Instant,
1850    mut done: impl FnMut() -> Result<Option<T>, Fallback>,
1851) -> Result<Option<T>, Fallback> {
1852    loop {
1853        if let Some(v) = done()? {
1854            return Ok(Some(v));
1855        }
1856        if Instant::now() >= until {
1857            return Ok(None);
1858        }
1859        std::thread::sleep(POLL);
1860    }
1861}
1862
1863/// Wait, bounded, for `fetch` — trusted image code, before any repository
1864/// code — to be Running. The pod's name, or why not.
1865fn wait_for_fetch(
1866    kube: &Kube,
1867    uid: &str,
1868    until: Instant,
1869    wait: Duration,
1870) -> Result<String, Fallback> {
1871    let found = poll(until, || {
1872        let Some(p) = pod_facts(kube, uid, until)? else {
1873            return Ok(None);
1874        };
1875        Ok(match p.fetch {
1876            State::Running => Some(Ok(p.name)),
1877            State::Terminated { .. } => Some(Err(Fallback::NotProved(
1878                "fetch ended before the bundle arrived".into(),
1879            ))),
1880            State::Absent | State::Waiting => None,
1881        })
1882    })?;
1883    found.unwrap_or_else(|| {
1884        Err(Fallback::NotProved(format!(
1885            "the pod was not Running within {} s",
1886            wait.as_secs()
1887        )))
1888    })
1889}
1890
1891/// Wait until the gate container has started, or an init container failed.
1892fn wait_for_gate(kube: &Kube, uid: &str, deadline: Instant) -> Result<(), Fallback> {
1893    let found = poll(deadline, || {
1894        let Some(p) = pod_facts(kube, uid, deadline)? else {
1895            return Ok(None);
1896        };
1897        // An init container that failed is infrastructure, never the gate's
1898        // verdict: said first, whatever the pod's phase.
1899        if let Some(w) = p.fetch.failed() {
1900            return Ok(Some(Err(Fallback::NotProved(format!("fetch {w}")))));
1901        }
1902        if let Some(w) = p.prepare.failed() {
1903            return Ok(Some(Err(Fallback::NotProved(format!("prepare {w}")))));
1904        }
1905        Ok((p.gate.started() || p.phase.ended()).then_some(Ok(())))
1906    })?;
1907    found.unwrap_or_else(|| {
1908        Err(Fallback::NotProved(
1909            "the gate did not start before the deadline".into(),
1910        ))
1911    })
1912}
1913
1914/// Wait for the Job's terminal condition — shortly after the logs end, or at
1915/// the deadline — on the Job amont created: its UID and gate annotation must
1916/// be this run's, or nothing it reports is judged.
1917fn wait_for_job(kube: &Kube, job: &Job, deadline: Instant) -> Result<JobEnd, Fallback> {
1918    let until = deadline.min(Instant::now() + Duration::from_secs(60));
1919    let found = poll(until, || {
1920        let args = ["get", "job", &job.name, "-o", "json"];
1921        let json = match kube.capture(&args, secs_left(deadline, CALL_SECS)) {
1922            Call::Ok(json) => json,
1923            Call::Refused(e) => {
1924                return Err(Fallback::NotProved(format!(
1925                    "kubectl get job: {}",
1926                    last_line(&e)
1927                )))
1928            }
1929            Call::NotStarted(e) | Call::TimedOut(e) => return Err(Fallback::Unreachable(e)),
1930        };
1931        let Some(facts) = parse_job(&json) else {
1932            return Ok(None);
1933        };
1934        if facts.uid.as_deref() != Some(job.uid.as_str())
1935            || facts.gate.as_deref() != Some(job.gate.as_str())
1936        {
1937            return Err(Fallback::NotProved(format!(
1938                "{} is not the Job this run created",
1939                job.name
1940            )));
1941        }
1942        Ok((facts.end != JobEnd::Running).then_some(facts.end))
1943    })?;
1944    found.ok_or_else(|| Fallback::NotProved("the Job reached no terminal condition".into()))
1945}
1946
1947#[cfg(test)]
1948mod tests {
1949    use super::*;
1950    /// A run label is the pid, a 16-hex-digit nonce and the run: valid as a
1951    /// label value, distinct per run, and the same nonce within one process.
1952    #[test]
1953    fn a_run_label_is_pid_nonce_and_run() {
1954        let first = run_label(1);
1955        let parts: Vec<&str> = first.split('-').collect();
1956        assert_eq!(parts.len(), 3, "{first}");
1957        assert_eq!(parts[0], std::process::id().to_string());
1958        assert_eq!(parts[1].len(), 16, "{first}");
1959        assert!(parts[1].chars().all(|c| c.is_ascii_hexdigit()), "{first}");
1960        assert_eq!(parts[2], "1");
1961        assert!(first.len() <= 63);
1962        let second = run_label(2);
1963        assert_ne!(first, second);
1964        assert_eq!(second.split('-').nth(1), Some(parts[1]));
1965    }
1966
1967    fn cluster_config(prepare: Option<&str>) -> ClusterConfig {
1968        ClusterConfig {
1969            kubeconfig: PathBuf::from("/k"),
1970            namespace: "greengate-gates".into(),
1971            slots: 2,
1972            image: format!("reg/gate:1@sha256:{}", "a".repeat(64)),
1973            digest: format!("sha256:{}", "a".repeat(64)),
1974            max_bundle_mib: 1,
1975            start_wait: Duration::from_secs(30),
1976            timeout_secs: 3600,
1977            prepare: prepare.map(str::to_string),
1978        }
1979    }
1980
1981    #[test]
1982    fn a_digest_is_sha256_and_64_hex() {
1983        let hex = "b".repeat(64);
1984        assert_eq!(
1985            digest_of(&format!("r/x:1@sha256:{hex}")),
1986            Some(format!("sha256:{hex}").as_str())
1987        );
1988        assert_eq!(digest_of("r/x:1"), None);
1989        assert_eq!(digest_of("r/x@sha256:short"), None);
1990    }
1991
1992    #[test]
1993    fn a_repo_dir_is_a_plain_name() {
1994        assert_eq!(sanitize_repo_dir("amont"), "amont");
1995        assert_eq!(sanitize_repo_dir("my repo!"), "my-repo-");
1996        assert_eq!(sanitize_repo_dir("..hidden"), "hidden");
1997        assert_eq!(sanitize_repo_dir("x.git"), "x");
1998        assert_eq!(sanitize_repo_dir(""), "repo");
1999    }
2000
2001    /// Every later wait is capped at the time the one deadline leaves.
2002    #[test]
2003    fn a_wait_never_outlives_the_deadline() {
2004        let soon = Instant::now() + Duration::from_secs(3);
2005        assert!(secs_left(soon, CALL_SECS) <= 3);
2006        let later = Instant::now() + Duration::from_secs(600);
2007        assert_eq!(secs_left(later, CALL_SECS), CALL_SECS);
2008        let past = Instant::now() - Duration::from_secs(1);
2009        assert_eq!(secs_left(past, CALL_SECS), 1, "a floor of one second");
2010    }
2011
2012    #[test]
2013    fn the_job_carries_the_contract() {
2014        let config = cluster_config(Some("make deps"));
2015        let argv = vec!["scripts/lint.sh".to_string(), "--strict".to_string()];
2016        let spec = Spec {
2017            config: &config,
2018            gate: "pre-commit-lint",
2019            tree: "abc",
2020            repo_dir: "amont",
2021            argv: &argv,
2022            run_label: "42-7",
2023        };
2024        let json = job_manifest(&spec, 1);
2025        let doc = crate::json_read::parse(&json).expect("valid JSON");
2026        let job_spec = doc.get("spec").unwrap();
2027        assert_eq!(job_spec.get("backoffLimit"), Some(&Value::Num("0".into())));
2028        assert_eq!(
2029            job_spec.get("activeDeadlineSeconds"),
2030            Some(&Value::Num("3660".into()))
2031        );
2032        assert!(!json.contains("\"command\""));
2033        for needle in [
2034            "\"name\":\"greengate-gate-slot-1\"",
2035            "\"claimName\":\"gate-cache-1\"",
2036            "\"subPath\":\"amont\"",
2037            "\"restartPolicy\":\"Never\"",
2038            "\"priorityClassName\":\"gate-batch\"",
2039            "\"kubernetes.io/hostname\":\"talos-wk-3-gpu\"",
2040            "\"automountServiceAccountToken\":false",
2041            "\"args\":[\"sh\",\"-c\",\"make deps\"]",
2042            "\"args\":[\"scripts/lint.sh\",\"--strict\"]",
2043            "\"value\":\"refs/amont/cluster/1\"",
2044            "\"greengate.dev/gate\":\"pre-commit-lint\"",
2045        ] {
2046            assert!(json.contains(needle), "{needle} missing from {json}");
2047        }
2048    }
2049
2050    fn pod(fetch: State, gate: State) -> PodFacts {
2051        PodFacts {
2052            name: "p".into(),
2053            phase: Phase::Succeeded,
2054            disrupted: false,
2055            fetch,
2056            prepare: State::Absent,
2057            gate,
2058            image_id: Some("img@sha256:x".into()),
2059        }
2060    }
2061
2062    fn done(exit: i64, reason: &str, message: &str) -> State {
2063        State::Terminated {
2064            exit: Some(exit),
2065            reason: reason.into(),
2066            message: message.into(),
2067        }
2068    }
2069
2070    #[test]
2071    fn only_recorded_facts_make_a_pass() {
2072        let ok = pod(done(0, "", "tree t1\n"), done(0, "", ""));
2073        assert_eq!(
2074            judge(&JobEnd::Complete, &ok, "t1", None),
2075            Ok("img@sha256:x".into())
2076        );
2077        let failed = || JobEnd::Failed("BackoffLimitExceeded".into());
2078        let cases: Vec<(&str, JobEnd, PodFacts, Option<&str>)> = vec![
2079            (
2080                "fetch reported",
2081                JobEnd::Complete,
2082                pod(done(0, "", "tree t2"), done(0, "", "")),
2083                None,
2084            ),
2085            (
2086                "failed on the cluster (exit 2)",
2087                failed(),
2088                pod(done(0, "", "tree t1"), done(2, "Error", "")),
2089                None,
2090            ),
2091            (
2092                "exit 137, OOMKilled",
2093                failed(),
2094                pod(done(0, "", "tree t1"), done(137, "OOMKilled", "")),
2095                None,
2096            ),
2097            (
2098                "DeadlineExceeded",
2099                JobEnd::Failed("DeadlineExceeded".into()),
2100                pod(done(0, "", "tree t1"), State::Running),
2101                None,
2102            ),
2103            (
2104                "prepare did not exit 0",
2105                JobEnd::Complete,
2106                ok.clone(),
2107                Some("make"),
2108            ),
2109            ("no terminal condition", JobEnd::Running, ok.clone(), None),
2110            (
2111                "no imageID",
2112                JobEnd::Complete,
2113                PodFacts {
2114                    image_id: None,
2115                    ..ok.clone()
2116                },
2117                None,
2118            ),
2119            (
2120                "DisruptionTarget",
2121                JobEnd::Complete,
2122                PodFacts {
2123                    disrupted: true,
2124                    ..ok.clone()
2125                },
2126                None,
2127            ),
2128        ];
2129        for (why, end, p, prepare) in cases {
2130            let reason = judge(&end, &p, "t1", prepare).expect_err(why).to_string();
2131            assert!(reason.contains(why), "{why}: {reason}");
2132        }
2133    }
2134
2135    #[test]
2136    fn facts_parse_from_kubectl_json() {
2137        let json = r#"{"items":[{"metadata":{"name":"greengate-gate-slot-0-x"},
2138          "status":{"phase":"Failed","conditions":[{"type":"DisruptionTarget","status":"True"}],
2139          "initContainerStatuses":[{"name":"fetch","state":{"terminated":{"exitCode":0,"message":"tree t"}}}],
2140          "containerStatuses":[{"name":"gate","imageID":"i@sha256:1","state":{"terminated":{"exitCode":137,"reason":"OOMKilled"}}}]}}]}"#;
2141        let p = parse_pod(json).expect("parses");
2142        assert!(p.disrupted);
2143        assert_eq!(p.phase, Phase::Failed);
2144        assert_eq!(p.image_id.as_deref(), Some("i@sha256:1"));
2145        assert_eq!(p.gate, done(137, "OOMKilled", ""));
2146        assert_eq!(p.prepare, State::Absent);
2147        let job = r#"{"metadata":{"uid":"u1","annotations":{"greengate.dev/gate":"pre-commit-x"}},
2148          "status":{"conditions":[{"type":"Failed","status":"True","reason":"DeadlineExceeded"}]}}"#;
2149        assert_eq!(
2150            parse_job(job),
2151            Some(JobFacts {
2152                uid: Some("u1".into()),
2153                gate: Some("pre-commit-x".into()),
2154                end: JobEnd::Failed("DeadlineExceeded".into()),
2155            })
2156        );
2157        let complete = r#"{"status":{"conditions":[{"type":"Complete","status":"True"}]}}"#;
2158        assert_eq!(parse_job(complete).map(|j| j.end), Some(JobEnd::Complete));
2159        assert_eq!(
2160            parse_job(r#"{"status":{}}"#).map(|j| j.end),
2161            Some(JobEnd::Running)
2162        );
2163    }
2164
2165    #[test]
2166    fn a_refusal_is_a_name_clash_the_quota_or_trouble() {
2167        assert_eq!(
2168            refusal("Error from server (AlreadyExists): jobs.batch \"greengate-gate-slot-0\" already exists"),
2169            Refusal::Taken
2170        );
2171        assert_eq!(
2172            refusal("Error from server (Forbidden): ... exceeded quota: gates, requested: limits.memory=4Gi"),
2173            Refusal::Quota
2174        );
2175        assert_eq!(
2176            refusal("Unable to connect to the server: dial tcp: i/o timeout"),
2177            Refusal::Other
2178        );
2179    }
2180
2181    #[test]
2182    fn a_bundle_over_the_cap_says_its_size_in_mib() {
2183        let f = Fallback::BundleTooBig { mib: 63, cap: 50 };
2184        assert_eq!(f.to_string(), "bundle-too-big: 63 MiB, over the 50 MiB cap");
2185    }
2186}