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