Skip to main content

greengate_runtime/cluster/detached/
collect.rs

1//! Collect: turn the passes of detached Workflows into cluster tokens
2//! (ADR-0017), cheaply, at the start of a hook.
3//!
4//! With nothing pending it costs one `stat` and spawns no `kubectl`. With
5//! something pending it takes the pending file's lock without waiting (busy
6//! means somebody else is collecting: return), and asks the cluster ONE
7//! question per hook process: `kubectl get workflows,pods -l 'amont.run in
8//! (…)' -o json`, under a 1 s request timeout and a wall deadline. A failed
9//! read keeps every record for the next hook.
10//!
11//! What a pod proves is read from its `containerStatuses` and
12//! `initContainerStatuses` alone, as ADR-0016's Job does. The Workflow's and
13//! its nodes' phases say only that the pod FINISHED: gate code can write what
14//! Argo's executor reads, so a phase is never a pass. The pod must also be
15//! the one submitted (its owner is the saved Workflow UID; its images, tree
16//! and command are the frozen ones), and the token written is the one frozen
17//! at submission.
18
19use std::sync::atomic::{AtomicBool, Ordering};
20
21use crate::json_read::Value;
22
23use super::super::{
24    capture, judge, last_line, log_line, parse_pod_object, record_token, Call, Fallback, JobEnd,
25    Kube, PodFacts, State, PLATFORM, RUN_LABEL_KEY,
26};
27use super::pending::{GateState, Pending, PendingError, RecordPhase, Store};
28use super::workflow::{check_pod, check_workflow, node_name, template_name, TTL_SECS};
29
30/// The wall deadline for the one batched call. `kubectl`'s own request timeout
31/// is 1 s; this bounds the process around it.
32const COLLECT_SECS: u64 = 5;
33/// Bound on each `patch` of `--stop`, and on all of them together.
34const PATCH_SECS: u64 = 10;
35const STOP_SECS: u64 = 30;
36/// An intent no Workflow appeared for in this long was never created.
37// holds-until: an apiserver slower than this to show a created Workflow — a
38// create that lands after the grace is not adopted, and its gates run at the
39// push instead
40const INTENT_GRACE_SECS: u64 = 600;
41/// A record outlives its Workflow's TTL by this long, then goes whatever the
42/// cluster says.
43const EXPIRY_SLACK_SECS: u64 = 3600;
44
45/// Once per hook process, however many callers ask. Process-scoped on
46/// purpose: a hook runs as one process and asks the cluster one question, so
47/// `stamps` inside a hook, or `--status` after a collect, do not repeat it;
48/// the next hook is a new process and asks again.
49static COLLECTED: AtomicBool = AtomicBool::new(false);
50
51/// Why a collect learned nothing, or could not keep what it learned.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub(crate) enum Trouble {
54    /// Another collect, or a submission, holds the pending file.
55    Busy,
56    /// The cluster did not answer.
57    NotReached(String),
58    /// The pending file could not be read or written.
59    StoreFailed(PendingError),
60}
61
62impl std::fmt::Display for Trouble {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        match self {
65            Trouble::Busy => write!(f, "another collect is running"),
66            Trouble::NotReached(why) => write!(f, "cluster not reached: {why}"),
67            Trouble::StoreFailed(why) => write!(f, "pending store failed: {why}"),
68        }
69    }
70}
71
72/// A Workflow that left the pending file in this collect, for `--status`.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub(crate) struct Settled {
75    pub name: String,
76    /// The Workflow's last phase in plain words.
77    pub phase: RecordPhase,
78    pub passed: Vec<String>,
79    pub failed: Vec<String>,
80}
81
82/// What a collect did.
83#[derive(Debug, Clone, PartialEq, Eq, Default)]
84pub(crate) struct Collected {
85    /// Passes written as cluster tokens.
86    pub passes: usize,
87    /// Workflows still pending afterwards.
88    pub pending: usize,
89    /// The Workflows this collect finished with.
90    pub settled: Vec<Settled>,
91    pub trouble: Option<Trouble>,
92}
93
94impl Collected {
95    fn troubled(trouble: Trouble) -> Collected {
96        Collected {
97            trouble: Some(trouble),
98            ..Collected::default()
99        }
100    }
101}
102
103/// A gate judged a pass: the token to write, frozen at submission.
104#[derive(Debug, Clone, PartialEq, Eq)]
105struct Pass {
106    gate: String,
107    tree: String,
108    token: String,
109    provenance: String,
110}
111
112/// What one record became.
113#[derive(Debug)]
114struct Resolution {
115    /// The record as it stands now.
116    record: Pending,
117    /// Whether it leaves the pending file: its Workflow is finished and judged,
118    /// or gone. A pass whose token is not written keeps it there all the same.
119    leaves: bool,
120    passes: Vec<Pass>,
121    /// One `cluster.log` line per gate that is not a pass: `(gate, why)`.
122    notes: Vec<(String, String)>,
123}
124
125/// Collect, once per hook process. Called at the start of pre-commit and
126/// pre-push, by `amont stamps`, `amont cluster collect` and `rehearse
127/// --status`.
128pub(crate) fn collect() -> Collected {
129    if COLLECTED.swap(true, Ordering::SeqCst) {
130        return Collected::default();
131    }
132    Store::here().map_or_else(Collected::default, |store| collect_from(&store))
133}
134
135fn collect_from(store: &Store) -> Collected {
136    if !store.exists() {
137        return Collected::default();
138    }
139    // Busy: another hook is collecting, or a submission is writing.
140    let Some(held) = store.try_lock() else {
141        return Collected::troubled(Trouble::Busy);
142    };
143    let records = match store.read() {
144        Ok(records) => records,
145        Err(why) => {
146            log_line("collect", &why.to_string());
147            return Collected::troubled(Trouble::StoreFailed(why));
148        }
149    };
150    if records.is_empty() {
151        return Collected::default();
152    }
153    let now = crate::gate_evidence::now();
154    let mut kept: Vec<Pending> = Vec::new();
155    let mut settled: Vec<Settled> = Vec::new();
156    let mut passes = 0;
157    let mut unreached: Vec<String> = Vec::new();
158    for group in by_cluster(records) {
159        let kube = Kube {
160            kubeconfig: group[0].kubeconfig.clone(),
161            namespace: group[0].namespace.clone(),
162        };
163        match fetch(&kube, &group) {
164            Ok(list) => {
165                for record in group {
166                    let done = settle(resolve(record, &list, now));
167                    passes += done.written;
168                    settled.extend(done.settled);
169                    kept.extend(done.record);
170                }
171            }
172            Err(why) => {
173                log_line("collect", &format!("the cluster could not be read: {why}"));
174                // The rollback says an unreadable record expires: it does,
175                // even when the cluster cannot be asked.
176                let (old, young): (Vec<Pending>, Vec<Pending>) =
177                    group.into_iter().partition(|r| is_expired(r, now));
178                for record in &old {
179                    log_line(
180                        record.gates.first().map_or("collect", |g| g.id.as_str()),
181                        &format!(
182                            "detached {}: older than the Workflow TTL; dropped",
183                            record.name
184                        ),
185                    );
186                }
187                kept.extend(young);
188                unreached.push(format!(
189                    "{why} (namespace {}, kubeconfig {})",
190                    kube.namespace,
191                    kube.kubeconfig.display()
192                ));
193            }
194        }
195    }
196    let trouble = match (store.write(&held, &kept), unreached) {
197        (Err(why), _) => {
198            log_line(
199                "collect",
200                &format!("cluster-pending was not updated: {why}"),
201            );
202            Some(Trouble::StoreFailed(why))
203        }
204        // Any group left unasked is named, even when another answered.
205        (Ok(()), why) if !why.is_empty() => Some(Trouble::NotReached(why.join("; "))),
206        (Ok(()), _) => None,
207    };
208    Collected {
209        passes,
210        pending: kept.len(),
211        settled,
212        trouble,
213    }
214}
215
216fn is_expired(record: &Pending, now: u64) -> bool {
217    now > record.submitted + TTL_SECS + EXPIRY_SLACK_SECS
218}
219
220/// The records grouped by the cluster they live on: one call each.
221fn by_cluster(records: Vec<Pending>) -> Vec<Vec<Pending>> {
222    let mut groups: Vec<Vec<Pending>> = Vec::new();
223    for record in records {
224        match groups
225            .iter_mut()
226            .find(|g| g[0].kubeconfig == record.kubeconfig && g[0].namespace == record.namespace)
227        {
228            Some(group) => group.push(record),
229            None => groups.push(vec![record]),
230        }
231    }
232    groups
233}
234
235/// The one batched call: every Workflow and pod carrying one of the records'
236/// run labels.
237fn fetch(kube: &Kube, records: &[Pending]) -> Result<Value, String> {
238    let labels: Vec<&str> = records.iter().map(|r| r.label.as_str()).collect();
239    let selector = format!("{RUN_LABEL_KEY} in ({})", labels.join(","));
240    let mut cmd = kube.command(
241        "--request-timeout=1s",
242        &["get", "workflows,pods", "-l", &selector, "-o", "json"],
243    );
244    match capture(&mut cmd, COLLECT_SECS) {
245        Call::Ok(json) => crate::json_read::parse(&json)
246            .ok_or_else(|| "kubectl printed something that is not JSON".to_string()),
247        Call::Refused(e) | Call::NotStarted(e) | Call::TimedOut(e) => Err(last_line(&e)),
248    }
249}
250
251/// What settling a resolution left.
252struct Settlement {
253    /// The record if it stays in the file.
254    record: Option<Pending>,
255    /// Tokens written.
256    written: usize,
257    /// The record's end, when it left the file.
258    settled: Option<Settled>,
259}
260
261/// [`settle_with`], writing tokens to the cluster note.
262fn settle(resolution: Resolution) -> Settlement {
263    settle_with(resolution, |pass| {
264        record_token(&pass.tree, &pass.token, &pass.provenance)
265    })
266}
267
268/// Write the passes of a resolution through `write` and log its notes. A pass
269/// whose token was not written returns its gate to waiting and keeps the
270/// record in the file, finished Workflow or not, so that the next collect
271/// tries again.
272fn settle_with(
273    resolution: Resolution,
274    mut write: impl FnMut(&Pass) -> Result<(), Fallback>,
275) -> Settlement {
276    let Resolution {
277        mut record,
278        leaves,
279        passes,
280        notes,
281    } = resolution;
282    for (gate, why) in &notes {
283        log_line(gate, why);
284    }
285    let mut written = 0;
286    let mut unwritten = 0;
287    for pass in &passes {
288        match write(pass) {
289            Ok(()) => {
290                written += 1;
291                // stderr: `amont stamps --json` collects first, and its stdout
292                // is the JSON object alone.
293                eprintln!(
294                    "collected the cluster pass of {} for tree {}",
295                    crate::ui::sanitize(&pass.gate),
296                    short(&pass.tree)
297                );
298            }
299            Err(why) => {
300                log_line(
301                    &pass.gate,
302                    &format!("detached: the pass was not recorded: {why}"),
303                );
304                unwritten += 1;
305                for gate in record.gates.iter_mut().filter(|g| g.id == pass.gate) {
306                    gate.state = GateState::Waiting;
307                }
308            }
309        }
310    }
311    if !leaves || unwritten > 0 {
312        return Settlement {
313            record: Some(record),
314            written,
315            settled: None,
316        };
317    }
318    let ids = |state: GateState| -> Vec<String> {
319        record
320            .gates
321            .iter()
322            .filter(|g| g.state == state)
323            .map(|g| g.id.clone())
324            .collect()
325    };
326    let settled = Settled {
327        name: record.name.clone(),
328        phase: record.phase,
329        passed: ids(GateState::Passed),
330        failed: ids(GateState::Failed),
331    };
332    Settlement {
333        record: None,
334        written,
335        settled: Some(settled),
336    }
337}
338
339fn short(oid: &str) -> &str {
340    oid.get(..8).unwrap_or(oid)
341}
342
343fn text<'a>(v: Option<&'a Value>, key: &str) -> Option<&'a str> {
344    v?.get(key).and_then(Value::as_str)
345}
346
347fn kind_of<'a>(list: &'a Value, kind: &'a str) -> impl Iterator<Item = &'a Value> {
348    list.get("items")
349        .map(Value::items)
350        .unwrap_or(&[])
351        .iter()
352        .filter(move |i| text(Some(i), "kind") == Some(kind))
353}
354
355/// The pod of the Workflow `uid` that ran `node`: named so by Argo's
356/// annotation, owned by that Workflow, and a Pod node of the Workflow's own
357/// status of the template the gate was submitted under.
358fn pod_of<'a>(list: &'a Value, wf: &Value, name: &str, uid: &str, task: &str) -> Option<&'a Value> {
359    let node = node_name(name, task);
360    let recorded = wf
361        .get("status")
362        .and_then(|s| s.get("nodes"))
363        .map(Value::members)
364        .unwrap_or(&[])
365        .iter()
366        .map(|(_, n)| n)
367        .find(|n| {
368            text(Some(n), "name") == Some(node.as_str())
369                && text(Some(n), "type") == Some("Pod")
370                && text(Some(n), "templateName") == Some(template_name(task).as_str())
371        })?;
372    kind_of(list, "Pod").find(|pod| {
373        let metadata = pod.get("metadata");
374        let annotations = metadata.and_then(|m| m.get("annotations"));
375        let owned = metadata
376            .and_then(|m| m.get("ownerReferences"))
377            .map(Value::items)
378            .unwrap_or(&[])
379            .iter()
380            .any(|o| {
381                text(Some(o), "kind") == Some("Workflow")
382                    && text(Some(o), "uid") == Some(uid)
383                    && text(Some(o), "name") == Some(name)
384                    && o.get("controller").is_some_and(Value::is_true)
385            });
386        // The node id is required, not optional: a pod that does not name its
387        // node cannot be bound to the Workflow's record of it.
388        let node_id = text(annotations, "workflows.argoproj.io/node-id");
389        owned
390            && text(annotations, "workflows.argoproj.io/node-name") == Some(node.as_str())
391            && node_id.is_some()
392            && node_id == text(Some(recorded), "id")
393    })
394}
395
396/// The Job-shaped end of a Workflow pod, from `main`'s termination status
397/// alone: exit 0 is `Complete`, any other exit is `Failed`, and a container
398/// that has not terminated is `Running`. Workflow and node phases are never
399/// read here: gate code can write what Argo's executor reports from.
400fn end_from_main(main: &State) -> JobEnd {
401    match main {
402        State::Terminated { exit: Some(0), .. } => JobEnd::Complete,
403        State::Terminated { reason, .. } => JobEnd::Failed(if reason.is_empty() {
404            "Error".to_string()
405        } else {
406            reason.clone()
407        }),
408        State::Absent | State::Waiting | State::Running => JobEnd::Running,
409    }
410}
411
412/// Why a pod that never ended `main` is no pass, as the pod says it.
413fn unfinished(facts: &PodFacts) -> String {
414    if let Some(w) = facts.fetch.failed() {
415        format!("fetch {w}")
416    } else if let Some(w) = facts.prepare.failed() {
417        format!("prepare {w}")
418    } else {
419        "the pod ended without a verdict from main".to_string()
420    }
421}
422
423/// Decide what the cluster's answer means for one record. Pure.
424fn resolve(record: Pending, list: &Value, now: u64) -> Resolution {
425    let mut notes: Vec<(String, String)> = Vec::new();
426    let wf = kind_of(list, "Workflow").find(|w| {
427        text(w.get("metadata"), "name") == Some(record.name.as_str())
428            && text(
429                w.get("metadata").and_then(|m| m.get("labels")),
430                RUN_LABEL_KEY,
431            ) == Some(record.label.as_str())
432    });
433    // The record ends here, its waiting gates failed, one note each.
434    let drop_all = |mut record: Pending, why: &str| {
435        let notes = record
436            .waiting()
437            .map(|g| (g.id.clone(), format!("detached {}: {why}", record.name)))
438            .collect();
439        for gate in record
440            .gates
441            .iter_mut()
442            .filter(|g| g.state == GateState::Waiting)
443        {
444            gate.state = GateState::Failed;
445        }
446        record.phase = RecordPhase::Gone;
447        Resolution {
448            record,
449            leaves: true,
450            passes: Vec::new(),
451            notes,
452        }
453    };
454    let Some(wf) = wf else {
455        return if record.uid.is_some() {
456            drop_all(
457                record,
458                "the Workflow is gone (its TTL passed, or it was deleted)",
459            )
460        } else if is_expired(&record, now) || now > record.submitted + INTENT_GRACE_SECS {
461            drop_all(record, "the Workflow never appeared")
462        } else {
463            // A create that may still land: the intent stays.
464            Resolution {
465                record,
466                leaves: false,
467                passes: Vec::new(),
468                notes,
469            }
470        };
471    };
472    if is_expired(&record, now) {
473        return drop_all(record, "older than the Workflow TTL");
474    }
475    let found_uid = text(wf.get("metadata"), "uid").map(str::to_string);
476    let uid = match (&record.uid, &found_uid) {
477        (Some(saved), Some(found)) if saved == found => saved.clone(),
478        (Some(_), _) => {
479            return drop_all(
480                record,
481                "another Workflow than the one submitted holds the name",
482            )
483        }
484        (None, Some(found)) => match check_workflow(wf, &record) {
485            Ok(()) => found.clone(),
486            Err(why) => {
487                return drop_all(record, &format!("not the Workflow submitted: {why}"));
488            }
489        },
490        (None, None) => return drop_all(record, "the Workflow has no UID"),
491    };
492    let phase = RecordPhase::parse(text(wf.get("status"), "phase").unwrap_or(""));
493    let mut passes: Vec<Pass> = Vec::new();
494    let mut gates = record.gates.clone();
495    for gate in gates.iter_mut().filter(|g| g.state == GateState::Waiting) {
496        let Some(pod) = pod_of(list, wf, &record.name, &uid, &gate.task) else {
497            if phase.finished() {
498                gate.state = GateState::Failed;
499                notes.push((
500                    gate.id.clone(),
501                    format!(
502                        "detached {}: no pod of {} was found ({})",
503                        record.name,
504                        gate.task,
505                        phase.as_str()
506                    ),
507                ));
508            }
509            continue;
510        };
511        if let Err(why) = check_pod(pod, gate, &record) {
512            gate.state = GateState::Failed;
513            notes.push((
514                gate.id.clone(),
515                format!(
516                    "detached {}: the pod is not the one submitted: {why}",
517                    record.name
518                ),
519            ));
520            continue;
521        }
522        let Some(facts) = parse_pod_object(pod, "main") else {
523            if phase.finished() {
524                gate.state = GateState::Failed;
525                notes.push((
526                    gate.id.clone(),
527                    format!("detached {}: the pod's status cannot be read", record.name),
528                ));
529            }
530            continue;
531        };
532        let end = end_from_main(&facts.gate);
533        if end == JobEnd::Running {
534            if phase.finished() {
535                gate.state = GateState::Failed;
536                notes.push((
537                    gate.id.clone(),
538                    format!("detached {}: {}", record.name, unfinished(&facts)),
539                ));
540            }
541            continue;
542        }
543        match judge(&end, &facts, &record.tree, gate.prepare.as_deref()) {
544            Ok(image_id) => {
545                gate.state = GateState::Passed;
546                passes.push(Pass {
547                    gate: gate.id.clone(),
548                    tree: record.tree.clone(),
549                    token: gate.token.clone(),
550                    provenance: format!(
551                        "platform={PLATFORM} image={image_id} job={uid} name={} bundle=0",
552                        node_name(&record.name, &gate.task)
553                    ),
554                });
555            }
556            Err(fallback) => {
557                gate.state = GateState::Failed;
558                notes.push((
559                    gate.id.clone(),
560                    format!("detached {}: {}", record.name, fallback),
561                ));
562            }
563        }
564    }
565    let settled = gates.iter().all(|g| g.state != GateState::Waiting);
566    Resolution {
567        leaves: settled || phase.finished(),
568        record: Pending {
569            uid: Some(uid),
570            phase,
571            gates,
572            ..record
573        },
574        passes,
575        notes,
576    }
577}
578
579/// `amont cluster collect`: exit 0 when it asked the cluster (or had nothing
580/// to ask, or another collect is at it), 1 when it learned nothing or could
581/// not keep what it learned, 2 on usage.
582pub fn collect_command(args: &[std::ffi::OsString]) -> i32 {
583    if args.iter().any(|a| a == "--help" || a == "-h") {
584        println!("usage: {} cluster collect", crate::names::BIN);
585        return 0;
586    }
587    match args.first().and_then(|a| a.to_str()) {
588        Some("collect") if args.len() == 1 => {
589            let done = collect();
590            match &done.trouble {
591                Some(Trouble::Busy) => {
592                    eprintln!("{}; nothing was asked of the cluster", Trouble::Busy);
593                    0
594                }
595                Some(trouble) => {
596                    eprintln!("{trouble}");
597                    1
598                }
599                None => {
600                    eprintln!(
601                        "collected {} cluster pass{}; {} Workflow{} still pending",
602                        done.passes,
603                        if done.passes == 1 { "" } else { "es" },
604                        done.pending,
605                        if done.pending == 1 { "" } else { "s" },
606                    );
607                    0
608                }
609            }
610        }
611        _ => {
612            eprintln!("usage: {} cluster collect", crate::names::BIN);
613            2
614        }
615    }
616}
617
618/// `rehearse --status`: one line per pending Workflow, its phase as the last
619/// collect saw it and the gates collected so far.
620pub(crate) fn status_lines() -> Vec<String> {
621    let Some(store) = Store::here() else {
622        return Vec::new();
623    };
624    match store.read() {
625        Ok(records) => records.iter().map(describe).collect(),
626        Err(why) => {
627            eprintln!("cluster run records cannot be read: {why}");
628            Vec::new()
629        }
630    }
631}
632
633/// The Workflows a collect finished with, for the person who asked.
634pub(crate) fn settled_lines(settled: &[Settled]) -> Vec<String> {
635    settled
636        .iter()
637        .map(|run| {
638            let mut parts: Vec<String> = Vec::new();
639            if !run.passed.is_empty() {
640                parts.push(format!("collected: {}", run.passed.join(" ")));
641            }
642            if !run.failed.is_empty() {
643                parts.push(format!(
644                    "did not pass: {} — see cluster.log; the gate runs at the push",
645                    run.failed.join(" ")
646                ));
647            }
648            format!(
649                "cluster run {} {}: {}",
650                run.name,
651                run.phase.plain(),
652                parts.join("; ")
653            )
654        })
655        .collect()
656}
657
658fn describe(record: &Pending) -> String {
659    let named = |label: &str, state: GateState| -> Option<String> {
660        let ids: Vec<&str> = record
661            .gates
662            .iter()
663            .filter(|g| g.state == state)
664            .map(|g| g.id.as_str())
665            .collect();
666        (!ids.is_empty()).then(|| format!("{label}: {}", ids.join(" ")))
667    };
668    let fields: Vec<String> = [
669        named("collected", GateState::Passed),
670        named("did not pass", GateState::Failed),
671        named("waiting", GateState::Waiting),
672    ]
673    .into_iter()
674    .flatten()
675    .collect();
676    let follow = if record.phase.finished() {
677        String::new()
678    } else {
679        format!(
680            " (follow: kubectl -n {} get wf {})",
681            record.namespace, record.name
682        )
683    };
684    format!(
685        "cluster run {}: {}{}{follow}",
686        record.name,
687        record.phase.plain(),
688        if fields.is_empty() {
689            String::new()
690        } else {
691            format!(" — {}", fields.join("; "))
692        }
693    )
694}
695
696/// The command that does by hand what `--stop` does for one Workflow.
697fn terminate_command(record: &Pending) -> String {
698    format!(
699        "kubectl --kubeconfig {} -n {} patch workflow {} --type merge -p '{{\"spec\":{{\"shutdown\":\"Terminate\"}}}}'",
700        shell_quote(&record.kubeconfig.to_string_lossy()),
701        record.namespace,
702        record.name
703    )
704}
705
706/// `text` as one word for a POSIX shell.
707fn shell_quote(text: &str) -> String {
708    format!("'{}'", text.replace('\'', "'\\''"))
709}
710
711/// What `rehearse --stop` did to the pending Workflows.
712#[derive(Debug, Clone, PartialEq, Eq, Default)]
713pub(crate) struct Stopped {
714    /// One line per Workflow asked to terminate.
715    pub done: Vec<String>,
716    /// One line per Workflow that was not, with the command to do it by hand.
717    pub failed: Vec<String>,
718}
719
720/// `rehearse --stop`: ask the cluster to terminate every pending Workflow,
721/// each call and all of them bounded. Once the overall deadline is gone the
722/// rest are reported as not attempted.
723pub(crate) fn stop_pending() -> Stopped {
724    let mut report = Stopped::default();
725    let Some(store) = Store::here() else {
726        return report;
727    };
728    let records = match store.read() {
729        Ok(records) => records,
730        Err(why) => {
731            report
732                .failed
733                .push(format!("cluster run records cannot be read: {why}"));
734            return report;
735        }
736    };
737    let until = std::time::Instant::now() + std::time::Duration::from_secs(STOP_SECS);
738    for record in &records {
739        let left = until.saturating_duration_since(std::time::Instant::now());
740        if left.is_zero() {
741            report.failed.push(format!(
742                "cluster run {} was not attempted: the stop deadline passed — {}",
743                record.name,
744                terminate_command(record)
745            ));
746            continue;
747        }
748        let kube = Kube {
749            kubeconfig: record.kubeconfig.clone(),
750            namespace: record.namespace.clone(),
751        };
752        let patched = kube.bounded(
753            &[
754                "patch",
755                "workflow",
756                &record.name,
757                "--type",
758                "merge",
759                "-p",
760                "{\"spec\":{\"shutdown\":\"Terminate\"}}",
761            ],
762            left.as_secs().clamp(1, PATCH_SECS),
763        );
764        match patched {
765            Ok(()) => report
766                .done
767                .push(format!("terminating cluster run {}", record.name)),
768            Err(why) => report.failed.push(format!(
769                "could not terminate cluster run {}: {why} — {}",
770                record.name,
771                terminate_command(record)
772            )),
773        }
774    }
775    report
776}
777
778#[cfg(test)]
779mod tests {
780    use super::super::pending::tests::sample;
781    use super::*;
782
783    fn fixture(name: &str) -> String {
784        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
785            .join("../greengate/tests/it/fixtures/argo");
786        std::fs::read_to_string(dir.join(name)).expect("fixture")
787    }
788
789    /// `text` without the whitespace outside strings, so a replacement does
790    /// not depend on how the fixture was indented.
791    fn compact(text: &str) -> String {
792        let (mut out, mut in_string, mut escaped) = (String::new(), false, false);
793        for c in text.chars() {
794            if in_string {
795                out.push(c);
796                match (escaped, c) {
797                    (true, _) => escaped = false,
798                    (false, '\\') => escaped = true,
799                    (false, '"') => in_string = false,
800                    (false, _) => {}
801                }
802            } else if c == '"' {
803                in_string = true;
804                out.push(c);
805            } else if !c.is_whitespace() {
806                out.push(c);
807            }
808        }
809        out
810    }
811
812    /// What the cluster answers for `record`: the first live run's pod, made
813    /// the pod of task `g0` of the Workflow, and a Workflow in `phase` whose
814    /// node for it is in `node_phase`. `tweak` edits the pod's compact text.
815    fn list_for(
816        record: &Pending,
817        phase: &str,
818        node_phase: &str,
819        tweak: impl Fn(String) -> String,
820    ) -> Value {
821        let node = node_name(&record.name, "g0");
822        let pod = compact(&fixture("pod-succeeded.json"))
823            .replace(
824                "\"workflows.argoproj.io/node-name\":\"amont-handrun-pqtbl\"",
825                &format!("\"workflows.argoproj.io/node-name\":\"{node}\""),
826            )
827            .replace(
828                "\"workflows.argoproj.io/node-id\":\"amont-handrun-pqtbl\"",
829                "\"workflows.argoproj.io/node-id\":\"node-g0\"",
830            )
831            .replace("amont-handrun-pqtbl", &record.name)
832            .replace("b8eb52b7-8ede-4c1f-bd94-9ada529eec97", "uid-1")
833            .replace("handrun-2", &record.label);
834        let wf = format!(
835            "{{\"kind\":\"Workflow\",\"metadata\":{{\"name\":\"{}\",\"uid\":\"uid-1\",\
836             \"labels\":{{\"amont.run\":\"{}\"}}}},\"status\":{{\"phase\":\"{phase}\",\
837             \"nodes\":{{\"node-g0\":{{\"id\":\"node-g0\",\"name\":\"{node}\",\"type\":\"Pod\",\
838             \"templateName\":\"gate-g0\",\"phase\":\"{node_phase}\"}}}}}}}}",
839            record.name, record.label
840        );
841        let list = format!("{{\"kind\":\"List\",\"items\":[{wf},{}]}}", tweak(pod));
842        crate::json_read::parse(&list).expect("list json")
843    }
844
845    #[test]
846    fn a_workflow_phase_is_only_ever_finished_or_not() {
847        for (phase, finished) in [
848            ("Succeeded", true),
849            ("Failed", true),
850            ("Error", true),
851            ("Running", false),
852            ("Pending", false),
853            ("", false),
854        ] {
855            assert_eq!(RecordPhase::parse(phase).finished(), finished, "{phase}");
856        }
857    }
858
859    /// `main` alone decides: exit 0 is the only pass, whatever else the pod
860    /// or the Workflow says.
861    #[test]
862    fn the_end_of_a_pod_comes_from_main_alone() {
863        let ended = |exit, reason: &str| State::Terminated {
864            exit: Some(exit),
865            reason: reason.into(),
866            message: String::new(),
867        };
868        assert_eq!(end_from_main(&ended(0, "Completed")), JobEnd::Complete);
869        assert_eq!(
870            end_from_main(&ended(1, "Error")),
871            JobEnd::Failed("Error".into())
872        );
873        assert_eq!(
874            end_from_main(&ended(137, "OOMKilled")),
875            JobEnd::Failed("OOMKilled".into())
876        );
877        assert_eq!(end_from_main(&State::Running), JobEnd::Running);
878        assert_eq!(end_from_main(&State::Waiting), JobEnd::Running);
879        assert_eq!(end_from_main(&State::Absent), JobEnd::Running);
880    }
881
882    fn record_of_the_fixture() -> Pending {
883        let mut record = sample("amont-rh-test");
884        record.uid = Some("uid-1".into());
885        record.label = "label-1".into();
886        record.tree = "13b5ee2d54389399fa2738f084a1b653b5844028".into();
887        record.source.oid = "7e04624939f8c93f774d570276af8643c61f0320".into();
888        record.gates[0].argv = vec!["python3".into(), "scripts/check-module-cycles.py".into()];
889        record.gates[0].prepare = None;
890        record.gates[0].digest =
891            "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c".into();
892        record
893    }
894
895    fn collected(record: Pending, list: &Value) -> Resolution {
896        resolve(record, list, 1_700_000_100)
897    }
898
899    /// The first live run, collected: a pass written under the FROZEN token,
900    /// and the finished Workflow leaves the file.
901    #[test]
902    fn the_live_fixture_is_a_pass() {
903        let record = record_of_the_fixture();
904        let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
905        let done = collected(record, &list);
906        assert!(done.notes.is_empty(), "{:?}", done.notes);
907        assert_eq!(done.passes.len(), 1, "{done:?}");
908        assert_eq!(
909            done.passes[0].token, "pre-push-lint@abc",
910            "the frozen token"
911        );
912        assert!(done.passes[0].provenance.contains("platform=x86_64-linux"));
913        assert!(done.leaves, "a finished Workflow leaves the file");
914    }
915
916    /// The node and the Workflow say Succeeded; `main` exited 1. Phases only
917    /// say the pod finished.
918    #[test]
919    fn a_succeeded_node_with_a_failed_main_is_no_pass() {
920        let record = record_of_the_fixture();
921        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
922            p.replacen(
923                "\"exitCode\":0,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
924                "\"exitCode\":1,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
925                1,
926            )
927        });
928        let done = collected(record, &list);
929        assert!(done.passes.is_empty(), "{done:?}");
930        assert_eq!(done.notes.len(), 1, "{done:?}");
931        assert!(done.notes[0].1.contains("exit 1"), "{:?}", done.notes);
932    }
933
934    #[test]
935    fn a_pod_of_another_workflow_uid_is_not_this_ones() {
936        let record = record_of_the_fixture();
937        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
938            p.replace("\"uid\":\"uid-1\"", "\"uid\":\"uid-other\"")
939        });
940        let done = collected(record, &list);
941        assert!(done.passes.is_empty(), "{done:?}");
942    }
943
944    #[test]
945    fn a_pod_with_another_image_or_command_is_not_the_submission() {
946        for tweak in [
947            |p: String| {
948                p.replace(
949                    "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c",
950                    &format!("sha256:{}", "0".repeat(64)),
951                )
952            },
953            |p: String| p.replace("scripts/check-module-cycles.py", "scripts/other.py"),
954            |p: String| {
955                p.replace(
956                    "tree 13b5ee2d54389399fa2738f084a1b653b5844028",
957                    "tree 0000000000000000000000000000000000000000",
958                )
959            },
960        ] {
961            let record = record_of_the_fixture();
962            let list = list_for(&record, "Succeeded", "Succeeded", tweak);
963            let done = collected(record, &list);
964            assert!(done.passes.is_empty(), "{done:?}");
965            assert_eq!(done.notes.len(), 1, "{done:?}");
966        }
967    }
968
969    #[test]
970    fn a_running_workflow_keeps_its_waiting_gates() {
971        let record = record_of_the_fixture();
972        let list = list_for(&record, "Running", "Running", |p| {
973            // `main` has not terminated: the same state, reopened as running
974            p.replace(
975                "\"terminated\":{\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
976                "\"running\":{\"startedAt\":\"t\",\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
977            )
978        });
979        let done = collected(record, &list);
980        assert!(done.passes.is_empty(), "{done:?}");
981        assert!(!done.leaves);
982        assert_eq!(done.record.gates[0].state, GateState::Waiting);
983        assert_eq!(done.record.phase, RecordPhase::Running);
984    }
985
986    #[test]
987    fn a_workflow_gone_after_its_ttl_drops_the_record_with_one_note() {
988        let record = record_of_the_fixture();
989        let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
990        let done = collected(record, &empty);
991        assert!(done.leaves);
992        assert_eq!(done.record.phase, RecordPhase::Gone);
993        assert_eq!(done.record.phase.plain(), "gone (TTL passed or deleted)");
994        assert_eq!(done.notes.len(), 1, "{done:?}");
995    }
996
997    /// A create whose answer was lost: no Workflow yet, so the intent stays
998    /// for a while, and goes once the grace has passed.
999    #[test]
1000    fn an_intent_with_no_workflow_waits_then_goes() {
1001        let mut record = record_of_the_fixture();
1002        record.uid = None;
1003        let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
1004        let young = resolve(record.clone(), &empty, record.submitted + 60);
1005        assert!(!young.leaves);
1006        let old = resolve(
1007            record.clone(),
1008            &empty,
1009            record.submitted + INTENT_GRACE_SECS + 1,
1010        );
1011        assert!(old.leaves);
1012        assert_eq!(old.notes.len(), 1);
1013    }
1014
1015    /// The Workflow finished and passed, but the token cannot be written: the
1016    /// record stays, its gate waiting, and the next collect writes the token.
1017    #[test]
1018    fn a_pass_whose_token_cannot_be_written_keeps_the_record() {
1019        let record = record_of_the_fixture();
1020        let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
1021        let refuse = |_: &Pass| Err(Fallback::NotProved("git refused".into()));
1022        let first = settle_with(resolve(record.clone(), &list, 1_700_000_100), refuse);
1023        assert_eq!(first.written, 0);
1024        assert!(
1025            first.settled.is_none(),
1026            "the run has not ended for the person"
1027        );
1028        let kept = first.record.expect("the record survives");
1029        assert_eq!(kept.gates[0].state, GateState::Waiting);
1030
1031        let mut tokens = Vec::new();
1032        let second = settle_with(resolve(kept, &list, 1_700_000_200), |pass| {
1033            tokens.push(pass.token.clone());
1034            Ok(())
1035        });
1036        assert_eq!(second.written, 1);
1037        assert_eq!(tokens, ["pre-push-lint@abc"]);
1038        assert!(second.record.is_none());
1039        let ended = second.settled.expect("now it ends");
1040        assert_eq!(ended.passed, ["pre-push-lint"]);
1041    }
1042
1043    /// A finished Workflow whose pod status cannot be read fails the gate.
1044    #[test]
1045    fn an_unreadable_pod_status_on_a_finished_workflow_fails_the_gate() {
1046        let record = record_of_the_fixture();
1047        let list = list_for(&record, "Failed", "Failed", |p| {
1048            p.replace(
1049                "\"name\":\"amont-rh-test\",\"namespace\"",
1050                "\"namex\":\"amont-rh-test\",\"namespace\"",
1051            )
1052        });
1053        let done = collected(record, &list);
1054        assert!(done.passes.is_empty());
1055        assert_eq!(done.notes.len(), 1, "{done:?}");
1056        assert!(
1057            done.notes[0].1.contains("status cannot be read"),
1058            "{done:?}"
1059        );
1060    }
1061
1062    /// A pod that does not name its node cannot be bound to the Workflow's.
1063    #[test]
1064    fn a_pod_without_a_node_id_is_not_bound() {
1065        let record = record_of_the_fixture();
1066        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1067            p.replace(
1068                "workflows.argoproj.io/node-id",
1069                "workflows.argoproj.io/node-idx",
1070            )
1071        });
1072        let done = collected(record, &list);
1073        assert!(done.passes.is_empty(), "{done:?}");
1074    }
1075
1076    #[test]
1077    fn a_record_older_than_the_ttl_expires_whatever_the_cluster_says() {
1078        let record = record_of_the_fixture();
1079        assert!(!is_expired(&record, record.submitted + TTL_SECS));
1080        assert!(is_expired(
1081            &record,
1082            record.submitted + TTL_SECS + EXPIRY_SLACK_SECS + 1
1083        ));
1084    }
1085}