Skip to main content

greengate_runtime/cluster/
detached.rs

1//! A rehearsal's `platform=any` gates as one Argo Workflow that outlives the
2//! laptop (ADR-0017).
3//!
4//! `amont rehearse --cluster`, or `greengate.rehearse.cluster` for the
5//! post-commit rehearsal, hands the gates a rehearsal would run, and that the
6//! cluster may run, to one Workflow: a DAG with a pod per gate, the same pod
7//! as ADR-0016's Job. The code goes in as a Forgejo snapshot commit, or is
8//! read from a pull mirror that already advertises it. Submission returns
9//! once the Workflow exists; [`collect`] turns its passes into cluster tokens
10//! at the start of the next hook, from facts Kubernetes recorded, under the
11//! identity frozen at submission. The laptop is the only signer.
12//!
13//! Every path that goes wrong ends in the gate running here, as before: a
14//! detached run can only remove work from a push, never let it skip work
15//! nobody did.
16
17use std::time::Duration;
18
19use crate::check::Stage;
20use crate::manifest::{External, Kind, Manifest};
21
22use super::{
23    key, last_line, log_line, machine_keys, run_label, sanitize_repo_dir, token_from, Call,
24    ClusterConfig, Fallback, Kube, CALL_SECS, SEQ,
25};
26use crate::json_read::Value;
27
28mod collect;
29mod pending;
30mod workflow;
31
32pub use collect::collect_command;
33pub(crate) use collect::{collect, lists_live, settled_lines, status_lines, stop_pending};
34#[cfg(test)]
35pub(crate) use pending::sample_file as sample_pending_file;
36pub(crate) use pending::PENDING_FILE;
37
38use pending::{Gate, GateState, Pending, PendingError, RecordPhase, Source, Store};
39
40/// The machine key that sends every rehearsal to the cluster.
41const REHEARSE_CLUSTER: &str = "greengate.rehearse.cluster";
42/// A push of the snapshot commit, and a read of a remote's refs, are network
43/// calls with a deadline each.
44const PUSH_SECS: u64 = 60;
45const LS_REMOTE_SECS: u64 = 20;
46/// How long a submission waits for the pending file's lock.
47const LOCK_WAIT: Duration = Duration::from_secs(5);
48
49/// Who asks for a rehearsal to go to the cluster.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum Ask {
52    /// `rehearse --cluster`: the person asked, so what goes wrong is said.
53    Flag,
54    /// Only the machine key may ask (`greengate.rehearse.cluster`): the
55    /// post-commit rehearsal, which says nothing on the terminal.
56    Setting,
57}
58
59/// Does this rehearsal go to the cluster: asked for with `--cluster`, or the
60/// machine says `greengate.rehearse.cluster true`?
61pub fn wanted(settings: &crate::config::Settings, ask: Ask) -> bool {
62    ask == Ask::Flag || crate::config::boolean_or(settings, REHEARSE_CLUSTER, false)
63}
64
65/// The gates of a rehearsal that are on the cluster for `HEAD`'s tree now.
66#[derive(Debug, Clone, PartialEq, Eq, Default)]
67pub struct Detached {
68    pub gates: Vec<String>,
69}
70
71/// A Workflow's pod stops here for tests that kill amont at a precise point.
72/// Compiled only with `test-hooks`: nothing reads the variable otherwise.
73#[cfg(feature = "test-hooks")]
74fn crash_point(at: &str) {
75    if std::env::var("GREENGATE_TEST_CRASH").is_ok_and(|v| v == at) {
76        std::process::exit(137);
77    }
78}
79
80#[cfg(not(feature = "test-hooks"))]
81fn crash_point(_at: &str) {}
82
83/// The detached lane's machine keys, as git prints them (lowercased).
84struct Machine {
85    base: ClusterConfig,
86    snapshot_remote: String,
87    snapshot_fetch: String,
88    mirror: Option<Mirror>,
89}
90
91/// A read-only pull mirror: where the laptop lists its refs, and where the
92/// cluster fetches from.
93struct Mirror {
94    remote: String,
95    fetch: String,
96}
97
98fn machine(settings: &crate::config::Settings) -> Result<Machine, Fallback> {
99    let base = super::cluster_config(settings)?;
100    let keys = machine_keys();
101    let need = |name: &'static str, shown: &'static str| {
102        key(&keys, name)
103            .map(str::to_string)
104            .ok_or(Fallback::Unconfigured(shown))
105    };
106    let snapshot_remote = need(
107        "greengate.cluster.snapshotremote",
108        "greengate.cluster.snapshotRemote is not set: `git config --global greengate.cluster.snapshotRemote 'git@host:org/{repo}.git'`",
109    )?;
110    let snapshot_fetch = need(
111        "greengate.cluster.snapshotfetch",
112        "greengate.cluster.snapshotFetch is not set: `git config --global greengate.cluster.snapshotFetch 'http://forgejo-http.forgejo.svc.cluster.local:3000/org/{repo}.git'`",
113    )?;
114    let mirror = match (
115        key(&keys, "greengate.cluster.mirrorremote"),
116        key(&keys, "greengate.cluster.mirror"),
117    ) {
118        (Some(remote), Some(fetch)) => Some(Mirror {
119            remote: remote.to_string(),
120            fetch: fetch.to_string(),
121        }),
122        _ => None,
123    };
124    Ok(Machine {
125        base,
126        snapshot_remote,
127        snapshot_fetch,
128        mirror,
129    })
130}
131
132/// The repository's name for a URL template: the last segment of `origin`'s
133/// URL, without `.git`, as a plain word.
134fn repo_name() -> Result<String, String> {
135    let url = crate::git::stdout(&["remote", "get-url", "origin"])
136        .ok_or("the repository has no origin remote to name it by")?;
137    let last = url
138        .trim_end_matches('/')
139        .rsplit(['/', ':'])
140        .next()
141        .unwrap_or_default();
142    if last.is_empty() {
143        return Err(format!("cannot name the repository from {url:?}"));
144    }
145    Ok(sanitize_repo_dir(last))
146}
147
148fn expand(template: &str, repo: &str) -> String {
149    template.replace("{repo}", repo)
150}
151
152/// The trusted `platform=any` pre-push gates among `scoped` that the cluster
153/// may run: the repository says `set executor cluster`, and nothing local
154/// turned it off.
155fn eligible<'a>(
156    settings: &crate::config::Settings,
157    manifest: &'a Manifest,
158    scoped: &[String],
159) -> Vec<&'a External> {
160    if !super::executor_is_cluster(settings) {
161        return Vec::new();
162    }
163    scoped
164        .iter()
165        .filter_map(|name| {
166            manifest
167                .externals
168                .iter()
169                .find(|e| e.stage == Stage::PrePush && e.id == *name)
170        })
171        .filter(|e| super::is_platform_any(e))
172        .collect()
173}
174
175/// The gates of the records of `tree` still waiting for a verdict, and every
176/// gate any record of `tree` holds, whatever its state.
177///
178/// An intent whose `create` never happened (amont died between the two)
179/// counts as waiting, so later rehearsals of the tree leave its gates alone.
180// holds-until: INTENT_GRACE_SECS (10 minutes) in collect.rs — collect drops an
181// intent no Workflow appeared for after that; until then the push, not the
182// rehearsal, runs those gates
183fn known_for(tree: &str) -> (Vec<String>, Vec<String>) {
184    let Some(store) = Store::here() else {
185        return (Vec::new(), Vec::new());
186    };
187    let records = match store.read() {
188        Ok(records) => records,
189        Err(why) => {
190            log_line("detach", &format!("cluster-pending is unreadable: {why}"));
191            return (Vec::new(), Vec::new());
192        }
193    };
194    let ours = records.iter().filter(|r| r.tree == tree);
195    let waiting = ours
196        .clone()
197        .flat_map(|r| r.waiting().map(|g| g.id.clone()))
198        .collect();
199    let all = ours
200        .flat_map(|r| r.gates.iter().map(|g| g.id.clone()))
201        .collect();
202    (waiting, all)
203}
204
205/// Hand `scoped` — the gates a rehearsal of `HEAD` would run — to the
206/// cluster, as far as it may take them, and say which are there now: the ones
207/// a record of this tree still waits for, and the ones this call submitted.
208/// The rest run here, exactly as without the lane.
209///
210/// `ask` is `--cluster` ([`Ask::Flag`]); `greengate.rehearse.cluster` asks too.
211/// With neither, nothing is submitted, but the gates an earlier call put there
212/// still count. What is said goes to stderr, and only when the person asked.
213pub fn detach(
214    settings: &crate::config::Settings,
215    manifest: &Manifest,
216    scoped: &[String],
217    ask: Ask,
218) -> Detached {
219    let Some(tree) = crate::git::stdout(&["rev-parse", "HEAD^{tree}"]) else {
220        return Detached::default();
221    };
222    let (waiting, known) = known_for(&tree);
223    let mut riding: Vec<String> = scoped
224        .iter()
225        .filter(|gate| waiting.contains(gate))
226        .cloned()
227        .collect();
228    if !wanted(settings, ask) {
229        return Detached { gates: riding };
230    }
231    let fresh: Vec<&External> = eligible(settings, manifest, scoped)
232        .into_iter()
233        .filter(|e| !known.contains(&e.id))
234        .collect();
235    if fresh.is_empty() {
236        if ask == Ask::Flag {
237            if riding.is_empty() {
238                eprintln!(
239                    "no gate of this rehearsal can go to the cluster: it needs a trusted \
240                     `platform=any` pre-push gate and `set executor cluster`"
241                );
242            } else {
243                eprintln!("already on the cluster: {}", riding.join(" "));
244            }
245        }
246        return Detached { gates: riding };
247    }
248    match submit(settings, &tree, &fresh) {
249        Ok(submitted) => {
250            eprintln!(
251                "submitted {} to the cluster: {} — the next commit or push collects the result",
252                submitted.name,
253                submitted.gates.join(" ")
254            );
255            riding.extend(submitted.gates);
256        }
257        Err(error) => {
258            let (line, spoken) = error.render();
259            for e in &fresh {
260                log_line(&e.id, &format!("detached: {line}"));
261            }
262            if ask == Ask::Flag {
263                crate::hooks::common::warn(&crate::ui::sanitize(&spoken));
264            }
265        }
266    }
267    Detached { gates: riding }
268}
269
270/// Why a submission did not end with a recorded Workflow.
271#[derive(Debug)]
272enum SubmitError {
273    /// Nothing was created: the gates run here.
274    NotSubmitted(Fallback),
275    /// A Workflow may exist, or does, but this process cannot vouch for it:
276    /// the gates run here as well, and a later collect adopts it.
277    Unconfirmed(String),
278}
279
280impl From<Fallback> for SubmitError {
281    fn from(f: Fallback) -> SubmitError {
282        SubmitError::NotSubmitted(f)
283    }
284}
285
286impl SubmitError {
287    /// The line for `cluster.log`, and the sentence for the person.
288    fn render(&self) -> (String, String) {
289        match self {
290            SubmitError::NotSubmitted(Fallback::Misconfigured { why, fix }) => (
291                why.clone(),
292                format!("not submitted to the cluster, the gates run here: {why} — fix with {fix}"),
293            ),
294            SubmitError::NotSubmitted(f) => (
295                f.to_string(),
296                format!("not submitted to the cluster, the gates run here: {f}"),
297            ),
298            SubmitError::Unconfirmed(why) => (
299                format!("not confirmed: {why}"),
300                format!(
301                    "submitted, not confirmed ({why}); the gates also run here, and the next \
302                     commit or push collects the Workflow if it landed"
303                ),
304            ),
305        }
306    }
307}
308
309/// A Workflow that exists on the cluster and is recorded.
310struct Submitted {
311    name: String,
312    gates: Vec<String>,
313}
314
315/// Where the code comes from, and the URL the cluster fetches it by.
316struct Origin {
317    source: Source,
318    url: String,
319}
320
321fn submit(
322    settings: &crate::config::Settings,
323    tree: &str,
324    gates: &[&External],
325) -> Result<Submitted, SubmitError> {
326    let machine = machine(settings)?;
327    let head = crate::git::stdout(&["rev-parse", "HEAD"])
328        .ok_or_else(|| Fallback::NotProved("git would not name HEAD".into()))?;
329    let repo = repo_name().map_err(Fallback::NotProved)?;
330    let label = run_label(SEQ.fetch_add(1, std::sync::atomic::Ordering::SeqCst));
331    let frozen = freeze(settings, &machine, gates)?;
332    let origin = choose_origin(&machine, &repo, &head, tree, &label)?;
333    let record = Pending {
334        name: workflow::workflow_name(&label),
335        uid: None,
336        label,
337        namespace: machine.base.namespace.clone(),
338        kubeconfig: machine.base.kubeconfig.clone(),
339        tree: tree.to_string(),
340        source: origin.source,
341        submitted: crate::gate_evidence::now(),
342        phase: RecordPhase::Submitting,
343        gates: frozen,
344    };
345    let store = Store::here()
346        .ok_or_else(|| Fallback::NotProved("git would not name the common directory".into()))?;
347    record_intent(&store, &record)?;
348    crash_point("before-create");
349    let plan = workflow::Plan {
350        config: &machine.base,
351        record: &record,
352        repo_dir: &super::repo_dir(),
353        url: &origin.url,
354    };
355    let kube = Kube::new(&machine.base);
356    let uid = create(&kube, &record, &workflow::workflow_json(&plan))?;
357    crash_point("after-create");
358    adopt(&store, &record.name, &uid)?;
359    Ok(Submitted {
360        name: record.name,
361        gates: record.gates.into_iter().map(|g| g.id).collect(),
362    })
363}
364
365/// Each gate's identity, frozen: the token as the push will look it up, from
366/// the same function, so a pass earned under today's configuration is one only
367/// today's configuration accepts.
368fn freeze(
369    settings: &crate::config::Settings,
370    machine: &Machine,
371    gates: &[&External],
372) -> Result<Vec<Gate>, Fallback> {
373    let keys = machine_keys();
374    gates
375        .iter()
376        .enumerate()
377        .map(|(i, ext)| {
378            let Kind::Runnable {
379                program,
380                args,
381                scope,
382                ..
383            } = &ext.kind
384            else {
385                return Err(Fallback::NotProved(format!("{} is not runnable", ext.id)));
386            };
387            let token = token_from(&keys, settings, ext, &ext.id).ok_or_else(|| {
388                Fallback::NotProved(format!("git would not hash the identity of {}", ext.id))
389            })?;
390            let mut argv = vec![program.clone()];
391            argv.extend(args.iter().cloned());
392            Ok(Gate {
393                id: ext.id.clone(),
394                task: format!("g{i}"),
395                argv,
396                scope: format!("{scope:?}"),
397                prepare: machine.base.prepare.clone(),
398                digest: machine.base.digest.clone(),
399                contract: crate::gate_identity::CLUSTER_CONTRACT.to_string(),
400                token,
401                state: GateState::Waiting,
402            })
403        })
404        .collect()
405}
406
407/// The mirror when it advertises `head`; otherwise a snapshot commit pushed to
408/// the snapshot remote and read back.
409fn choose_origin(
410    machine: &Machine,
411    repo: &str,
412    head: &str,
413    tree: &str,
414    label: &str,
415) -> Result<Origin, Fallback> {
416    if let Some(mirror) = &machine.mirror {
417        match advertised(&expand(&mirror.remote, repo)) {
418            Ok(oids) if oids.iter().any(|o| o == head) => {
419                return Ok(Origin {
420                    source: Source {
421                        snapshot_ref: None,
422                        oid: head.to_string(),
423                    },
424                    url: expand(&mirror.fetch, repo),
425                })
426            }
427            Ok(_) => {}
428            Err(why) => log_line("detach", &format!("mirror not listed: {why}")),
429        }
430    }
431    let oid = snapshot_commit(head, tree, label)?;
432    let snapshot_ref = format!("refs/snapshots/{label}");
433    let remote = expand(&machine.snapshot_remote, repo);
434    push_snapshot(&remote, &oid, &snapshot_ref)?;
435    let seen = advertised_at(&remote, &snapshot_ref)
436        .map_err(|why| Fallback::NotProved(format!("the snapshot was not read back: {why}")))?;
437    if seen.as_deref() != Some(oid.as_str()) {
438        return Err(Fallback::NotProved(
439            "the snapshot was pushed but not read back from the remote".into(),
440        ));
441    }
442    Ok(Origin {
443        source: Source {
444            snapshot_ref: Some(snapshot_ref),
445            oid,
446        },
447        url: expand(&machine.snapshot_fetch, repo),
448    })
449}
450
451/// The commit objects `git ls-remote <remote>` advertises. `ls-remote <sha>`
452/// would match ref NAMES, never commits, so the answer is compared here.
453fn advertised(remote: &str) -> Result<Vec<String>, String> {
454    let (probe, out) = crate::git::probe_remote_stdout(
455        &["ls-remote", remote, "refs/heads/*", "refs/tags/*"],
456        LS_REMOTE_SECS,
457    );
458    match probe {
459        crate::git::Probe::Exit(0) => Ok(out
460            .lines()
461            .filter_map(|l| l.split_whitespace().next())
462            .map(str::to_string)
463            .collect()),
464        other => Err(format!("git ls-remote {remote}: {other:?}")),
465    }
466}
467
468/// The object `ref_name` points to on `remote`, if it is there.
469fn advertised_at(remote: &str, ref_name: &str) -> Result<Option<String>, String> {
470    let (probe, out) =
471        crate::git::probe_remote_stdout(&["ls-remote", remote, ref_name], LS_REMOTE_SECS);
472    match probe {
473        crate::git::Probe::Exit(0) => Ok(out
474            .lines()
475            .filter_map(|l| l.split_once('\t'))
476            .find(|(_, name)| *name == ref_name)
477            .map(|(oid, _)| oid.trim().to_string())),
478        other => Err(format!("git ls-remote {remote}: {other:?}")),
479    }
480}
481
482/// A commit holding `tree` with `head` as its parent, dated NOW: the prune
483/// ages a snapshot ref by its commit's committer date, so a reused date would
484/// age a fresh snapshot out at once.
485fn snapshot_commit(head: &str, tree: &str, label: &str) -> Result<String, Fallback> {
486    let now = format!("@{} +0000", crate::gate_evidence::now());
487    let out = std::process::Command::new("git")
488        .args(["commit-tree", tree, "-p", head, "-m"])
489        .arg(format!("greengate snapshot {label}"))
490        .env("GIT_AUTHOR_NAME", crate::names::GIT_AUTHOR)
491        .env("GIT_AUTHOR_EMAIL", crate::names::GIT_EMAIL)
492        .env("GIT_COMMITTER_NAME", crate::names::GIT_AUTHOR)
493        .env("GIT_COMMITTER_EMAIL", crate::names::GIT_EMAIL)
494        .env("GIT_AUTHOR_DATE", &now)
495        .env("GIT_COMMITTER_DATE", &now)
496        .stdin(std::process::Stdio::null())
497        .output()
498        .map_err(|e| Fallback::NotProved(format!("git commit-tree: {e}")))?;
499    let oid = String::from_utf8_lossy(&out.stdout).trim().to_string();
500    if out.status.success() && !oid.is_empty() {
501        Ok(oid)
502    } else {
503        Err(Fallback::NotProved("git commit-tree failed".into()))
504    }
505}
506
507/// Push `oid` to `ref_name` on `remote` with the person's own credentials:
508/// never a prompt, bounded, and marked so this repository's own pre-push hook
509/// stands down instead of judging a snapshot.
510fn push_snapshot(remote: &str, oid: &str, ref_name: &str) -> Result<(), Fallback> {
511    let (mut args, mut env) = crate::git::remote_env(crate::git::configured_ssh());
512    env.push((crate::attest::PUSH_GUARD, "1"));
513    let refspec = format!("{oid}:{ref_name}");
514    args.extend(["push", "-q", remote, &refspec]);
515    match crate::git::probe_env(&args, PUSH_SECS, &env) {
516        crate::git::Probe::Exit(0) => Ok(()),
517        other => Err(Fallback::NotProved(format!(
518            "git push of the snapshot to {remote}: {other:?}"
519        ))),
520    }
521}
522
523/// Write the intent: a record with no UID, durably, before anything is
524/// created. Under the same lock, a record of the same tree that already holds
525/// one of these gates refuses it: two rehearsals of one tree that both passed
526/// the unlocked look in [`known_for`] cannot both submit.
527fn record_intent(store: &Store, record: &Pending) -> Result<(), Fallback> {
528    let not = |why: PendingError| Fallback::NotProved(format!("cluster-pending: {why}"));
529    let held = store.lock_within(LOCK_WAIT).ok_or_else(|| {
530        Fallback::NotProved("cluster-pending: busy, or no flock on this platform".into())
531    })?;
532    let mut records = store.read().map_err(not)?;
533    if let Some(taken) = holder_of(&records, record) {
534        return Err(Fallback::NotProved(format!(
535            "another submission of this tree already holds {taken}"
536        )));
537    }
538    records.push(record.clone());
539    store.write(&held, &records).map_err(not)
540}
541
542/// A gate of `record` that a record of the same tree in `records` holds.
543fn holder_of(records: &[Pending], record: &Pending) -> Option<String> {
544    records
545        .iter()
546        .filter(|other| other.tree == record.tree)
547        .flat_map(|other| other.gates.iter())
548        .find(|held| record.gates.iter().any(|g| g.id == held.id))
549        .map(|held| held.id.clone())
550}
551
552/// Set the UID of the record `name`, durably. The record may have been
553/// adopted already by a collect that found the Workflow first.
554fn adopt(store: &Store, name: &str, uid: &str) -> Result<(), SubmitError> {
555    let not = |why: String| {
556        SubmitError::Unconfirmed(format!(
557            "the Workflow exists but its UID was not recorded: {why}"
558        ))
559    };
560    let held = store
561        .lock_within(LOCK_WAIT)
562        .ok_or_else(|| not("cluster-pending is busy".into()))?;
563    let records: Vec<Pending> = store
564        .read()
565        .map_err(|e| not(e.to_string()))?
566        .into_iter()
567        .map(|mut r| {
568            if r.name == name && r.uid.is_none() {
569                r.uid = Some(uid.to_string());
570                r.phase = RecordPhase::Pending;
571            }
572            r
573        })
574        .collect();
575    store.write(&held, &records).map_err(|e| not(e.to_string()))
576}
577
578/// How a `kubectl create` of the Workflow ended.
579#[derive(Debug, PartialEq, Eq)]
580enum Created {
581    /// The Workflow exists, with this UID.
582    Made(String),
583    /// The name is taken: a Workflow of this name exists.
584    Taken,
585    /// The apiserver answered with an error: nothing was created.
586    Rejected(String),
587    /// kubectl did not start: nothing reached the apiserver.
588    NotSent(String),
589    /// The request may have landed: the answer was lost, or never came.
590    Unknown(String),
591}
592
593fn classify(call: Call) -> Created {
594    match call {
595        Call::Ok(uid) if !uid.trim().is_empty() => Created::Made(uid.trim().to_string()),
596        Call::Ok(_) => Created::Unknown("kubectl create printed no UID".into()),
597        Call::Refused(err) if err.contains("AlreadyExists") || err.contains("already exists") => {
598            Created::Taken
599        }
600        // "Error from server (…)" is the apiserver speaking: it refused.
601        // Anything else (an EOF, a reset, a deadline) may have landed.
602        Call::Refused(err) if err.contains("Error from server") => {
603            Created::Rejected(last_line(&err))
604        }
605        Call::Refused(err) | Call::TimedOut(err) => Created::Unknown(last_line(&err)),
606        Call::NotStarted(err) => Created::NotSent(err),
607    }
608}
609
610/// Why a `create` may or may not have landed, for [`reconcile`].
611#[derive(Debug, PartialEq, Eq)]
612enum Uncertain {
613    /// The name is taken: a Workflow of this name exists.
614    Taken,
615    /// The answer was lost, or never came.
616    Lost(String),
617}
618
619/// Create the Workflow ONCE, as `greengate-gate-runner` (the kubeconfig's user),
620/// and return its UID. A create whose answer is lost is reconciled by `get`
621/// on its deterministic name and never repeated.
622fn create(kube: &Kube, record: &Pending, json: &str) -> Result<String, SubmitError> {
623    let file = ManifestFile::write(&record.label, json)?;
624    let path = file.path.to_string_lossy().into_owned();
625    let args = ["create", "-f", &path, "-o", "jsonpath={.metadata.uid}"];
626    let outcome = classify(kube.capture(&args, CALL_SECS));
627    drop(file);
628    match outcome {
629        Created::Made(uid) => Ok(uid),
630        Created::Rejected(why) => {
631            forget(record);
632            Err(Fallback::NotProved(format!("the cluster refused it: {why}")).into())
633        }
634        Created::NotSent(why) => {
635            forget(record);
636            Err(Fallback::Unreachable(why).into())
637        }
638        Created::Taken => reconcile(kube, record, Uncertain::Taken),
639        Created::Unknown(why) => reconcile(kube, record, Uncertain::Lost(why)),
640    }
641}
642
643/// After a create that may have landed: `get` the Workflow by its name and
644/// adopt it only if its spec is the one submitted.
645fn reconcile(kube: &Kube, record: &Pending, uncertain: Uncertain) -> Result<String, SubmitError> {
646    let said = match uncertain {
647        Uncertain::Lost(why) => why,
648        Uncertain::Taken => "the name was taken".to_string(),
649    };
650    match kube.capture(&["get", "workflow", &record.name, "-o", "json"], CALL_SECS) {
651        Call::Ok(json) => {
652            let wf = crate::json_read::parse(&json).ok_or_else(|| {
653                SubmitError::Unconfirmed("the Workflow found by name is not JSON".into())
654            })?;
655            let uid = wf
656                .get("metadata")
657                .and_then(|m| m.get("uid"))
658                .and_then(Value::as_str)
659                .ok_or_else(|| SubmitError::Unconfirmed("the Workflow found has no UID".into()))?;
660            match workflow::check_workflow(&wf, record) {
661                Ok(()) => Ok(uid.to_string()),
662                Err(why) => {
663                    forget(record);
664                    Err(Fallback::NotProved(format!(
665                        "a Workflow named {} exists and is not the one submitted: {why}",
666                        record.name
667                    ))
668                    .into())
669                }
670            }
671        }
672        // Not there: one whose answer was lost keeps its intent, so that a
673        // request landing late is adopted by the next collect and never
674        // repeated.
675        Call::Refused(err) if err.contains("NotFound") => Err(SubmitError::Unconfirmed(format!(
676            "the cluster did not show the Workflow ({said}); the intent is kept"
677        ))),
678        Call::Refused(err) | Call::NotStarted(err) | Call::TimedOut(err) => {
679            Err(SubmitError::Unconfirmed(format!(
680                "the Workflow could not be looked up ({said}; {})",
681                last_line(&err)
682            )))
683        }
684    }
685}
686
687/// Drop the intent of `record`: nothing was created for it. Failing to is
688/// logged, never fatal: an intent with no Workflow expires.
689fn forget(record: &Pending) {
690    let Some(store) = Store::here() else { return };
691    let Some(held) = store.lock_within(LOCK_WAIT) else {
692        log_line(
693            "detach",
694            &format!("could not drop the intent of {}", record.name),
695        );
696        return;
697    };
698    let kept: Result<Vec<Pending>, PendingError> = store
699        .read()
700        .map(|rs| rs.into_iter().filter(|r| r.name != record.name).collect());
701    let written = kept.and_then(|rs| store.write(&held, &rs));
702    if let Err(why) = written {
703        log_line(
704            "detach",
705            &format!("could not drop the intent of {}: {why}", record.name),
706        );
707    }
708}
709
710/// The manifest handed to `kubectl create -f`, in a private file of its own:
711/// created fresh and unreadable to others, removed when dropped, and listed
712/// with the interrupt clean-up, which deletes this file and nothing else. Not
713/// a [`super::Scratch`]: that registers a clean-up which deletes Jobs, and a
714/// detached Workflow is meant to survive amont.
715struct ManifestFile {
716    path: std::path::PathBuf,
717}
718
719impl ManifestFile {
720    fn write(label: &str, json: &str) -> Result<ManifestFile, Fallback> {
721        let path = std::env::temp_dir().join(format!("greengate-workflow-{label}.json"));
722        let mut options = std::fs::OpenOptions::new();
723        options.write(true).create_new(true);
724        #[cfg(unix)]
725        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
726        options
727            .open(&path)
728            .and_then(|mut f| std::io::Write::write_all(&mut f, json.as_bytes()))
729            .map_err(|e| Fallback::NotProved(format!("manifest file: {e}")))?;
730        super::track_temp_file(&path);
731        Ok(ManifestFile { path })
732    }
733}
734
735impl Drop for ManifestFile {
736    fn drop(&mut self) {
737        super::untrack_temp_file(&self.path);
738        if let Err(e) = std::fs::remove_file(&self.path) {
739            crate::hooks::common::warn(&format!("could not remove {}: {e}", self.path.display()));
740        }
741    }
742}
743
744#[cfg(test)]
745mod tests {
746    use super::*;
747
748    #[test]
749    fn a_repository_is_named_by_its_origin() {
750        // the last segment, with no `.git`
751        for (url, name) in [
752            ("git@git.example:org/relais.git", "relais"),
753            (
754                "https://github.com/o/duro-design-system",
755                "duro-design-system",
756            ),
757            ("/tmp/x/remote.git/", "remote"),
758        ] {
759            let last = url
760                .trim_end_matches('/')
761                .rsplit(['/', ':'])
762                .next()
763                .unwrap_or_default();
764            assert_eq!(sanitize_repo_dir(last), name, "{url}");
765        }
766        assert_eq!(
767            expand("git@h:amont-snapshots/{repo}.git", "relais"),
768            "git@h:amont-snapshots/relais.git"
769        );
770    }
771
772    #[test]
773    fn a_create_is_only_repeated_never() {
774        let made = classify(Call::Ok("uid-1\n".into()));
775        assert_eq!(made, Created::Made("uid-1".into()));
776        assert_eq!(
777            classify(Call::Refused(
778                "Error from server (AlreadyExists): workflows.argoproj.io \"x\" already exists"
779                    .into()
780            )),
781            Created::Taken
782        );
783        // the apiserver spoke: nothing was created
784        assert!(matches!(
785            classify(Call::Refused(
786                "Error from server (Forbidden): workflows is forbidden".into()
787            )),
788            Created::Rejected(_)
789        ));
790        // a lost answer may have landed
791        assert!(matches!(
792            classify(Call::Refused("error: unexpected EOF".into())),
793            Created::Unknown(_)
794        ));
795        assert!(matches!(
796            classify(Call::TimedOut("kubectl timed out".into())),
797            Created::Unknown(_)
798        ));
799        assert!(matches!(
800            classify(Call::Ok(String::new())),
801            Created::Unknown(_)
802        ));
803        assert!(matches!(
804            classify(Call::NotStarted("kubectl: not found".into())),
805            Created::NotSent(_)
806        ));
807    }
808
809    #[test]
810    fn a_second_submission_of_a_tree_cannot_take_a_gate_already_held() {
811        let held = super::pending::tests::sample("wf-1");
812        let mut other = super::pending::tests::sample("wf-2");
813        assert_eq!(
814            holder_of(std::slice::from_ref(&held), &other),
815            Some("pre-push-lint".to_string())
816        );
817        other.tree = "0".repeat(40);
818        assert_eq!(holder_of(&[held], &other), None, "another tree");
819    }
820
821    /// Under the lock, a record of the same tree holding the gate refuses the
822    /// second intent: two rehearsals that both looked first cannot both submit.
823    #[cfg(unix)]
824    #[test]
825    fn record_intent_refuses_a_gate_a_record_of_the_tree_holds() {
826        let dir = std::env::temp_dir().join(format!("greengate-intent-{}", std::process::id()));
827        std::fs::create_dir_all(&dir).expect("mkdir");
828        let store = Store::in_dir(&dir);
829        let first = super::pending::tests::sample("wf-1");
830        assert!(record_intent(&store, &first).is_ok());
831        let second = super::pending::tests::sample("wf-2");
832        let refused = record_intent(&store, &second).expect_err("held");
833        assert!(
834            refused.to_string().contains("already holds pre-push-lint"),
835            "{refused}"
836        );
837        assert_eq!(store.read().expect("read").len(), 1);
838        std::fs::remove_dir_all(&dir).expect("clean");
839    }
840}