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 'greengate.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/// Whether the pending file at `path` still lists a run that has not
221/// outlived its Workflow by [`EXPIRY_SLACK_SECS`]: what `collect` would keep.
222/// `Ok(false)` for no file; `Err` for a file this version cannot read.
223pub(crate) fn lists_live(path: &std::path::Path, now: u64) -> Result<bool, String> {
224    let text = match std::fs::read_to_string(path) {
225        Ok(text) => text,
226        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
227        Err(e) => return Err(e.to_string()),
228    };
229    Ok(super::pending::parse_file(&text)?
230        .iter()
231        .any(|record| !is_expired(record, now)))
232}
233
234/// The records grouped by the cluster they live on: one call each.
235fn by_cluster(records: Vec<Pending>) -> Vec<Vec<Pending>> {
236    let mut groups: Vec<Vec<Pending>> = Vec::new();
237    for record in records {
238        match groups
239            .iter_mut()
240            .find(|g| g[0].kubeconfig == record.kubeconfig && g[0].namespace == record.namespace)
241        {
242            Some(group) => group.push(record),
243            None => groups.push(vec![record]),
244        }
245    }
246    groups
247}
248
249/// The one batched call: every Workflow and pod carrying one of the records'
250/// run labels.
251fn fetch(kube: &Kube, records: &[Pending]) -> Result<Value, String> {
252    let labels: Vec<&str> = records.iter().map(|r| r.label.as_str()).collect();
253    let selector = format!("{RUN_LABEL_KEY} in ({})", labels.join(","));
254    let mut cmd = kube.command(
255        "--request-timeout=1s",
256        &["get", "workflows,pods", "-l", &selector, "-o", "json"],
257    );
258    match capture(&mut cmd, COLLECT_SECS) {
259        Call::Ok(json) => crate::json_read::parse(&json)
260            .ok_or_else(|| "kubectl printed something that is not JSON".to_string()),
261        Call::Refused(e) | Call::NotStarted(e) | Call::TimedOut(e) => Err(last_line(&e)),
262    }
263}
264
265/// What settling a resolution left.
266struct Settlement {
267    /// The record if it stays in the file.
268    record: Option<Pending>,
269    /// Tokens written.
270    written: usize,
271    /// The record's end, when it left the file.
272    settled: Option<Settled>,
273}
274
275/// [`settle_with`], writing tokens to the cluster note.
276fn settle(resolution: Resolution) -> Settlement {
277    settle_with(resolution, |pass| {
278        record_token(&pass.tree, &pass.token, &pass.provenance)
279    })
280}
281
282/// Write the passes of a resolution through `write` and log its notes. A pass
283/// whose token was not written returns its gate to waiting and keeps the
284/// record in the file, finished Workflow or not, so that the next collect
285/// tries again.
286fn settle_with(
287    resolution: Resolution,
288    mut write: impl FnMut(&Pass) -> Result<(), Fallback>,
289) -> Settlement {
290    let Resolution {
291        mut record,
292        leaves,
293        passes,
294        notes,
295    } = resolution;
296    for (gate, why) in &notes {
297        log_line(gate, why);
298    }
299    let mut written = 0;
300    let mut unwritten = 0;
301    for pass in &passes {
302        match write(pass) {
303            Ok(()) => {
304                written += 1;
305                // stderr: `amont stamps --json` collects first, and its stdout
306                // is the JSON object alone.
307                eprintln!(
308                    "collected the cluster pass of {} for tree {}",
309                    crate::ui::sanitize(&pass.gate),
310                    short(&pass.tree)
311                );
312            }
313            Err(why) => {
314                log_line(
315                    &pass.gate,
316                    &format!("detached: the pass was not recorded: {why}"),
317                );
318                unwritten += 1;
319                for gate in record.gates.iter_mut().filter(|g| g.id == pass.gate) {
320                    gate.state = GateState::Waiting;
321                }
322            }
323        }
324    }
325    if !leaves || unwritten > 0 {
326        return Settlement {
327            record: Some(record),
328            written,
329            settled: None,
330        };
331    }
332    let ids = |state: GateState| -> Vec<String> {
333        record
334            .gates
335            .iter()
336            .filter(|g| g.state == state)
337            .map(|g| g.id.clone())
338            .collect()
339    };
340    let settled = Settled {
341        name: record.name.clone(),
342        phase: record.phase,
343        passed: ids(GateState::Passed),
344        failed: ids(GateState::Failed),
345    };
346    Settlement {
347        record: None,
348        written,
349        settled: Some(settled),
350    }
351}
352
353fn short(oid: &str) -> &str {
354    oid.get(..8).unwrap_or(oid)
355}
356
357fn text<'a>(v: Option<&'a Value>, key: &str) -> Option<&'a str> {
358    v?.get(key).and_then(Value::as_str)
359}
360
361fn kind_of<'a>(list: &'a Value, kind: &'a str) -> impl Iterator<Item = &'a Value> {
362    list.get("items")
363        .map(Value::items)
364        .unwrap_or(&[])
365        .iter()
366        .filter(move |i| text(Some(i), "kind") == Some(kind))
367}
368
369/// The pod of the Workflow `uid` that ran `node`: named so by Argo's
370/// annotation, owned by that Workflow, and a Pod node of the Workflow's own
371/// status of the template the gate was submitted under.
372fn pod_of<'a>(list: &'a Value, wf: &Value, name: &str, uid: &str, task: &str) -> Option<&'a Value> {
373    let node = node_name(name, task);
374    let recorded = wf
375        .get("status")
376        .and_then(|s| s.get("nodes"))
377        .map(Value::members)
378        .unwrap_or(&[])
379        .iter()
380        .map(|(_, n)| n)
381        .find(|n| {
382            text(Some(n), "name") == Some(node.as_str())
383                && text(Some(n), "type") == Some("Pod")
384                && text(Some(n), "templateName") == Some(template_name(task).as_str())
385        })?;
386    kind_of(list, "Pod").find(|pod| {
387        let metadata = pod.get("metadata");
388        let annotations = metadata.and_then(|m| m.get("annotations"));
389        let owned = metadata
390            .and_then(|m| m.get("ownerReferences"))
391            .map(Value::items)
392            .unwrap_or(&[])
393            .iter()
394            .any(|o| {
395                text(Some(o), "kind") == Some("Workflow")
396                    && text(Some(o), "uid") == Some(uid)
397                    && text(Some(o), "name") == Some(name)
398                    && o.get("controller").is_some_and(Value::is_true)
399            });
400        // The node id is required, not optional: a pod that does not name its
401        // node cannot be bound to the Workflow's record of it.
402        let node_id = text(annotations, "workflows.argoproj.io/node-id");
403        owned
404            && text(annotations, "workflows.argoproj.io/node-name") == Some(node.as_str())
405            && node_id.is_some()
406            && node_id == text(Some(recorded), "id")
407    })
408}
409
410/// The Job-shaped end of a Workflow pod, from `main`'s termination status
411/// alone: exit 0 is `Complete`, any other exit is `Failed`, and a container
412/// that has not terminated is `Running`. Workflow and node phases are never
413/// read here: gate code can write what Argo's executor reports from.
414fn end_from_main(main: &State) -> JobEnd {
415    match main {
416        State::Terminated { exit: Some(0), .. } => JobEnd::Complete,
417        State::Terminated { reason, .. } => JobEnd::Failed(if reason.is_empty() {
418            "Error".to_string()
419        } else {
420            reason.clone()
421        }),
422        State::Absent | State::Waiting | State::Running => JobEnd::Running,
423    }
424}
425
426/// Why a pod that never ended `main` is no pass, as the pod says it.
427fn unfinished(facts: &PodFacts) -> String {
428    if let Some(w) = facts.fetch.failed() {
429        format!("fetch {w}")
430    } else if let Some(w) = facts.prepare.failed() {
431        format!("prepare {w}")
432    } else {
433        "the pod ended without a verdict from main".to_string()
434    }
435}
436
437/// Decide what the cluster's answer means for one record. Pure.
438fn resolve(record: Pending, list: &Value, now: u64) -> Resolution {
439    let mut notes: Vec<(String, String)> = Vec::new();
440    let wf = kind_of(list, "Workflow").find(|w| {
441        text(w.get("metadata"), "name") == Some(record.name.as_str())
442            && text(
443                w.get("metadata").and_then(|m| m.get("labels")),
444                RUN_LABEL_KEY,
445            ) == Some(record.label.as_str())
446    });
447    // The record ends here, its waiting gates failed, one note each.
448    let drop_all = |mut record: Pending, why: &str| {
449        let notes = record
450            .waiting()
451            .map(|g| (g.id.clone(), format!("detached {}: {why}", record.name)))
452            .collect();
453        for gate in record
454            .gates
455            .iter_mut()
456            .filter(|g| g.state == GateState::Waiting)
457        {
458            gate.state = GateState::Failed;
459        }
460        record.phase = RecordPhase::Gone;
461        Resolution {
462            record,
463            leaves: true,
464            passes: Vec::new(),
465            notes,
466        }
467    };
468    let Some(wf) = wf else {
469        return if record.uid.is_some() {
470            drop_all(
471                record,
472                "the Workflow is gone (its TTL passed, or it was deleted)",
473            )
474        } else if is_expired(&record, now) || now > record.submitted + INTENT_GRACE_SECS {
475            drop_all(record, "the Workflow never appeared")
476        } else {
477            // A create that may still land: the intent stays.
478            Resolution {
479                record,
480                leaves: false,
481                passes: Vec::new(),
482                notes,
483            }
484        };
485    };
486    if is_expired(&record, now) {
487        return drop_all(record, "older than the Workflow TTL");
488    }
489    let found_uid = text(wf.get("metadata"), "uid").map(str::to_string);
490    let uid = match (&record.uid, &found_uid) {
491        (Some(saved), Some(found)) if saved == found => saved.clone(),
492        (Some(_), _) => {
493            return drop_all(
494                record,
495                "another Workflow than the one submitted holds the name",
496            )
497        }
498        (None, Some(found)) => match check_workflow(wf, &record) {
499            Ok(()) => found.clone(),
500            Err(why) => {
501                return drop_all(record, &format!("not the Workflow submitted: {why}"));
502            }
503        },
504        (None, None) => return drop_all(record, "the Workflow has no UID"),
505    };
506    let phase = RecordPhase::parse(text(wf.get("status"), "phase").unwrap_or(""));
507    let mut passes: Vec<Pass> = Vec::new();
508    let mut gates = record.gates.clone();
509    for gate in gates.iter_mut().filter(|g| g.state == GateState::Waiting) {
510        let Some(pod) = pod_of(list, wf, &record.name, &uid, &gate.task) else {
511            if phase.finished() {
512                gate.state = GateState::Failed;
513                notes.push((
514                    gate.id.clone(),
515                    format!(
516                        "detached {}: no pod of {} was found ({})",
517                        record.name,
518                        gate.task,
519                        phase.as_str()
520                    ),
521                ));
522            }
523            continue;
524        };
525        if let Err(why) = check_pod(pod, gate, &record) {
526            gate.state = GateState::Failed;
527            notes.push((
528                gate.id.clone(),
529                format!(
530                    "detached {}: the pod is not the one submitted: {why}",
531                    record.name
532                ),
533            ));
534            continue;
535        }
536        let Some(facts) = parse_pod_object(pod, "main") else {
537            if phase.finished() {
538                gate.state = GateState::Failed;
539                notes.push((
540                    gate.id.clone(),
541                    format!("detached {}: the pod's status cannot be read", record.name),
542                ));
543            }
544            continue;
545        };
546        let end = end_from_main(&facts.gate);
547        if end == JobEnd::Running {
548            if phase.finished() {
549                gate.state = GateState::Failed;
550                notes.push((
551                    gate.id.clone(),
552                    format!("detached {}: {}", record.name, unfinished(&facts)),
553                ));
554            }
555            continue;
556        }
557        match judge(&end, &facts, &record.tree, gate.prepare.as_deref()) {
558            Ok(image_id) => {
559                gate.state = GateState::Passed;
560                passes.push(Pass {
561                    gate: gate.id.clone(),
562                    tree: record.tree.clone(),
563                    token: gate.token.clone(),
564                    provenance: format!(
565                        "platform={PLATFORM} image={image_id} job={uid} name={} bundle=0",
566                        node_name(&record.name, &gate.task)
567                    ),
568                });
569            }
570            Err(fallback) => {
571                gate.state = GateState::Failed;
572                notes.push((
573                    gate.id.clone(),
574                    format!("detached {}: {}", record.name, fallback),
575                ));
576            }
577        }
578    }
579    let settled = gates.iter().all(|g| g.state != GateState::Waiting);
580    Resolution {
581        leaves: settled || phase.finished(),
582        record: Pending {
583            uid: Some(uid),
584            phase,
585            gates,
586            ..record
587        },
588        passes,
589        notes,
590    }
591}
592
593/// `amont cluster collect`: exit 0 when it asked the cluster (or had nothing
594/// to ask, or another collect is at it), 1 when it learned nothing or could
595/// not keep what it learned, 2 on usage.
596pub fn collect_command(args: &[std::ffi::OsString]) -> i32 {
597    if args.iter().any(|a| a == "--help" || a == "-h") {
598        println!("usage: {} cluster collect", crate::names::BIN);
599        return 0;
600    }
601    match args.first().and_then(|a| a.to_str()) {
602        Some("collect") if args.len() == 1 => {
603            let done = collect();
604            match &done.trouble {
605                Some(Trouble::Busy) => {
606                    eprintln!("{}; nothing was asked of the cluster", Trouble::Busy);
607                    0
608                }
609                Some(trouble) => {
610                    eprintln!("{trouble}");
611                    1
612                }
613                None => {
614                    eprintln!(
615                        "collected {} cluster pass{}; {} Workflow{} still pending",
616                        done.passes,
617                        if done.passes == 1 { "" } else { "es" },
618                        done.pending,
619                        if done.pending == 1 { "" } else { "s" },
620                    );
621                    0
622                }
623            }
624        }
625        _ => {
626            eprintln!("usage: {} cluster collect", crate::names::BIN);
627            2
628        }
629    }
630}
631
632/// `rehearse --status`: one line per pending Workflow, its phase as the last
633/// collect saw it and the gates collected so far.
634pub(crate) fn status_lines() -> Vec<String> {
635    let Some(store) = Store::here() else {
636        return Vec::new();
637    };
638    match store.read() {
639        Ok(records) => records.iter().map(describe).collect(),
640        Err(why) => {
641            eprintln!("cluster run records cannot be read: {why}");
642            Vec::new()
643        }
644    }
645}
646
647/// The Workflows a collect finished with, for the person who asked.
648pub(crate) fn settled_lines(settled: &[Settled]) -> Vec<String> {
649    settled
650        .iter()
651        .map(|run| {
652            let mut parts: Vec<String> = Vec::new();
653            if !run.passed.is_empty() {
654                parts.push(format!("collected: {}", run.passed.join(" ")));
655            }
656            if !run.failed.is_empty() {
657                parts.push(format!(
658                    "did not pass: {} — see cluster.log; the gate runs at the push",
659                    run.failed.join(" ")
660                ));
661            }
662            format!(
663                "cluster run {} {}: {}",
664                run.name,
665                run.phase.plain(),
666                parts.join("; ")
667            )
668        })
669        .collect()
670}
671
672fn describe(record: &Pending) -> String {
673    let named = |label: &str, state: GateState| -> Option<String> {
674        let ids: Vec<&str> = record
675            .gates
676            .iter()
677            .filter(|g| g.state == state)
678            .map(|g| g.id.as_str())
679            .collect();
680        (!ids.is_empty()).then(|| format!("{label}: {}", ids.join(" ")))
681    };
682    let fields: Vec<String> = [
683        named("collected", GateState::Passed),
684        named("did not pass", GateState::Failed),
685        named("waiting", GateState::Waiting),
686    ]
687    .into_iter()
688    .flatten()
689    .collect();
690    let follow = if record.phase.finished() {
691        String::new()
692    } else {
693        format!(
694            " (follow: kubectl -n {} get wf {})",
695            record.namespace, record.name
696        )
697    };
698    format!(
699        "cluster run {}: {}{}{follow}",
700        record.name,
701        record.phase.plain(),
702        if fields.is_empty() {
703            String::new()
704        } else {
705            format!(" — {}", fields.join("; "))
706        }
707    )
708}
709
710/// The command that does by hand what `--stop` does for one Workflow.
711fn terminate_command(record: &Pending) -> String {
712    format!(
713        "kubectl --kubeconfig {} -n {} patch workflow {} --type merge -p '{{\"spec\":{{\"shutdown\":\"Terminate\"}}}}'",
714        shell_quote(&record.kubeconfig.to_string_lossy()),
715        record.namespace,
716        record.name
717    )
718}
719
720/// `text` as one word for a POSIX shell.
721fn shell_quote(text: &str) -> String {
722    format!("'{}'", text.replace('\'', "'\\''"))
723}
724
725/// What `rehearse --stop` did to the pending Workflows.
726#[derive(Debug, Clone, PartialEq, Eq, Default)]
727pub(crate) struct Stopped {
728    /// One line per Workflow asked to terminate.
729    pub done: Vec<String>,
730    /// One line per Workflow that was not, with the command to do it by hand.
731    pub failed: Vec<String>,
732}
733
734/// `rehearse --stop`: ask the cluster to terminate every pending Workflow,
735/// each call and all of them bounded. Once the overall deadline is gone the
736/// rest are reported as not attempted.
737pub(crate) fn stop_pending() -> Stopped {
738    let mut report = Stopped::default();
739    let Some(store) = Store::here() else {
740        return report;
741    };
742    let records = match store.read() {
743        Ok(records) => records,
744        Err(why) => {
745            report
746                .failed
747                .push(format!("cluster run records cannot be read: {why}"));
748            return report;
749        }
750    };
751    let until = std::time::Instant::now() + std::time::Duration::from_secs(STOP_SECS);
752    for record in &records {
753        let left = until.saturating_duration_since(std::time::Instant::now());
754        if left.is_zero() {
755            report.failed.push(format!(
756                "cluster run {} was not attempted: the stop deadline passed — {}",
757                record.name,
758                terminate_command(record)
759            ));
760            continue;
761        }
762        let kube = Kube {
763            kubeconfig: record.kubeconfig.clone(),
764            namespace: record.namespace.clone(),
765        };
766        let patched = kube.bounded(
767            &[
768                "patch",
769                "workflow",
770                &record.name,
771                "--type",
772                "merge",
773                "-p",
774                "{\"spec\":{\"shutdown\":\"Terminate\"}}",
775            ],
776            left.as_secs().clamp(1, PATCH_SECS),
777        );
778        match patched {
779            Ok(()) => report
780                .done
781                .push(format!("terminating cluster run {}", record.name)),
782            Err(why) => report.failed.push(format!(
783                "could not terminate cluster run {}: {why} — {}",
784                record.name,
785                terminate_command(record)
786            )),
787        }
788    }
789    report
790}
791
792#[cfg(test)]
793mod tests {
794    use super::super::pending::tests::sample;
795    use super::*;
796
797    #[test]
798    fn lists_live_skips_a_run_past_its_ttl_and_reads_the_owner_format() {
799        let dir = std::env::temp_dir().join(format!("greengate-lists-live-{}", std::process::id()));
800        let _ = std::fs::remove_dir_all(&dir); // best-effort: a scratch path; absent or left behind is harmless
801        std::fs::create_dir_all(&dir).unwrap();
802        let file = dir.join(super::super::PENDING_FILE);
803        let now = 1_800_000_000;
804        assert_eq!(lists_live(&file, now), Ok(false), "no file, no run");
805        let mut live = super::super::pending::tests::sample("wf-live");
806        live.submitted = now;
807        let mut gone = super::super::pending::tests::sample("wf-gone");
808        gone.submitted = now - TTL_SECS - EXPIRY_SLACK_SECS - 1;
809        std::fs::write(&file, super::super::pending::render_file(&[gone.clone()])).unwrap();
810        assert_eq!(
811            lists_live(&file, now),
812            Ok(false),
813            "a run past its TTL is not live"
814        );
815        std::fs::write(&file, super::super::pending::render_file(&[gone, live])).unwrap();
816        assert_eq!(lists_live(&file, now), Ok(true));
817        std::fs::write(&file, "not json").unwrap();
818        assert!(lists_live(&file, now).is_err());
819    }
820
821    fn fixture(name: &str) -> String {
822        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
823            .join("../greengate/tests/it/fixtures/argo");
824        std::fs::read_to_string(dir.join(name)).expect("fixture")
825    }
826
827    /// `text` without the whitespace outside strings, so a replacement does
828    /// not depend on how the fixture was indented.
829    fn compact(text: &str) -> String {
830        let (mut out, mut in_string, mut escaped) = (String::new(), false, false);
831        for c in text.chars() {
832            if in_string {
833                out.push(c);
834                match (escaped, c) {
835                    (true, _) => escaped = false,
836                    (false, '\\') => escaped = true,
837                    (false, '"') => in_string = false,
838                    (false, _) => {}
839                }
840            } else if c == '"' {
841                in_string = true;
842                out.push(c);
843            } else if !c.is_whitespace() {
844                out.push(c);
845            }
846        }
847        out
848    }
849
850    /// What the cluster answers for `record`: the first live run's pod, made
851    /// the pod of task `g0` of the Workflow, and a Workflow in `phase` whose
852    /// node for it is in `node_phase`. `tweak` edits the pod's compact text.
853    fn list_for(
854        record: &Pending,
855        phase: &str,
856        node_phase: &str,
857        tweak: impl Fn(String) -> String,
858    ) -> Value {
859        let node = node_name(&record.name, "g0");
860        let pod = compact(&fixture("pod-succeeded.json"))
861            .replace(
862                "\"workflows.argoproj.io/node-name\":\"greengate-handrun-pqtbl\"",
863                &format!("\"workflows.argoproj.io/node-name\":\"{node}\""),
864            )
865            .replace(
866                "\"workflows.argoproj.io/node-id\":\"greengate-handrun-pqtbl\"",
867                "\"workflows.argoproj.io/node-id\":\"node-g0\"",
868            )
869            .replace("greengate-handrun-pqtbl", &record.name)
870            .replace("b8eb52b7-8ede-4c1f-bd94-9ada529eec97", "uid-1")
871            .replace("handrun-2", &record.label);
872        let wf = format!(
873            "{{\"kind\":\"Workflow\",\"metadata\":{{\"name\":\"{}\",\"uid\":\"uid-1\",\
874             \"labels\":{{\"greengate.run\":\"{}\"}}}},\"status\":{{\"phase\":\"{phase}\",\
875             \"nodes\":{{\"node-g0\":{{\"id\":\"node-g0\",\"name\":\"{node}\",\"type\":\"Pod\",\
876             \"templateName\":\"gate-g0\",\"phase\":\"{node_phase}\"}}}}}}}}",
877            record.name, record.label
878        );
879        let list = format!("{{\"kind\":\"List\",\"items\":[{wf},{}]}}", tweak(pod));
880        crate::json_read::parse(&list).expect("list json")
881    }
882
883    #[test]
884    fn a_workflow_phase_is_only_ever_finished_or_not() {
885        for (phase, finished) in [
886            ("Succeeded", true),
887            ("Failed", true),
888            ("Error", true),
889            ("Running", false),
890            ("Pending", false),
891            ("", false),
892        ] {
893            assert_eq!(RecordPhase::parse(phase).finished(), finished, "{phase}");
894        }
895    }
896
897    /// `main` alone decides: exit 0 is the only pass, whatever else the pod
898    /// or the Workflow says.
899    #[test]
900    fn the_end_of_a_pod_comes_from_main_alone() {
901        let ended = |exit, reason: &str| State::Terminated {
902            exit: Some(exit),
903            reason: reason.into(),
904            message: String::new(),
905        };
906        assert_eq!(end_from_main(&ended(0, "Completed")), JobEnd::Complete);
907        assert_eq!(
908            end_from_main(&ended(1, "Error")),
909            JobEnd::Failed("Error".into())
910        );
911        assert_eq!(
912            end_from_main(&ended(137, "OOMKilled")),
913            JobEnd::Failed("OOMKilled".into())
914        );
915        assert_eq!(end_from_main(&State::Running), JobEnd::Running);
916        assert_eq!(end_from_main(&State::Waiting), JobEnd::Running);
917        assert_eq!(end_from_main(&State::Absent), JobEnd::Running);
918    }
919
920    fn record_of_the_fixture() -> Pending {
921        let mut record = sample("greengate-rh-test");
922        record.uid = Some("uid-1".into());
923        record.label = "label-1".into();
924        record.tree = "13b5ee2d54389399fa2738f084a1b653b5844028".into();
925        record.source.oid = "7e04624939f8c93f774d570276af8643c61f0320".into();
926        record.gates[0].argv = vec!["python3".into(), "scripts/check-module-cycles.py".into()];
927        record.gates[0].prepare = None;
928        record.gates[0].digest =
929            "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c".into();
930        record
931    }
932
933    fn collected(record: Pending, list: &Value) -> Resolution {
934        resolve(record, list, 1_700_000_100)
935    }
936
937    /// The first live run, collected: a pass written under the FROZEN token,
938    /// and the finished Workflow leaves the file.
939    #[test]
940    fn the_live_fixture_is_a_pass() {
941        let record = record_of_the_fixture();
942        let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
943        let done = collected(record, &list);
944        assert!(done.notes.is_empty(), "{:?}", done.notes);
945        assert_eq!(done.passes.len(), 1, "{done:?}");
946        assert_eq!(
947            done.passes[0].token, "pre-push-lint@abc",
948            "the frozen token"
949        );
950        assert!(done.passes[0].provenance.contains("platform=x86_64-linux"));
951        assert!(done.leaves, "a finished Workflow leaves the file");
952    }
953
954    /// The node and the Workflow say Succeeded; `main` exited 1. Phases only
955    /// say the pod finished.
956    #[test]
957    fn a_succeeded_node_with_a_failed_main_is_no_pass() {
958        let record = record_of_the_fixture();
959        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
960            p.replacen(
961                "\"exitCode\":0,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
962                "\"exitCode\":1,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
963                1,
964            )
965        });
966        let done = collected(record, &list);
967        assert!(done.passes.is_empty(), "{done:?}");
968        assert_eq!(done.notes.len(), 1, "{done:?}");
969        assert!(done.notes[0].1.contains("exit 1"), "{:?}", done.notes);
970    }
971
972    #[test]
973    fn a_pod_of_another_workflow_uid_is_not_this_ones() {
974        let record = record_of_the_fixture();
975        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
976            p.replace("\"uid\":\"uid-1\"", "\"uid\":\"uid-other\"")
977        });
978        let done = collected(record, &list);
979        assert!(done.passes.is_empty(), "{done:?}");
980    }
981
982    #[test]
983    fn a_pod_with_another_image_or_command_is_not_the_submission() {
984        for tweak in [
985            |p: String| {
986                p.replace(
987                    "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c",
988                    &format!("sha256:{}", "0".repeat(64)),
989                )
990            },
991            |p: String| p.replace("scripts/check-module-cycles.py", "scripts/other.py"),
992            |p: String| {
993                p.replace(
994                    "tree 13b5ee2d54389399fa2738f084a1b653b5844028",
995                    "tree 0000000000000000000000000000000000000000",
996                )
997            },
998        ] {
999            let record = record_of_the_fixture();
1000            let list = list_for(&record, "Succeeded", "Succeeded", tweak);
1001            let done = collected(record, &list);
1002            assert!(done.passes.is_empty(), "{done:?}");
1003            assert_eq!(done.notes.len(), 1, "{done:?}");
1004        }
1005    }
1006
1007    #[test]
1008    fn a_running_workflow_keeps_its_waiting_gates() {
1009        let record = record_of_the_fixture();
1010        let list = list_for(&record, "Running", "Running", |p| {
1011            // `main` has not terminated: the same state, reopened as running
1012            p.replace(
1013                "\"terminated\":{\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
1014                "\"running\":{\"startedAt\":\"t\",\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
1015            )
1016        });
1017        let done = collected(record, &list);
1018        assert!(done.passes.is_empty(), "{done:?}");
1019        assert!(!done.leaves);
1020        assert_eq!(done.record.gates[0].state, GateState::Waiting);
1021        assert_eq!(done.record.phase, RecordPhase::Running);
1022    }
1023
1024    #[test]
1025    fn a_workflow_gone_after_its_ttl_drops_the_record_with_one_note() {
1026        let record = record_of_the_fixture();
1027        let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
1028        let done = collected(record, &empty);
1029        assert!(done.leaves);
1030        assert_eq!(done.record.phase, RecordPhase::Gone);
1031        assert_eq!(done.record.phase.plain(), "gone (TTL passed or deleted)");
1032        assert_eq!(done.notes.len(), 1, "{done:?}");
1033    }
1034
1035    /// A create whose answer was lost: no Workflow yet, so the intent stays
1036    /// for a while, and goes once the grace has passed.
1037    #[test]
1038    fn an_intent_with_no_workflow_waits_then_goes() {
1039        let mut record = record_of_the_fixture();
1040        record.uid = None;
1041        let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
1042        let young = resolve(record.clone(), &empty, record.submitted + 60);
1043        assert!(!young.leaves);
1044        let old = resolve(
1045            record.clone(),
1046            &empty,
1047            record.submitted + INTENT_GRACE_SECS + 1,
1048        );
1049        assert!(old.leaves);
1050        assert_eq!(old.notes.len(), 1);
1051    }
1052
1053    /// The Workflow finished and passed, but the token cannot be written: the
1054    /// record stays, its gate waiting, and the next collect writes the token.
1055    #[test]
1056    fn a_pass_whose_token_cannot_be_written_keeps_the_record() {
1057        let record = record_of_the_fixture();
1058        let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
1059        let refuse = |_: &Pass| Err(Fallback::NotProved("git refused".into()));
1060        let first = settle_with(resolve(record.clone(), &list, 1_700_000_100), refuse);
1061        assert_eq!(first.written, 0);
1062        assert!(
1063            first.settled.is_none(),
1064            "the run has not ended for the person"
1065        );
1066        let kept = first.record.expect("the record survives");
1067        assert_eq!(kept.gates[0].state, GateState::Waiting);
1068
1069        let mut tokens = Vec::new();
1070        let second = settle_with(resolve(kept, &list, 1_700_000_200), |pass| {
1071            tokens.push(pass.token.clone());
1072            Ok(())
1073        });
1074        assert_eq!(second.written, 1);
1075        assert_eq!(tokens, ["pre-push-lint@abc"]);
1076        assert!(second.record.is_none());
1077        let ended = second.settled.expect("now it ends");
1078        assert_eq!(ended.passed, ["pre-push-lint"]);
1079    }
1080
1081    /// A finished Workflow whose pod status cannot be read fails the gate.
1082    #[test]
1083    fn an_unreadable_pod_status_on_a_finished_workflow_fails_the_gate() {
1084        let record = record_of_the_fixture();
1085        let list = list_for(&record, "Failed", "Failed", |p| {
1086            p.replace(
1087                "\"name\":\"greengate-rh-test\",\"namespace\"",
1088                "\"namex\":\"greengate-rh-test\",\"namespace\"",
1089            )
1090        });
1091        let done = collected(record, &list);
1092        assert!(done.passes.is_empty());
1093        assert_eq!(done.notes.len(), 1, "{done:?}");
1094        assert!(
1095            done.notes[0].1.contains("status cannot be read"),
1096            "{done:?}"
1097        );
1098    }
1099
1100    /// A pod that does not name its node cannot be bound to the Workflow's.
1101    #[test]
1102    fn a_pod_without_a_node_id_is_not_bound() {
1103        let record = record_of_the_fixture();
1104        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1105            p.replace(
1106                "workflows.argoproj.io/node-id",
1107                "workflows.argoproj.io/node-idx",
1108            )
1109        });
1110        let done = collected(record, &list);
1111        assert!(done.passes.is_empty(), "{done:?}");
1112    }
1113
1114    #[test]
1115    fn a_record_older_than_the_ttl_expires_whatever_the_cluster_says() {
1116        let record = record_of_the_fixture();
1117        assert!(!is_expired(&record, record.submitted + TTL_SECS));
1118        assert!(is_expired(
1119            &record,
1120            record.submitted + TTL_SECS + EXPIRY_SLACK_SECS + 1
1121        ));
1122    }
1123}