1use std::sync::atomic::{AtomicBool, Ordering};
20
21use crate::attest::{BlockRefusal, SignerBlock};
22use crate::json_read::Value;
23
24use super::super::{
25 capture, in_cluster_signer, judge, last_line, log_line, parse_pod_object, record_token, Call,
26 Fallback, JobEnd, Kube, PodFacts, State, PLATFORM, RUN_LABEL_KEY,
27};
28use super::pending::{GateState, Pending, PendingError, RecordPhase, Store};
29use super::sign::{SIGNER_LABEL, SIGNER_LABEL_VALUE};
30use super::workflow::{check_pod, check_workflow, node_name, template_name, TTL_SECS};
31
32const COLLECT_SECS: u64 = 5;
35const PATCH_SECS: u64 = 10;
37const STOP_SECS: u64 = 30;
38const INTENT_GRACE_SECS: u64 = 600;
43const EXPIRY_SLACK_SECS: u64 = 3600;
46
47static COLLECTED: AtomicBool = AtomicBool::new(false);
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55pub(crate) enum Trouble {
56 Busy,
58 NotReached(String),
60 StoreFailed(PendingError),
62}
63
64impl std::fmt::Display for Trouble {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 match self {
67 Trouble::Busy => write!(f, "another collect is running"),
68 Trouble::NotReached(why) => write!(f, "cluster not reached: {why}"),
69 Trouble::StoreFailed(why) => write!(f, "pending store failed: {why}"),
70 }
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76pub(crate) struct Settled {
77 pub name: String,
78 pub phase: RecordPhase,
80 pub passed: Vec<String>,
81 pub failed: Vec<String>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Default)]
86pub(crate) struct Collected {
87 pub passes: usize,
89 pub pending: usize,
91 pub settled: Vec<Settled>,
93 pub trouble: Option<Trouble>,
94}
95
96impl Collected {
97 fn troubled(trouble: Trouble) -> Collected {
98 Collected {
99 trouble: Some(trouble),
100 ..Collected::default()
101 }
102 }
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
107struct Pass {
108 gate: String,
109 tree: String,
110 token: String,
111 provenance: String,
112}
113
114#[derive(Debug)]
116struct Resolution {
117 record: Pending,
119 leaves: bool,
122 passes: Vec<Pass>,
123 notes: Vec<(String, String)>,
125}
126
127#[derive(Debug, Clone, PartialEq, Eq)]
130enum Signed {
131 Filed(String),
134 NotReady,
136 Refused {
139 refusal: BlockRefusal,
140 namespace: String,
141 },
142 Skipped(String),
144}
145
146type SignerLookup<'a> = Option<&'a mut dyn FnMut(&Pending) -> Signed>;
148
149pub(crate) fn collect() -> Collected {
153 if COLLECTED.swap(true, Ordering::SeqCst) {
154 return Collected::default();
155 }
156 Store::here().map_or_else(Collected::default, |store| collect_from(&store))
157}
158
159fn collect_from(store: &Store) -> Collected {
160 if !store.exists() {
161 return Collected::default();
162 }
163 let Some(held) = store.try_lock() else {
165 return Collected::troubled(Trouble::Busy);
166 };
167 let records = match store.read() {
168 Ok(records) => records,
169 Err(why) => {
170 log_line("collect", &why.to_string());
171 return Collected::troubled(Trouble::StoreFailed(why));
172 }
173 };
174 if records.is_empty() {
175 return Collected::default();
176 }
177 let now = crate::gate_evidence::now();
178 let mut kept: Vec<Pending> = Vec::new();
179 let mut settled: Vec<Settled> = Vec::new();
180 let mut passes = 0;
181 let mut unreached: Vec<String> = Vec::new();
182 let signer_namespace = in_cluster_signer();
184 for group in by_cluster(records) {
185 let kube = Kube {
186 kubeconfig: group[0].kubeconfig.clone(),
187 namespace: group[0].namespace.clone(),
188 };
189 match fetch(&kube, &group) {
190 Ok(list) => {
191 let labels: Vec<String> = group.iter().map(|r| r.label.clone()).collect();
194 let mut configmaps: Option<Result<Value, String>> = None;
195 let mut lookup = |record: &Pending| -> Signed {
196 let Some(namespace) = &signer_namespace else {
197 return Signed::NotReady;
198 };
199 let answer = configmaps.get_or_insert_with(|| {
200 let signer = Kube {
201 kubeconfig: kube.kubeconfig.clone(),
202 namespace: namespace.clone(),
203 };
204 let read = fetch_blocks(&signer, &labels);
205 if let Err(why) = &read {
206 log_line(
207 "collect",
208 &format!("the signer's blocks could not be read: {why}"),
209 );
210 }
211 read
212 });
213 match answer {
214 Ok(list) => match_block(record, list, namespace),
215 Err(_) => Signed::NotReady,
216 }
217 };
218 for mut record in group {
219 let done = if signer_namespace.is_none() {
220 record.awaiting_signer = false;
222 settle(resolve(record, &list, now), None)
223 } else if record.awaiting_signer {
224 settle_awaiting(record, now, &mut lookup)
225 } else {
226 settle(resolve(record, &list, now), Some(&mut lookup))
227 };
228 passes += done.written;
229 settled.extend(done.settled);
230 kept.extend(done.record);
231 }
232 }
233 Err(why) => {
234 log_line("collect", &format!("the cluster could not be read: {why}"));
235 let (old, young): (Vec<Pending>, Vec<Pending>) =
238 group.into_iter().partition(|r| is_expired(r, now));
239 for record in &old {
240 if record.awaiting_signer && signer_namespace.is_some() {
241 unsigned_at_ttl(record);
242 continue;
243 }
244 log_line(
245 record.gates.first().map_or("collect", |g| g.id.as_str()),
246 &format!(
247 "detached {}: older than the Workflow TTL; dropped",
248 record.name
249 ),
250 );
251 }
252 kept.extend(young);
253 unreached.push(format!(
254 "{why} (namespace {}, kubeconfig {})",
255 kube.namespace,
256 kube.kubeconfig.display()
257 ));
258 }
259 }
260 }
261 let trouble = match (store.write(&held, &kept), unreached) {
262 (Err(why), _) => {
263 log_line(
264 "collect",
265 &format!("cluster-pending was not updated: {why}"),
266 );
267 Some(Trouble::StoreFailed(why))
268 }
269 (Ok(()), why) if !why.is_empty() => Some(Trouble::NotReached(why.join("; "))),
271 (Ok(()), _) => None,
272 };
273 Collected {
274 passes,
275 pending: kept.len(),
276 settled,
277 trouble,
278 }
279}
280
281fn is_expired(record: &Pending, now: u64) -> bool {
282 now > record.submitted + TTL_SECS + EXPIRY_SLACK_SECS
283}
284
285pub(crate) fn lists_live(path: &std::path::Path, now: u64) -> Result<bool, String> {
289 let text = match std::fs::read_to_string(path) {
290 Ok(text) => text,
291 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
292 Err(e) => return Err(e.to_string()),
293 };
294 Ok(super::pending::parse_file(&text)?
295 .iter()
296 .any(|record| !is_expired(record, now)))
297}
298
299fn by_cluster(records: Vec<Pending>) -> Vec<Vec<Pending>> {
301 let mut groups: Vec<Vec<Pending>> = Vec::new();
302 for record in records {
303 match groups
304 .iter_mut()
305 .find(|g| g[0].kubeconfig == record.kubeconfig && g[0].namespace == record.namespace)
306 {
307 Some(group) => group.push(record),
308 None => groups.push(vec![record]),
309 }
310 }
311 groups
312}
313
314fn fetch(kube: &Kube, records: &[Pending]) -> Result<Value, String> {
317 let labels: Vec<&str> = records.iter().map(|r| r.label.as_str()).collect();
318 let selector = format!("{RUN_LABEL_KEY} in ({})", labels.join(","));
319 get_json(kube, "workflows,pods", &selector)
320}
321
322fn fetch_blocks(signer: &Kube, labels: &[String]) -> Result<Value, String> {
326 let selector = format!(
327 "{SIGNER_LABEL}={SIGNER_LABEL_VALUE},{RUN_LABEL_KEY} in ({})",
328 labels.join(",")
329 );
330 get_json(signer, "configmaps", &selector)
331}
332
333fn get_json(kube: &Kube, what: &str, selector: &str) -> Result<Value, String> {
334 let mut cmd = kube.command(
335 "--request-timeout=1s",
336 &["get", what, "-l", selector, "-o", "json"],
337 );
338 match capture(&mut cmd, COLLECT_SECS) {
339 Call::Ok(json) => crate::json_read::parse(&json)
340 .ok_or_else(|| "kubectl printed something that is not JSON".to_string()),
341 Call::Refused(e) | Call::NotStarted(e) | Call::TimedOut(e) => Err(last_line(&e)),
342 }
343}
344
345struct Settlement {
347 record: Option<Pending>,
349 written: usize,
351 settled: Option<Settled>,
353}
354
355fn settle(resolution: Resolution, signer: SignerLookup) -> Settlement {
357 settle_with(
358 resolution,
359 |pass| record_token(&pass.tree, &pass.token, &pass.provenance),
360 signer,
361 )
362}
363
364fn settle_with(
375 resolution: Resolution,
376 mut write: impl FnMut(&Pass) -> Result<(), Fallback>,
377 signer: SignerLookup,
378) -> Settlement {
379 let Resolution {
380 mut record,
381 leaves,
382 passes,
383 notes,
384 } = resolution;
385 for (gate, why) in ¬es {
386 log_line(gate, why);
387 }
388 let mut written = 0;
389 let mut unwritten = 0;
390 for pass in &passes {
391 match write(pass) {
392 Ok(()) => {
393 written += 1;
394 if signer.is_none() {
395 say_collected(&pass.gate, &pass.tree);
396 }
397 }
398 Err(why) => {
399 log_line(
400 &pass.gate,
401 &format!("detached: the pass was not recorded: {why}"),
402 );
403 unwritten += 1;
404 for gate in record.gates.iter_mut().filter(|g| g.id == pass.gate) {
405 gate.state = GateState::Waiting;
406 }
407 }
408 }
409 }
410 if !leaves || unwritten > 0 {
411 return Settlement {
412 record: Some(record),
413 written,
414 settled: None,
415 };
416 }
417 if let Some(lookup) = signer {
418 if record.gates.iter().any(|g| g.state == GateState::Passed) {
419 let signed = lookup(&record);
420 if signed == Signed::NotReady {
421 say_signed(&record, &signed);
422 record.awaiting_signer = true;
423 return Settlement {
424 record: Some(record),
425 written,
426 settled: None,
427 };
428 }
429 say_signed(&record, &signed);
430 }
431 }
432 Settlement {
433 written,
434 ..ended(record)
435 }
436}
437
438fn settle_awaiting(
442 record: Pending,
443 now: u64,
444 lookup: &mut dyn FnMut(&Pending) -> Signed,
445) -> Settlement {
446 if is_expired(&record, now) {
447 unsigned_at_ttl(&record);
448 return ended(record);
449 }
450 let signed = lookup(&record);
451 say_signed(&record, &signed);
452 if signed == Signed::NotReady {
453 return Settlement {
454 record: Some(record),
455 written: 0,
456 settled: None,
457 };
458 }
459 ended(record)
460}
461
462fn ended(record: Pending) -> Settlement {
464 let ids = |state: GateState| -> Vec<String> {
465 record
466 .gates
467 .iter()
468 .filter(|g| g.state == state)
469 .map(|g| g.id.clone())
470 .collect()
471 };
472 let settled = Settled {
473 name: record.name.clone(),
474 phase: record.phase,
475 passed: ids(GateState::Passed),
476 failed: ids(GateState::Failed),
477 };
478 Settlement {
479 record: None,
480 written: 0,
481 settled: Some(settled),
482 }
483}
484
485fn passed(record: &Pending) -> impl Iterator<Item = &str> {
487 record
488 .gates
489 .iter()
490 .filter(|g| g.state == GateState::Passed)
491 .map(|g| g.id.as_str())
492}
493
494fn say_collected(gate: &str, tree: &str) {
498 eprintln!(
499 "collected the cluster pass of {} for tree {}",
500 crate::ui::sanitize(gate),
501 short(tree)
502 );
503}
504
505fn say_collected_unsigned(gate: &str, tree: &str, rest: &str) {
509 eprintln!(
510 "collected {} for tree {}; {}",
511 crate::ui::sanitize(gate),
512 short(tree),
513 crate::ui::sanitize(rest)
514 );
515}
516
517fn next_step(record: &Pending, refusal: &BlockRefusal, namespace: &str) -> String {
519 match refusal {
520 BlockRefusal::Signer(_) => {
521 format!("check {} lists cluster-signer@{PLATFORM}", signers_shown())
522 }
523 BlockRefusal::Content(_) => {
524 format!(
525 "see kubectl --kubeconfig {} -n {namespace} get configmap {}",
526 record.kubeconfig.display(),
527 record.name
528 )
529 }
530 }
531}
532
533fn say_signed(record: &Pending, signed: &Signed) {
535 for gate in passed(record) {
536 match signed {
537 Signed::Filed(principal) => {
538 say_collected_unsigned(gate, &record.tree, &format!("signed by {principal}"))
539 }
540 Signed::NotReady => {
541 eprintln!(
542 "signer block for {} not ready; next collect retries",
543 crate::ui::sanitize(gate)
544 );
545 }
546 Signed::Refused { refusal, namespace } => {
547 log_line(
548 gate,
549 &format!(
550 "detached {}: signer block refused: {}",
551 record.name,
552 refusal.reason()
553 ),
554 );
555 say_collected_unsigned(
556 gate,
557 &record.tree,
558 &format!(
559 "signer block refused: {}; the laptop signs it; {}",
560 refusal.reason(),
561 next_step(record, refusal, namespace)
562 ),
563 );
564 }
565 Signed::Skipped(why) => say_collected_unsigned(
566 gate,
567 &record.tree,
568 &format!("signer skipped: {why}; the laptop signs it"),
569 ),
570 }
571 }
572}
573
574fn unsigned_at_ttl(record: &Pending) {
576 for gate in passed(record) {
577 log_line(
578 gate,
579 &format!("detached {}: unsigned: no signer block", record.name),
580 );
581 say_collected_unsigned(
582 gate,
583 &record.tree,
584 "signer block did not arrive before the Workflow TTL; the laptop signs it",
585 );
586 }
587}
588
589fn signers_shown() -> String {
592 crate::attest::default_signers()
593 .or_else(|| {
594 crate::git::stdout(&["rev-parse", "--show-toplevel"])
595 .map(|top| std::path::Path::new(&top).join(".github/allowed_signers"))
596 })
597 .map_or_else(
598 || ".github/allowed_signers".to_string(),
599 |p| shown_from_top(&p),
600 )
601}
602
603fn shown_from_top(path: &std::path::Path) -> String {
606 crate::git::stdout(&["rev-parse", "--show-toplevel"])
607 .and_then(|top| {
608 path.strip_prefix(&top)
609 .ok()
610 .map(|rel| rel.display().to_string())
611 })
612 .unwrap_or_else(|| path.display().to_string())
613}
614
615fn signer_configmap<'a>(record: &Pending, configmaps: &'a Value) -> Option<&'a Value> {
618 configmaps
619 .get("items")
620 .map(Value::items)
621 .unwrap_or(&[])
622 .iter()
623 .find(|cm| {
624 let metadata = cm.get("metadata");
625 let labels = metadata.and_then(|m| m.get("labels"));
626 text(metadata, "name") == Some(record.name.as_str())
627 && text(labels, RUN_LABEL_KEY) == Some(record.label.as_str())
628 && text(labels, SIGNER_LABEL) == Some(SIGNER_LABEL_VALUE)
629 })
630}
631
632fn match_block(record: &Pending, configmaps: &Value, namespace: &str) -> Signed {
636 let Some(cm) = signer_configmap(record, configmaps) else {
637 return Signed::NotReady;
638 };
639 let fields = cm.get("data");
640 let block = text(fields, "block").unwrap_or("");
641 if block.is_empty() {
642 return Signed::Skipped(
643 text(fields, "skipped")
644 .filter(|why| !why.is_empty())
645 .unwrap_or("no reason given")
646 .to_string(),
647 );
648 }
649 let signers = crate::attest::default_signers();
650 let checked = match judge_block(record, block, signers.as_deref()) {
651 Ok(checked) => checked,
652 Err(refusal) => {
653 return Signed::Refused {
654 refusal,
655 namespace: namespace.to_string(),
656 }
657 }
658 };
659 let commit = &record.source.oid;
660 let mut keys = vec![record.tree.as_str()];
661 if !commit.is_empty()
662 && crate::git::succeeds(&["cat-file", "-e", &format!("{commit}^{{commit}}")])
663 {
664 keys.push(commit);
665 }
666 match crate::attest::file_signer_block(&checked.body, &keys) {
667 Ok(()) => Signed::Filed(checked.principal),
668 Err(why) => {
669 log_line(
670 passed(record).next().unwrap_or("collect"),
671 &format!(
672 "detached {}: the signer block could not be filed ({why}); the next collect retries",
673 record.name
674 ),
675 );
676 Signed::NotReady
677 }
678 }
679}
680
681fn judge_block(
686 record: &Pending,
687 block: &str,
688 signers: Option<&std::path::Path>,
689) -> Result<SignerBlock, BlockRefusal> {
690 let Some(signers) = signers else {
691 return Err(BlockRefusal::Signer(
692 "the repository has no allowed_signers".into(),
693 ));
694 };
695 let checked = crate::attest::signer_block(block, &record.tree, signers)?;
696 if !checked.is_publishable() {
699 return Err(BlockRefusal::Content(format!(
700 "a {} block, and this greengate publishes {} notes",
701 checked.names.format,
702 git_attest::format::WRITE.format
703 )));
704 }
705 let missing: Vec<&str> = passed(record)
706 .filter(|g| !checked.gates.iter().any(|named| named == g))
707 .collect();
708 if !missing.is_empty() {
709 return Err(BlockRefusal::Content(format!(
710 "it does not name {}",
711 missing.join(" ")
712 )));
713 }
714 Ok(checked)
715}
716
717fn short(oid: &str) -> &str {
718 oid.get(..8).unwrap_or(oid)
719}
720
721fn text<'a>(v: Option<&'a Value>, key: &str) -> Option<&'a str> {
722 v?.get(key).and_then(Value::as_str)
723}
724
725pub(super) fn kind_of<'a>(list: &'a Value, kind: &'a str) -> impl Iterator<Item = &'a Value> {
726 list.get("items")
727 .map(Value::items)
728 .unwrap_or(&[])
729 .iter()
730 .filter(move |i| text(Some(i), "kind") == Some(kind))
731}
732
733pub(super) fn pod_of<'a>(
737 list: &'a Value,
738 wf: &Value,
739 name: &str,
740 uid: &str,
741 task: &str,
742) -> Option<&'a Value> {
743 let node = node_name(name, task);
744 let recorded = wf
745 .get("status")
746 .and_then(|s| s.get("nodes"))
747 .map(Value::members)
748 .unwrap_or(&[])
749 .iter()
750 .map(|(_, n)| n)
751 .find(|n| {
752 text(Some(n), "name") == Some(node.as_str())
753 && text(Some(n), "type") == Some("Pod")
754 && text(Some(n), "templateName") == Some(template_name(task).as_str())
755 })?;
756 kind_of(list, "Pod").find(|pod| {
757 let metadata = pod.get("metadata");
758 let annotations = metadata.and_then(|m| m.get("annotations"));
759 let owned = metadata
760 .and_then(|m| m.get("ownerReferences"))
761 .map(Value::items)
762 .unwrap_or(&[])
763 .iter()
764 .any(|o| {
765 text(Some(o), "kind") == Some("Workflow")
766 && text(Some(o), "uid") == Some(uid)
767 && text(Some(o), "name") == Some(name)
768 && o.get("controller").is_some_and(Value::is_true)
769 });
770 let node_id = text(annotations, "workflows.argoproj.io/node-id");
773 owned
774 && text(annotations, "workflows.argoproj.io/node-name") == Some(node.as_str())
775 && node_id.is_some()
776 && node_id == text(Some(recorded), "id")
777 })
778}
779
780pub(super) fn end_from_main(main: &State) -> JobEnd {
785 match main {
786 State::Terminated { exit: Some(0), .. } => JobEnd::Complete,
787 State::Terminated { reason, .. } => JobEnd::Failed(if reason.is_empty() {
788 "Error".to_string()
789 } else {
790 reason.clone()
791 }),
792 State::Absent | State::Waiting | State::Running => JobEnd::Running,
793 }
794}
795
796fn unfinished(facts: &PodFacts) -> String {
798 if let Some(w) = facts.fetch.failed() {
799 format!("fetch {w}")
800 } else if let Some(w) = facts.prepare.failed() {
801 format!("prepare {w}")
802 } else {
803 "the pod ended without a verdict from main".to_string()
804 }
805}
806
807fn resolve(record: Pending, list: &Value, now: u64) -> Resolution {
809 let mut notes: Vec<(String, String)> = Vec::new();
810 let wf = kind_of(list, "Workflow").find(|w| {
811 text(w.get("metadata"), "name") == Some(record.name.as_str())
812 && text(
813 w.get("metadata").and_then(|m| m.get("labels")),
814 RUN_LABEL_KEY,
815 ) == Some(record.label.as_str())
816 });
817 let drop_all = |mut record: Pending, why: &str| {
819 let notes = record
820 .waiting()
821 .map(|g| (g.id.clone(), format!("detached {}: {why}", record.name)))
822 .collect();
823 for gate in record
824 .gates
825 .iter_mut()
826 .filter(|g| g.state == GateState::Waiting)
827 {
828 gate.state = GateState::Failed;
829 }
830 record.phase = RecordPhase::Gone;
831 Resolution {
832 record,
833 leaves: true,
834 passes: Vec::new(),
835 notes,
836 }
837 };
838 let Some(wf) = wf else {
839 return if record.uid.is_some() {
840 drop_all(
841 record,
842 "the Workflow is gone (its TTL passed, or it was deleted)",
843 )
844 } else if is_expired(&record, now) || now > record.submitted + INTENT_GRACE_SECS {
845 drop_all(record, "the Workflow never appeared")
846 } else {
847 Resolution {
849 record,
850 leaves: false,
851 passes: Vec::new(),
852 notes,
853 }
854 };
855 };
856 if is_expired(&record, now) {
857 return drop_all(record, "older than the Workflow TTL");
858 }
859 let found_uid = text(wf.get("metadata"), "uid").map(str::to_string);
860 let uid = match (&record.uid, &found_uid) {
861 (Some(saved), Some(found)) if saved == found => saved.clone(),
862 (Some(_), _) => {
863 return drop_all(
864 record,
865 "another Workflow than the one submitted holds the name",
866 )
867 }
868 (None, Some(found)) => match check_workflow(wf, &record) {
869 Ok(()) => found.clone(),
870 Err(why) => {
871 return drop_all(record, &format!("not the Workflow submitted: {why}"));
872 }
873 },
874 (None, None) => return drop_all(record, "the Workflow has no UID"),
875 };
876 let phase = RecordPhase::parse(text(wf.get("status"), "phase").unwrap_or(""));
877 let mut passes: Vec<Pass> = Vec::new();
878 let mut gates = record.gates.clone();
879 for gate in gates.iter_mut().filter(|g| g.state == GateState::Waiting) {
880 let Some(pod) = pod_of(list, wf, &record.name, &uid, &gate.task) else {
881 if phase.finished() {
882 gate.state = GateState::Failed;
883 notes.push((
884 gate.id.clone(),
885 format!(
886 "detached {}: no pod of {} was found ({})",
887 record.name,
888 gate.task,
889 phase.as_str()
890 ),
891 ));
892 }
893 continue;
894 };
895 if let Err(why) = check_pod(pod, gate, &record) {
896 gate.state = GateState::Failed;
897 notes.push((
898 gate.id.clone(),
899 format!(
900 "detached {}: the pod is not the one submitted: {why}",
901 record.name
902 ),
903 ));
904 continue;
905 }
906 let Some(facts) = parse_pod_object(pod, "main") else {
907 if phase.finished() {
908 gate.state = GateState::Failed;
909 notes.push((
910 gate.id.clone(),
911 format!("detached {}: the pod's status cannot be read", record.name),
912 ));
913 }
914 continue;
915 };
916 let end = end_from_main(&facts.gate);
917 if end == JobEnd::Running {
918 if phase.finished() {
919 gate.state = GateState::Failed;
920 notes.push((
921 gate.id.clone(),
922 format!("detached {}: {}", record.name, unfinished(&facts)),
923 ));
924 }
925 continue;
926 }
927 match judge(&end, &facts, &record.tree, gate.prepare.as_deref()) {
928 Ok(image_id) => {
929 gate.state = GateState::Passed;
930 passes.push(Pass {
931 gate: gate.id.clone(),
932 tree: record.tree.clone(),
933 token: gate.token.clone(),
934 provenance: format!(
935 "platform={PLATFORM} image={image_id} job={uid} name={} bundle=0",
936 node_name(&record.name, &gate.task)
937 ),
938 });
939 }
940 Err(fallback) => {
941 gate.state = GateState::Failed;
942 notes.push((
943 gate.id.clone(),
944 format!("detached {}: {}", record.name, fallback),
945 ));
946 }
947 }
948 }
949 let settled = gates.iter().all(|g| g.state != GateState::Waiting);
950 Resolution {
951 leaves: settled || phase.finished(),
952 record: Pending {
953 uid: Some(uid),
954 phase,
955 gates,
956 ..record
957 },
958 passes,
959 notes,
960 }
961}
962
963pub fn collect_command(args: &[std::ffi::OsString]) -> i32 {
967 if args.iter().any(|a| a == "--help" || a == "-h") {
968 println!("usage: {} cluster collect", crate::names::BIN);
969 return 0;
970 }
971 match args.first().and_then(|a| a.to_str()) {
972 Some("collect") if args.len() == 1 => {
973 let done = collect();
974 match &done.trouble {
975 Some(Trouble::Busy) => {
976 eprintln!("{}; nothing was asked of the cluster", Trouble::Busy);
977 0
978 }
979 Some(trouble) => {
980 eprintln!("{trouble}");
981 1
982 }
983 None => {
984 eprintln!(
985 "collected {} cluster pass{}; {} Workflow{} still pending",
986 done.passes,
987 if done.passes == 1 { "" } else { "es" },
988 done.pending,
989 if done.pending == 1 { "" } else { "s" },
990 );
991 0
992 }
993 }
994 }
995 _ => {
996 eprintln!("usage: {} cluster collect", crate::names::BIN);
997 2
998 }
999 }
1000}
1001
1002pub(crate) fn status_lines() -> Vec<String> {
1005 let Some(store) = Store::here() else {
1006 return Vec::new();
1007 };
1008 match store.read() {
1009 Ok(records) => records.iter().map(describe).collect(),
1010 Err(why) => {
1011 eprintln!("cluster run records cannot be read: {why}");
1012 Vec::new()
1013 }
1014 }
1015}
1016
1017pub(crate) fn settled_lines(settled: &[Settled]) -> Vec<String> {
1019 settled
1020 .iter()
1021 .map(|run| {
1022 let mut parts: Vec<String> = Vec::new();
1023 if !run.passed.is_empty() {
1024 parts.push(format!("collected: {}", run.passed.join(" ")));
1025 }
1026 if !run.failed.is_empty() {
1027 parts.push(format!(
1028 "did not pass: {} — see cluster.log; the gate runs at the push",
1029 run.failed.join(" ")
1030 ));
1031 }
1032 format!(
1033 "cluster run {} {}: {}",
1034 run.name,
1035 run.phase.plain(),
1036 parts.join("; ")
1037 )
1038 })
1039 .collect()
1040}
1041
1042fn describe(record: &Pending) -> String {
1043 let named = |label: &str, state: GateState| -> Option<String> {
1044 let ids: Vec<&str> = record
1045 .gates
1046 .iter()
1047 .filter(|g| g.state == state)
1048 .map(|g| g.id.as_str())
1049 .collect();
1050 (!ids.is_empty()).then(|| format!("{label}: {}", ids.join(" ")))
1051 };
1052 let fields: Vec<String> = [
1053 named("collected", GateState::Passed),
1054 named("did not pass", GateState::Failed),
1055 named("waiting", GateState::Waiting),
1056 ]
1057 .into_iter()
1058 .flatten()
1059 .collect();
1060 let follow = if record.phase.finished() {
1061 String::new()
1062 } else {
1063 format!(
1064 " (follow: kubectl -n {} get wf {})",
1065 record.namespace, record.name
1066 )
1067 };
1068 format!(
1069 "cluster run {}: {}{}{follow}",
1070 record.name,
1071 record.phase.plain(),
1072 if fields.is_empty() {
1073 String::new()
1074 } else {
1075 format!(" — {}", fields.join("; "))
1076 }
1077 )
1078}
1079
1080fn terminate_command(record: &Pending) -> String {
1082 format!(
1083 "kubectl --kubeconfig {} -n {} patch workflow {} --type merge -p '{{\"spec\":{{\"shutdown\":\"Terminate\"}}}}'",
1084 shell_quote(&record.kubeconfig.to_string_lossy()),
1085 record.namespace,
1086 record.name
1087 )
1088}
1089
1090fn shell_quote(text: &str) -> String {
1092 format!("'{}'", text.replace('\'', "'\\''"))
1093}
1094
1095#[derive(Debug, Clone, PartialEq, Eq, Default)]
1097pub(crate) struct Stopped {
1098 pub done: Vec<String>,
1100 pub failed: Vec<String>,
1102}
1103
1104pub(crate) fn stop_pending() -> Stopped {
1108 let mut report = Stopped::default();
1109 let Some(store) = Store::here() else {
1110 return report;
1111 };
1112 let records = match store.read() {
1113 Ok(records) => records,
1114 Err(why) => {
1115 report
1116 .failed
1117 .push(format!("cluster run records cannot be read: {why}"));
1118 return report;
1119 }
1120 };
1121 let until = std::time::Instant::now() + std::time::Duration::from_secs(STOP_SECS);
1122 for record in &records {
1123 let left = until.saturating_duration_since(std::time::Instant::now());
1124 if left.is_zero() {
1125 report.failed.push(format!(
1126 "cluster run {} was not attempted: the stop deadline passed — {}",
1127 record.name,
1128 terminate_command(record)
1129 ));
1130 continue;
1131 }
1132 let kube = Kube {
1133 kubeconfig: record.kubeconfig.clone(),
1134 namespace: record.namespace.clone(),
1135 };
1136 let patched = kube.bounded(
1137 &[
1138 "patch",
1139 "workflow",
1140 &record.name,
1141 "--type",
1142 "merge",
1143 "-p",
1144 "{\"spec\":{\"shutdown\":\"Terminate\"}}",
1145 ],
1146 left.as_secs().clamp(1, PATCH_SECS),
1147 );
1148 match patched {
1149 Ok(()) => report
1150 .done
1151 .push(format!("terminating cluster run {}", record.name)),
1152 Err(why) => report.failed.push(format!(
1153 "could not terminate cluster run {}: {why} — {}",
1154 record.name,
1155 terminate_command(record)
1156 )),
1157 }
1158 }
1159 report
1160}
1161
1162#[cfg(test)]
1163pub(in crate::cluster::detached) mod tests {
1164 use super::super::pending::tests::sample;
1165 use super::*;
1166
1167 #[test]
1168 fn judge_block_refuses_a_legacy_block_while_the_written_names_are_green() {
1169 use crate::attest::tests::{block_with, both_names_signer, dir};
1170 use git_attest::format::{GREEN, LEGACY};
1171 let scratch = dir("judge-legacy");
1172 let (key, signers) = both_names_signer(&scratch);
1173 let tree = "0123456789012345678901234567890123456789";
1174 let mut record = sample("wf-legacy");
1175 record.tree = tree.to_string();
1176 let body = block_with(LEGACY.format, LEGACY.namespace, tree, &key);
1177 assert!(crate::attest::signer_block(&body, tree, &signers).is_ok());
1180 match judge_block(&record, &body, Some(&signers)) {
1181 Err(BlockRefusal::Content(why)) => {
1182 assert!(why.contains(LEGACY.format), "{why}");
1183 assert!(why.contains(GREEN.format), "{why}");
1184 }
1185 other => panic!("expected a content refusal, got {other:?}"),
1186 }
1187 let _ = std::fs::remove_dir_all(&scratch); }
1189
1190 #[test]
1191 fn judge_block_accepts_a_green_block() {
1192 use crate::attest::tests::{block_with, both_names_signer, dir};
1193 use git_attest::format::GREEN;
1194 let scratch = dir("judge-green");
1195 let (key, signers) = both_names_signer(&scratch);
1196 let tree = "0123456789012345678901234567890123456789";
1197 let mut record = sample("wf-green");
1198 record.tree = tree.to_string();
1199 let body = block_with(GREEN.format, GREEN.namespace, tree, &key);
1200 let checked = judge_block(&record, &body, Some(&signers)).expect("a green block judges");
1201 assert_eq!(checked.names, GREEN);
1202 let _ = std::fs::remove_dir_all(&scratch); }
1204
1205 #[test]
1206 fn lists_live_skips_a_run_past_its_ttl_and_reads_the_owner_format() {
1207 let dir = std::env::temp_dir().join(format!("greengate-lists-live-{}", std::process::id()));
1208 let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap();
1210 let file = dir.join(super::super::PENDING_FILE);
1211 let now = 1_800_000_000;
1212 assert_eq!(lists_live(&file, now), Ok(false), "no file, no run");
1213 let mut live = super::super::pending::tests::sample("wf-live");
1214 live.submitted = now;
1215 let mut gone = super::super::pending::tests::sample("wf-gone");
1216 gone.submitted = now - TTL_SECS - EXPIRY_SLACK_SECS - 1;
1217 std::fs::write(&file, super::super::pending::render_file(&[gone.clone()])).unwrap();
1218 assert_eq!(
1219 lists_live(&file, now),
1220 Ok(false),
1221 "a run past its TTL is not live"
1222 );
1223 std::fs::write(&file, super::super::pending::render_file(&[gone, live])).unwrap();
1224 assert_eq!(lists_live(&file, now), Ok(true));
1225 std::fs::write(&file, "not json").unwrap();
1226 assert!(lists_live(&file, now).is_err());
1227 }
1228
1229 pub(in crate::cluster::detached) fn fixture(name: &str) -> String {
1230 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1231 .join("../greengate/tests/it/fixtures/argo");
1232 std::fs::read_to_string(dir.join(name)).expect("fixture")
1233 }
1234
1235 pub(in crate::cluster::detached) fn compact(text: &str) -> String {
1238 let (mut out, mut in_string, mut escaped) = (String::new(), false, false);
1239 for c in text.chars() {
1240 if in_string {
1241 out.push(c);
1242 match (escaped, c) {
1243 (true, _) => escaped = false,
1244 (false, '\\') => escaped = true,
1245 (false, '"') => in_string = false,
1246 (false, _) => {}
1247 }
1248 } else if c == '"' {
1249 in_string = true;
1250 out.push(c);
1251 } else if !c.is_whitespace() {
1252 out.push(c);
1253 }
1254 }
1255 out
1256 }
1257
1258 fn list_for(
1262 record: &Pending,
1263 phase: &str,
1264 node_phase: &str,
1265 tweak: impl Fn(String) -> String,
1266 ) -> Value {
1267 let node = node_name(&record.name, "g0");
1268 let pod = compact(&fixture("pod-succeeded.json"))
1269 .replace(
1270 "\"workflows.argoproj.io/node-name\":\"greengate-handrun-pqtbl\"",
1271 &format!("\"workflows.argoproj.io/node-name\":\"{node}\""),
1272 )
1273 .replace(
1274 "\"workflows.argoproj.io/node-id\":\"greengate-handrun-pqtbl\"",
1275 "\"workflows.argoproj.io/node-id\":\"node-g0\"",
1276 )
1277 .replace("greengate-handrun-pqtbl", &record.name)
1278 .replace("b8eb52b7-8ede-4c1f-bd94-9ada529eec97", "uid-1")
1279 .replace("handrun-2", &record.label);
1280 let wf = format!(
1281 "{{\"kind\":\"Workflow\",\"metadata\":{{\"name\":\"{}\",\"uid\":\"uid-1\",\
1282 \"labels\":{{\"greengate.run\":\"{}\"}}}},\"status\":{{\"phase\":\"{phase}\",\
1283 \"nodes\":{{\"node-g0\":{{\"id\":\"node-g0\",\"name\":\"{node}\",\"type\":\"Pod\",\
1284 \"templateName\":\"gate-g0\",\"phase\":\"{node_phase}\"}}}}}}}}",
1285 record.name, record.label
1286 );
1287 let list = format!("{{\"kind\":\"List\",\"items\":[{wf},{}]}}", tweak(pod));
1288 crate::json_read::parse(&list).expect("list json")
1289 }
1290
1291 #[test]
1292 fn a_workflow_phase_is_only_ever_finished_or_not() {
1293 for (phase, finished) in [
1294 ("Succeeded", true),
1295 ("Failed", true),
1296 ("Error", true),
1297 ("Running", false),
1298 ("Pending", false),
1299 ("", false),
1300 ] {
1301 assert_eq!(RecordPhase::parse(phase).finished(), finished, "{phase}");
1302 }
1303 }
1304
1305 #[test]
1308 fn the_end_of_a_pod_comes_from_main_alone() {
1309 let ended = |exit, reason: &str| State::Terminated {
1310 exit: Some(exit),
1311 reason: reason.into(),
1312 message: String::new(),
1313 };
1314 assert_eq!(end_from_main(&ended(0, "Completed")), JobEnd::Complete);
1315 assert_eq!(
1316 end_from_main(&ended(1, "Error")),
1317 JobEnd::Failed("Error".into())
1318 );
1319 assert_eq!(
1320 end_from_main(&ended(137, "OOMKilled")),
1321 JobEnd::Failed("OOMKilled".into())
1322 );
1323 assert_eq!(end_from_main(&State::Running), JobEnd::Running);
1324 assert_eq!(end_from_main(&State::Waiting), JobEnd::Running);
1325 assert_eq!(end_from_main(&State::Absent), JobEnd::Running);
1326 }
1327
1328 fn record_of_the_fixture() -> Pending {
1329 let mut record = sample("greengate-rh-test");
1330 record.uid = Some("uid-1".into());
1331 record.label = "label-1".into();
1332 record.tree = "13b5ee2d54389399fa2738f084a1b653b5844028".into();
1333 record.source.oid = "7e04624939f8c93f774d570276af8643c61f0320".into();
1334 record.gates[0].argv = vec!["python3".into(), "scripts/check-module-cycles.py".into()];
1335 record.gates[0].prepare = None;
1336 record.gates[0].digest =
1337 "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c".into();
1338 record
1339 }
1340
1341 fn collected(record: Pending, list: &Value) -> Resolution {
1342 resolve(record, list, 1_700_000_100)
1343 }
1344
1345 #[test]
1348 fn the_live_fixture_is_a_pass() {
1349 let record = record_of_the_fixture();
1350 let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
1351 let done = collected(record, &list);
1352 assert!(done.notes.is_empty(), "{:?}", done.notes);
1353 assert_eq!(done.passes.len(), 1, "{done:?}");
1354 assert_eq!(
1355 done.passes[0].token, "pre-push-lint@abc",
1356 "the frozen token"
1357 );
1358 assert!(done.passes[0].provenance.contains("platform=x86_64-linux"));
1359 assert!(done.leaves, "a finished Workflow leaves the file");
1360 }
1361
1362 #[test]
1365 fn a_succeeded_node_with_a_failed_main_is_no_pass() {
1366 let record = record_of_the_fixture();
1367 let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1368 p.replacen(
1369 "\"exitCode\":0,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
1370 "\"exitCode\":1,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
1371 1,
1372 )
1373 });
1374 let done = collected(record, &list);
1375 assert!(done.passes.is_empty(), "{done:?}");
1376 assert_eq!(done.notes.len(), 1, "{done:?}");
1377 assert!(done.notes[0].1.contains("exit 1"), "{:?}", done.notes);
1378 }
1379
1380 #[test]
1381 fn a_pod_of_another_workflow_uid_is_not_this_ones() {
1382 let record = record_of_the_fixture();
1383 let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1384 p.replace("\"uid\":\"uid-1\"", "\"uid\":\"uid-other\"")
1385 });
1386 let done = collected(record, &list);
1387 assert!(done.passes.is_empty(), "{done:?}");
1388 }
1389
1390 #[test]
1391 fn a_pod_with_another_image_or_command_is_not_the_submission() {
1392 for tweak in [
1393 |p: String| {
1394 p.replace(
1395 "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c",
1396 &format!("sha256:{}", "0".repeat(64)),
1397 )
1398 },
1399 |p: String| p.replace("scripts/check-module-cycles.py", "scripts/other.py"),
1400 |p: String| {
1401 p.replace(
1402 "tree 13b5ee2d54389399fa2738f084a1b653b5844028",
1403 "tree 0000000000000000000000000000000000000000",
1404 )
1405 },
1406 ] {
1407 let record = record_of_the_fixture();
1408 let list = list_for(&record, "Succeeded", "Succeeded", tweak);
1409 let done = collected(record, &list);
1410 assert!(done.passes.is_empty(), "{done:?}");
1411 assert_eq!(done.notes.len(), 1, "{done:?}");
1412 }
1413 }
1414
1415 #[test]
1416 fn a_running_workflow_keeps_its_waiting_gates() {
1417 let record = record_of_the_fixture();
1418 let list = list_for(&record, "Running", "Running", |p| {
1419 p.replace(
1421 "\"terminated\":{\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
1422 "\"running\":{\"startedAt\":\"t\",\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
1423 )
1424 });
1425 let done = collected(record, &list);
1426 assert!(done.passes.is_empty(), "{done:?}");
1427 assert!(!done.leaves);
1428 assert_eq!(done.record.gates[0].state, GateState::Waiting);
1429 assert_eq!(done.record.phase, RecordPhase::Running);
1430 }
1431
1432 #[test]
1433 fn a_workflow_gone_after_its_ttl_drops_the_record_with_one_note() {
1434 let record = record_of_the_fixture();
1435 let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
1436 let done = collected(record, &empty);
1437 assert!(done.leaves);
1438 assert_eq!(done.record.phase, RecordPhase::Gone);
1439 assert_eq!(done.record.phase.plain(), "gone (TTL passed or deleted)");
1440 assert_eq!(done.notes.len(), 1, "{done:?}");
1441 }
1442
1443 #[test]
1446 fn an_intent_with_no_workflow_waits_then_goes() {
1447 let mut record = record_of_the_fixture();
1448 record.uid = None;
1449 let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
1450 let young = resolve(record.clone(), &empty, record.submitted + 60);
1451 assert!(!young.leaves);
1452 let old = resolve(
1453 record.clone(),
1454 &empty,
1455 record.submitted + INTENT_GRACE_SECS + 1,
1456 );
1457 assert!(old.leaves);
1458 assert_eq!(old.notes.len(), 1);
1459 }
1460
1461 #[test]
1464 fn a_pass_whose_token_cannot_be_written_keeps_the_record() {
1465 let record = record_of_the_fixture();
1466 let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
1467 let refuse = |_: &Pass| Err(Fallback::NotProved("git refused".into()));
1468 let first = settle_with(resolve(record.clone(), &list, 1_700_000_100), refuse, None);
1469 assert_eq!(first.written, 0);
1470 assert!(
1471 first.settled.is_none(),
1472 "the run has not ended for the person"
1473 );
1474 let kept = first.record.expect("the record survives");
1475 assert_eq!(kept.gates[0].state, GateState::Waiting);
1476
1477 let mut tokens = Vec::new();
1478 let second = settle_with(
1479 resolve(kept, &list, 1_700_000_200),
1480 |pass| {
1481 tokens.push(pass.token.clone());
1482 Ok(())
1483 },
1484 None,
1485 );
1486 assert_eq!(second.written, 1);
1487 assert_eq!(tokens, ["pre-push-lint@abc"]);
1488 assert!(second.record.is_none());
1489 let ended = second.settled.expect("now it ends");
1490 assert_eq!(ended.passed, ["pre-push-lint"]);
1491 }
1492
1493 #[test]
1495 fn an_unreadable_pod_status_on_a_finished_workflow_fails_the_gate() {
1496 let record = record_of_the_fixture();
1497 let list = list_for(&record, "Failed", "Failed", |p| {
1498 p.replace(
1499 "\"name\":\"greengate-rh-test\",\"namespace\"",
1500 "\"namex\":\"greengate-rh-test\",\"namespace\"",
1501 )
1502 });
1503 let done = collected(record, &list);
1504 assert!(done.passes.is_empty());
1505 assert_eq!(done.notes.len(), 1, "{done:?}");
1506 assert!(
1507 done.notes[0].1.contains("status cannot be read"),
1508 "{done:?}"
1509 );
1510 }
1511
1512 #[test]
1514 fn a_pod_without_a_node_id_is_not_bound() {
1515 let record = record_of_the_fixture();
1516 let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1517 p.replace(
1518 "workflows.argoproj.io/node-id",
1519 "workflows.argoproj.io/node-idx",
1520 )
1521 });
1522 let done = collected(record, &list);
1523 assert!(done.passes.is_empty(), "{done:?}");
1524 }
1525
1526 #[test]
1527 fn a_record_older_than_the_ttl_expires_whatever_the_cluster_says() {
1528 let record = record_of_the_fixture();
1529 assert!(!is_expired(&record, record.submitted + TTL_SECS));
1530 assert!(is_expired(
1531 &record,
1532 record.submitted + TTL_SECS + EXPIRY_SLACK_SECS + 1
1533 ));
1534 }
1535}