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