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