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 BlockRefusal::StaleSigner(_) => {
531 "roll the attest-signer image to this greengate release".to_string()
532 }
533 }
534}
535
536fn say_signed(record: &Pending, signed: &Signed) {
538 for gate in passed(record) {
539 match signed {
540 Signed::Filed(principal) => {
541 say_collected_unsigned(gate, &record.tree, &format!("signed by {principal}"))
542 }
543 Signed::NotReady => {
544 eprintln!(
545 "signer block for {} not ready; next collect retries",
546 crate::ui::sanitize(gate)
547 );
548 }
549 Signed::Refused { refusal, namespace } => {
550 log_line(
551 gate,
552 &format!(
553 "detached {}: signer block refused: {}",
554 record.name,
555 refusal.reason()
556 ),
557 );
558 say_collected_unsigned(
559 gate,
560 &record.tree,
561 &format!(
562 "signer block refused: {}; the laptop signs it; {}",
563 refusal.reason(),
564 next_step(record, refusal, namespace)
565 ),
566 );
567 }
568 Signed::Skipped(why) => say_collected_unsigned(
569 gate,
570 &record.tree,
571 &format!("signer skipped: {why}; the laptop signs it"),
572 ),
573 }
574 }
575}
576
577fn unsigned_at_ttl(record: &Pending) {
579 for gate in passed(record) {
580 log_line(
581 gate,
582 &format!("detached {}: unsigned: no signer block", record.name),
583 );
584 say_collected_unsigned(
585 gate,
586 &record.tree,
587 "signer block did not arrive before the Workflow TTL; the laptop signs it",
588 );
589 }
590}
591
592fn signers_shown() -> String {
595 crate::attest::default_signers()
596 .or_else(|| {
597 crate::git::stdout(&["rev-parse", "--show-toplevel"])
598 .map(|top| std::path::Path::new(&top).join(".github/allowed_signers"))
599 })
600 .map_or_else(
601 || ".github/allowed_signers".to_string(),
602 |p| shown_from_top(&p),
603 )
604}
605
606fn shown_from_top(path: &std::path::Path) -> String {
609 crate::git::stdout(&["rev-parse", "--show-toplevel"])
610 .and_then(|top| {
611 path.strip_prefix(&top)
612 .ok()
613 .map(|rel| rel.display().to_string())
614 })
615 .unwrap_or_else(|| path.display().to_string())
616}
617
618fn signer_configmap<'a>(record: &Pending, configmaps: &'a Value) -> Option<&'a Value> {
621 configmaps
622 .get("items")
623 .map(Value::items)
624 .unwrap_or(&[])
625 .iter()
626 .find(|cm| {
627 let metadata = cm.get("metadata");
628 let labels = metadata.and_then(|m| m.get("labels"));
629 text(metadata, "name") == Some(record.name.as_str())
630 && text(labels, RUN_LABEL_KEY) == Some(record.label.as_str())
631 && text(labels, SIGNER_LABEL) == Some(SIGNER_LABEL_VALUE)
632 })
633}
634
635fn match_block(record: &Pending, configmaps: &Value, namespace: &str) -> Signed {
639 let Some(cm) = signer_configmap(record, configmaps) else {
640 return Signed::NotReady;
641 };
642 let fields = cm.get("data");
643 let block = text(fields, "block").unwrap_or("");
644 if block.is_empty() {
645 return Signed::Skipped(
646 text(fields, "skipped")
647 .filter(|why| !why.is_empty())
648 .unwrap_or("no reason given")
649 .to_string(),
650 );
651 }
652 let signers = crate::attest::default_signers();
653 let checked = match judge_block(record, block, signers.as_deref()) {
654 Ok(checked) => checked,
655 Err(refusal) => {
656 return Signed::Refused {
657 refusal,
658 namespace: namespace.to_string(),
659 }
660 }
661 };
662 let commit = &record.source.oid;
663 let mut keys = vec![record.tree.as_str()];
664 if !commit.is_empty()
665 && crate::git::succeeds(&["cat-file", "-e", &format!("{commit}^{{commit}}")])
666 {
667 keys.push(commit);
668 }
669 match crate::attest::file_signer_block(&checked.body, &keys) {
670 Ok(()) => Signed::Filed(checked.principal),
671 Err(why) => {
672 log_line(
673 passed(record).next().unwrap_or("collect"),
674 &format!(
675 "detached {}: the signer block could not be filed ({why}); the next collect retries",
676 record.name
677 ),
678 );
679 Signed::NotReady
680 }
681 }
682}
683
684fn judge_block(
689 record: &Pending,
690 block: &str,
691 signers: Option<&std::path::Path>,
692) -> Result<SignerBlock, BlockRefusal> {
693 let Some(signers) = signers else {
694 return Err(BlockRefusal::Signer(
695 "the repository has no allowed_signers".into(),
696 ));
697 };
698 let checked = crate::attest::signer_block(block, &record.tree, signers)?;
701 let missing: Vec<&str> = passed(record)
702 .filter(|g| !checked.gates.iter().any(|named| named == g))
703 .collect();
704 if !missing.is_empty() {
705 return Err(BlockRefusal::Content(format!(
706 "it does not name {}",
707 missing.join(" ")
708 )));
709 }
710 Ok(checked)
711}
712
713fn short(oid: &str) -> &str {
714 oid.get(..8).unwrap_or(oid)
715}
716
717fn text<'a>(v: Option<&'a Value>, key: &str) -> Option<&'a str> {
718 v?.get(key).and_then(Value::as_str)
719}
720
721pub(super) fn kind_of<'a>(list: &'a Value, kind: &'a str) -> impl Iterator<Item = &'a Value> {
722 list.get("items")
723 .map(Value::items)
724 .unwrap_or(&[])
725 .iter()
726 .filter(move |i| text(Some(i), "kind") == Some(kind))
727}
728
729pub(super) fn pod_of<'a>(
733 list: &'a Value,
734 wf: &Value,
735 name: &str,
736 uid: &str,
737 task: &str,
738) -> Option<&'a Value> {
739 let node = node_name(name, task);
740 let recorded = wf
741 .get("status")
742 .and_then(|s| s.get("nodes"))
743 .map(Value::members)
744 .unwrap_or(&[])
745 .iter()
746 .map(|(_, n)| n)
747 .find(|n| {
748 text(Some(n), "name") == Some(node.as_str())
749 && text(Some(n), "type") == Some("Pod")
750 && text(Some(n), "templateName") == Some(template_name(task).as_str())
751 })?;
752 kind_of(list, "Pod").find(|pod| {
753 let metadata = pod.get("metadata");
754 let annotations = metadata.and_then(|m| m.get("annotations"));
755 let owned = metadata
756 .and_then(|m| m.get("ownerReferences"))
757 .map(Value::items)
758 .unwrap_or(&[])
759 .iter()
760 .any(|o| {
761 text(Some(o), "kind") == Some("Workflow")
762 && text(Some(o), "uid") == Some(uid)
763 && text(Some(o), "name") == Some(name)
764 && o.get("controller").is_some_and(Value::is_true)
765 });
766 let node_id = text(annotations, "workflows.argoproj.io/node-id");
769 owned
770 && text(annotations, "workflows.argoproj.io/node-name") == Some(node.as_str())
771 && node_id.is_some()
772 && node_id == text(Some(recorded), "id")
773 })
774}
775
776pub(super) fn end_from_main(main: &State) -> JobEnd {
781 match main {
782 State::Terminated { exit: Some(0), .. } => JobEnd::Complete,
783 State::Terminated { reason, .. } => JobEnd::Failed(if reason.is_empty() {
784 "Error".to_string()
785 } else {
786 reason.clone()
787 }),
788 State::Absent | State::Waiting | State::Running => JobEnd::Running,
789 }
790}
791
792fn unfinished(facts: &PodFacts) -> String {
794 if let Some(w) = facts.fetch.failed() {
795 format!("fetch {w}")
796 } else if let Some(w) = facts.prepare.failed() {
797 format!("prepare {w}")
798 } else {
799 "the pod ended without a verdict from main".to_string()
800 }
801}
802
803fn resolve(record: Pending, list: &Value, now: u64) -> Resolution {
805 let mut notes: Vec<(String, String)> = Vec::new();
806 let wf = kind_of(list, "Workflow").find(|w| {
807 text(w.get("metadata"), "name") == Some(record.name.as_str())
808 && text(
809 w.get("metadata").and_then(|m| m.get("labels")),
810 RUN_LABEL_KEY,
811 ) == Some(record.label.as_str())
812 });
813 let drop_all = |mut record: Pending, why: &str| {
815 let notes = record
816 .waiting()
817 .map(|g| (g.id.clone(), format!("detached {}: {why}", record.name)))
818 .collect();
819 for gate in record
820 .gates
821 .iter_mut()
822 .filter(|g| g.state == GateState::Waiting)
823 {
824 gate.state = GateState::Failed;
825 }
826 record.phase = RecordPhase::Gone;
827 Resolution {
828 record,
829 leaves: true,
830 passes: Vec::new(),
831 notes,
832 }
833 };
834 let Some(wf) = wf else {
835 return if record.uid.is_some() {
836 drop_all(
837 record,
838 "the Workflow is gone (its TTL passed, or it was deleted)",
839 )
840 } else if is_expired(&record, now) || now > record.submitted + INTENT_GRACE_SECS {
841 drop_all(record, "the Workflow never appeared")
842 } else {
843 Resolution {
845 record,
846 leaves: false,
847 passes: Vec::new(),
848 notes,
849 }
850 };
851 };
852 if is_expired(&record, now) {
853 return drop_all(record, "older than the Workflow TTL");
854 }
855 let found_uid = text(wf.get("metadata"), "uid").map(str::to_string);
856 let uid = match (&record.uid, &found_uid) {
857 (Some(saved), Some(found)) if saved == found => saved.clone(),
858 (Some(_), _) => {
859 return drop_all(
860 record,
861 "another Workflow than the one submitted holds the name",
862 )
863 }
864 (None, Some(found)) => match check_workflow(wf, &record) {
865 Ok(()) => found.clone(),
866 Err(why) => {
867 return drop_all(record, &format!("not the Workflow submitted: {why}"));
868 }
869 },
870 (None, None) => return drop_all(record, "the Workflow has no UID"),
871 };
872 let phase = RecordPhase::parse(text(wf.get("status"), "phase").unwrap_or(""));
873 let mut passes: Vec<Pass> = Vec::new();
874 let mut gates = record.gates.clone();
875 for gate in gates.iter_mut().filter(|g| g.state == GateState::Waiting) {
876 let Some(pod) = pod_of(list, wf, &record.name, &uid, &gate.task) else {
877 if phase.finished() {
878 gate.state = GateState::Failed;
879 notes.push((
880 gate.id.clone(),
881 format!(
882 "detached {}: no pod of {} was found ({})",
883 record.name,
884 gate.task,
885 phase.as_str()
886 ),
887 ));
888 }
889 continue;
890 };
891 if let Err(why) = check_pod(pod, gate, &record) {
892 gate.state = GateState::Failed;
893 notes.push((
894 gate.id.clone(),
895 format!(
896 "detached {}: the pod is not the one submitted: {why}",
897 record.name
898 ),
899 ));
900 continue;
901 }
902 let Some(facts) = parse_pod_object(pod, "main") else {
903 if phase.finished() {
904 gate.state = GateState::Failed;
905 notes.push((
906 gate.id.clone(),
907 format!("detached {}: the pod's status cannot be read", record.name),
908 ));
909 }
910 continue;
911 };
912 let end = end_from_main(&facts.gate);
913 if end == JobEnd::Running {
914 if phase.finished() {
915 gate.state = GateState::Failed;
916 notes.push((
917 gate.id.clone(),
918 format!("detached {}: {}", record.name, unfinished(&facts)),
919 ));
920 }
921 continue;
922 }
923 match judge(&end, &facts, &record.tree, gate.prepare.as_deref()) {
924 Ok(image_id) => {
925 gate.state = GateState::Passed;
926 passes.push(Pass {
927 gate: gate.id.clone(),
928 tree: record.tree.clone(),
929 token: gate.token.clone(),
930 provenance: format!(
931 "platform={PLATFORM} image={image_id} job={uid} name={} bundle=0",
932 node_name(&record.name, &gate.task)
933 ),
934 });
935 }
936 Err(fallback) => {
937 gate.state = GateState::Failed;
938 notes.push((
939 gate.id.clone(),
940 format!("detached {}: {}", record.name, fallback),
941 ));
942 }
943 }
944 }
945 let settled = gates.iter().all(|g| g.state != GateState::Waiting);
946 Resolution {
947 leaves: settled || phase.finished(),
948 record: Pending {
949 uid: Some(uid),
950 phase,
951 gates,
952 ..record
953 },
954 passes,
955 notes,
956 }
957}
958
959pub fn collect_command(args: &[std::ffi::OsString]) -> i32 {
963 if args.iter().any(|a| a == "--help" || a == "-h") {
964 println!("usage: {} cluster collect", crate::names::BIN);
965 return 0;
966 }
967 match args.first().and_then(|a| a.to_str()) {
968 Some("collect") if args.len() == 1 => {
969 let done = collect();
970 match &done.trouble {
971 Some(Trouble::Busy) => {
972 eprintln!("{}; nothing was asked of the cluster", Trouble::Busy);
973 0
974 }
975 Some(trouble) => {
976 eprintln!("{trouble}");
977 1
978 }
979 None => {
980 eprintln!(
981 "collected {} cluster pass{}; {} Workflow{} still pending",
982 done.passes,
983 if done.passes == 1 { "" } else { "es" },
984 done.pending,
985 if done.pending == 1 { "" } else { "s" },
986 );
987 0
988 }
989 }
990 }
991 _ => {
992 eprintln!("usage: {} cluster collect", crate::names::BIN);
993 2
994 }
995 }
996}
997
998pub(crate) fn status_lines() -> Vec<String> {
1001 let Some(store) = Store::here() else {
1002 return Vec::new();
1003 };
1004 match store.read() {
1005 Ok(records) => records.iter().map(describe).collect(),
1006 Err(why) => {
1007 eprintln!("cluster run records cannot be read: {why}");
1008 Vec::new()
1009 }
1010 }
1011}
1012
1013pub(crate) fn settled_lines(settled: &[Settled]) -> Vec<String> {
1015 settled
1016 .iter()
1017 .map(|run| {
1018 let mut parts: Vec<String> = Vec::new();
1019 if !run.passed.is_empty() {
1020 parts.push(format!("collected: {}", run.passed.join(" ")));
1021 }
1022 if !run.failed.is_empty() {
1023 parts.push(format!(
1024 "did not pass: {} — see cluster.log; the gate runs at the push",
1025 run.failed.join(" ")
1026 ));
1027 }
1028 format!(
1029 "cluster run {} {}: {}",
1030 run.name,
1031 run.phase.plain(),
1032 parts.join("; ")
1033 )
1034 })
1035 .collect()
1036}
1037
1038fn describe(record: &Pending) -> String {
1039 let named = |label: &str, state: GateState| -> Option<String> {
1040 let ids: Vec<&str> = record
1041 .gates
1042 .iter()
1043 .filter(|g| g.state == state)
1044 .map(|g| g.id.as_str())
1045 .collect();
1046 (!ids.is_empty()).then(|| format!("{label}: {}", ids.join(" ")))
1047 };
1048 let fields: Vec<String> = [
1049 named("collected", GateState::Passed),
1050 named("did not pass", GateState::Failed),
1051 named("waiting", GateState::Waiting),
1052 ]
1053 .into_iter()
1054 .flatten()
1055 .collect();
1056 let follow = if record.phase.finished() {
1057 String::new()
1058 } else {
1059 format!(
1060 " (follow: kubectl -n {} get wf {})",
1061 record.namespace, record.name
1062 )
1063 };
1064 format!(
1065 "cluster run {}: {}{}{follow}",
1066 record.name,
1067 record.phase.plain(),
1068 if fields.is_empty() {
1069 String::new()
1070 } else {
1071 format!(" — {}", fields.join("; "))
1072 }
1073 )
1074}
1075
1076fn terminate_command(record: &Pending) -> String {
1078 format!(
1079 "kubectl --kubeconfig {} -n {} patch workflow {} --type merge -p '{{\"spec\":{{\"shutdown\":\"Terminate\"}}}}'",
1080 shell_quote(&record.kubeconfig.to_string_lossy()),
1081 record.namespace,
1082 record.name
1083 )
1084}
1085
1086fn shell_quote(text: &str) -> String {
1088 format!("'{}'", text.replace('\'', "'\\''"))
1089}
1090
1091#[derive(Debug, Clone, PartialEq, Eq, Default)]
1093pub(crate) struct Stopped {
1094 pub done: Vec<String>,
1096 pub failed: Vec<String>,
1098}
1099
1100pub(crate) fn stop_pending() -> Stopped {
1104 let mut report = Stopped::default();
1105 let Some(store) = Store::here() else {
1106 return report;
1107 };
1108 let records = match store.read() {
1109 Ok(records) => records,
1110 Err(why) => {
1111 report
1112 .failed
1113 .push(format!("cluster run records cannot be read: {why}"));
1114 return report;
1115 }
1116 };
1117 let until = std::time::Instant::now() + std::time::Duration::from_secs(STOP_SECS);
1118 for record in &records {
1119 let left = until.saturating_duration_since(std::time::Instant::now());
1120 if left.is_zero() {
1121 report.failed.push(format!(
1122 "cluster run {} was not attempted: the stop deadline passed — {}",
1123 record.name,
1124 terminate_command(record)
1125 ));
1126 continue;
1127 }
1128 let kube = Kube {
1129 kubeconfig: record.kubeconfig.clone(),
1130 namespace: record.namespace.clone(),
1131 };
1132 let patched = kube.bounded(
1133 &[
1134 "patch",
1135 "workflow",
1136 &record.name,
1137 "--type",
1138 "merge",
1139 "-p",
1140 "{\"spec\":{\"shutdown\":\"Terminate\"}}",
1141 ],
1142 left.as_secs().clamp(1, PATCH_SECS),
1143 );
1144 match patched {
1145 Ok(()) => report
1146 .done
1147 .push(format!("terminating cluster run {}", record.name)),
1148 Err(why) => report.failed.push(format!(
1149 "could not terminate cluster run {}: {why} — {}",
1150 record.name,
1151 terminate_command(record)
1152 )),
1153 }
1154 }
1155 report
1156}
1157
1158#[cfg(test)]
1159pub(in crate::cluster::detached) mod tests {
1160 use super::super::pending::tests::sample;
1161 use super::*;
1162
1163 #[test]
1164 fn judge_block_refuses_a_block_under_the_old_names() {
1165 use crate::attest::tests::{block_with, both_names_signer, dir, OLD_FORMAT, OLD_NAMESPACE};
1166 use greensummit::format::SUMMIT;
1167 let scratch = dir("judge-legacy");
1168 let (key, signers) = both_names_signer(&scratch);
1169 let tree = "0123456789012345678901234567890123456789";
1170 let mut record = sample("wf-legacy");
1171 record.tree = tree.to_string();
1172 let body = block_with(OLD_FORMAT, OLD_NAMESPACE, tree, &key);
1175 match judge_block(&record, &body, Some(&signers)) {
1176 Err(BlockRefusal::StaleSigner(why)) => {
1177 assert!(why.contains(OLD_FORMAT), "{why}");
1178 assert!(why.contains(SUMMIT.format), "{why}");
1179 }
1180 other => panic!("expected a content refusal, got {other:?}"),
1181 }
1182 let _ = std::fs::remove_dir_all(&scratch); }
1184
1185 #[test]
1186 fn a_stale_signer_is_told_to_roll_its_image_not_to_read_the_configmap() {
1187 let record = sample("wf-stale");
1188 let said = next_step(
1189 &record,
1190 &BlockRefusal::StaleSigner("x".into()),
1191 "attest-signer",
1192 );
1193 assert!(said.contains("roll the attest-signer image"), "{said}");
1194 assert!(!said.contains("configmap"), "{said}");
1195 }
1196
1197 #[test]
1198 fn judge_block_accepts_a_greensummit_block() {
1199 use crate::attest::tests::{block_with, both_names_signer, dir};
1200 use greensummit::format::SUMMIT;
1201 let scratch = dir("judge-green");
1202 let (key, signers) = both_names_signer(&scratch);
1203 let tree = "0123456789012345678901234567890123456789";
1204 let mut record = sample("wf-green");
1205 record.tree = tree.to_string();
1206 let body = block_with(SUMMIT.format, SUMMIT.namespace, tree, &key);
1207 let checked =
1208 judge_block(&record, &body, Some(&signers)).expect("a greensummit block judges");
1209 assert_eq!(checked.gates, ["suite"]);
1210 let _ = std::fs::remove_dir_all(&scratch); }
1212
1213 #[test]
1214 fn lists_live_skips_a_run_past_its_ttl_and_reads_the_owner_format() {
1215 let dir = std::env::temp_dir().join(format!("greengate-lists-live-{}", std::process::id()));
1216 let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap();
1218 let file = dir.join(super::super::PENDING_FILE);
1219 let now = 1_800_000_000;
1220 assert_eq!(lists_live(&file, now), Ok(false), "no file, no run");
1221 let mut live = super::super::pending::tests::sample("wf-live");
1222 live.submitted = now;
1223 let mut gone = super::super::pending::tests::sample("wf-gone");
1224 gone.submitted = now - TTL_SECS - EXPIRY_SLACK_SECS - 1;
1225 std::fs::write(&file, super::super::pending::render_file(&[gone.clone()])).unwrap();
1226 assert_eq!(
1227 lists_live(&file, now),
1228 Ok(false),
1229 "a run past its TTL is not live"
1230 );
1231 std::fs::write(&file, super::super::pending::render_file(&[gone, live])).unwrap();
1232 assert_eq!(lists_live(&file, now), Ok(true));
1233 std::fs::write(&file, "not json").unwrap();
1234 assert!(lists_live(&file, now).is_err());
1235 }
1236
1237 pub(in crate::cluster::detached) fn fixture(name: &str) -> String {
1238 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1239 .join("../greengate/tests/it/fixtures/argo");
1240 std::fs::read_to_string(dir.join(name)).expect("fixture")
1241 }
1242
1243 pub(in crate::cluster::detached) fn compact(text: &str) -> String {
1246 let (mut out, mut in_string, mut escaped) = (String::new(), false, false);
1247 for c in text.chars() {
1248 if in_string {
1249 out.push(c);
1250 match (escaped, c) {
1251 (true, _) => escaped = false,
1252 (false, '\\') => escaped = true,
1253 (false, '"') => in_string = false,
1254 (false, _) => {}
1255 }
1256 } else if c == '"' {
1257 in_string = true;
1258 out.push(c);
1259 } else if !c.is_whitespace() {
1260 out.push(c);
1261 }
1262 }
1263 out
1264 }
1265
1266 fn list_for(
1270 record: &Pending,
1271 phase: &str,
1272 node_phase: &str,
1273 tweak: impl Fn(String) -> String,
1274 ) -> Value {
1275 let node = node_name(&record.name, "g0");
1276 let pod = compact(&fixture("pod-succeeded.json"))
1277 .replace(
1278 "\"workflows.argoproj.io/node-name\":\"greengate-handrun-pqtbl\"",
1279 &format!("\"workflows.argoproj.io/node-name\":\"{node}\""),
1280 )
1281 .replace(
1282 "\"workflows.argoproj.io/node-id\":\"greengate-handrun-pqtbl\"",
1283 "\"workflows.argoproj.io/node-id\":\"node-g0\"",
1284 )
1285 .replace("greengate-handrun-pqtbl", &record.name)
1286 .replace("b8eb52b7-8ede-4c1f-bd94-9ada529eec97", "uid-1")
1287 .replace("handrun-2", &record.label);
1288 let wf = format!(
1289 "{{\"kind\":\"Workflow\",\"metadata\":{{\"name\":\"{}\",\"uid\":\"uid-1\",\
1290 \"labels\":{{\"greengate.run\":\"{}\"}}}},\"status\":{{\"phase\":\"{phase}\",\
1291 \"nodes\":{{\"node-g0\":{{\"id\":\"node-g0\",\"name\":\"{node}\",\"type\":\"Pod\",\
1292 \"templateName\":\"gate-g0\",\"phase\":\"{node_phase}\"}}}}}}}}",
1293 record.name, record.label
1294 );
1295 let list = format!("{{\"kind\":\"List\",\"items\":[{wf},{}]}}", tweak(pod));
1296 crate::json_read::parse(&list).expect("list json")
1297 }
1298
1299 #[test]
1300 fn a_workflow_phase_is_only_ever_finished_or_not() {
1301 for (phase, finished) in [
1302 ("Succeeded", true),
1303 ("Failed", true),
1304 ("Error", true),
1305 ("Running", false),
1306 ("Pending", false),
1307 ("", false),
1308 ] {
1309 assert_eq!(RecordPhase::parse(phase).finished(), finished, "{phase}");
1310 }
1311 }
1312
1313 #[test]
1316 fn the_end_of_a_pod_comes_from_main_alone() {
1317 let ended = |exit, reason: &str| State::Terminated {
1318 exit: Some(exit),
1319 reason: reason.into(),
1320 message: String::new(),
1321 };
1322 assert_eq!(end_from_main(&ended(0, "Completed")), JobEnd::Complete);
1323 assert_eq!(
1324 end_from_main(&ended(1, "Error")),
1325 JobEnd::Failed("Error".into())
1326 );
1327 assert_eq!(
1328 end_from_main(&ended(137, "OOMKilled")),
1329 JobEnd::Failed("OOMKilled".into())
1330 );
1331 assert_eq!(end_from_main(&State::Running), JobEnd::Running);
1332 assert_eq!(end_from_main(&State::Waiting), JobEnd::Running);
1333 assert_eq!(end_from_main(&State::Absent), JobEnd::Running);
1334 }
1335
1336 fn record_of_the_fixture() -> Pending {
1337 let mut record = sample("greengate-rh-test");
1338 record.uid = Some("uid-1".into());
1339 record.label = "label-1".into();
1340 record.tree = "13b5ee2d54389399fa2738f084a1b653b5844028".into();
1341 record.source.oid = "7e04624939f8c93f774d570276af8643c61f0320".into();
1342 record.gates[0].argv = vec!["python3".into(), "scripts/check-module-cycles.py".into()];
1343 record.gates[0].prepare = None;
1344 record.gates[0].digest =
1345 "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c".into();
1346 record
1347 }
1348
1349 fn collected(record: Pending, list: &Value) -> Resolution {
1350 resolve(record, list, 1_700_000_100)
1351 }
1352
1353 #[test]
1356 fn the_live_fixture_is_a_pass() {
1357 let record = record_of_the_fixture();
1358 let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
1359 let done = collected(record, &list);
1360 assert!(done.notes.is_empty(), "{:?}", done.notes);
1361 assert_eq!(done.passes.len(), 1, "{done:?}");
1362 assert_eq!(
1363 done.passes[0].token, "pre-push-lint@abc",
1364 "the frozen token"
1365 );
1366 assert!(done.passes[0].provenance.contains("platform=x86_64-linux"));
1367 assert!(done.leaves, "a finished Workflow leaves the file");
1368 }
1369
1370 #[test]
1373 fn a_succeeded_node_with_a_failed_main_is_no_pass() {
1374 let record = record_of_the_fixture();
1375 let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1376 p.replacen(
1377 "\"exitCode\":0,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
1378 "\"exitCode\":1,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
1379 1,
1380 )
1381 });
1382 let done = collected(record, &list);
1383 assert!(done.passes.is_empty(), "{done:?}");
1384 assert_eq!(done.notes.len(), 1, "{done:?}");
1385 assert!(done.notes[0].1.contains("exit 1"), "{:?}", done.notes);
1386 }
1387
1388 #[test]
1389 fn a_pod_of_another_workflow_uid_is_not_this_ones() {
1390 let record = record_of_the_fixture();
1391 let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1392 p.replace("\"uid\":\"uid-1\"", "\"uid\":\"uid-other\"")
1393 });
1394 let done = collected(record, &list);
1395 assert!(done.passes.is_empty(), "{done:?}");
1396 }
1397
1398 #[test]
1399 fn a_pod_with_another_image_or_command_is_not_the_submission() {
1400 for tweak in [
1401 |p: String| {
1402 p.replace(
1403 "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c",
1404 &format!("sha256:{}", "0".repeat(64)),
1405 )
1406 },
1407 |p: String| p.replace("scripts/check-module-cycles.py", "scripts/other.py"),
1408 |p: String| {
1409 p.replace(
1410 "tree 13b5ee2d54389399fa2738f084a1b653b5844028",
1411 "tree 0000000000000000000000000000000000000000",
1412 )
1413 },
1414 ] {
1415 let record = record_of_the_fixture();
1416 let list = list_for(&record, "Succeeded", "Succeeded", tweak);
1417 let done = collected(record, &list);
1418 assert!(done.passes.is_empty(), "{done:?}");
1419 assert_eq!(done.notes.len(), 1, "{done:?}");
1420 }
1421 }
1422
1423 #[test]
1424 fn a_running_workflow_keeps_its_waiting_gates() {
1425 let record = record_of_the_fixture();
1426 let list = list_for(&record, "Running", "Running", |p| {
1427 p.replace(
1429 "\"terminated\":{\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
1430 "\"running\":{\"startedAt\":\"t\",\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
1431 )
1432 });
1433 let done = collected(record, &list);
1434 assert!(done.passes.is_empty(), "{done:?}");
1435 assert!(!done.leaves);
1436 assert_eq!(done.record.gates[0].state, GateState::Waiting);
1437 assert_eq!(done.record.phase, RecordPhase::Running);
1438 }
1439
1440 #[test]
1441 fn a_workflow_gone_after_its_ttl_drops_the_record_with_one_note() {
1442 let record = record_of_the_fixture();
1443 let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
1444 let done = collected(record, &empty);
1445 assert!(done.leaves);
1446 assert_eq!(done.record.phase, RecordPhase::Gone);
1447 assert_eq!(done.record.phase.plain(), "gone (TTL passed or deleted)");
1448 assert_eq!(done.notes.len(), 1, "{done:?}");
1449 }
1450
1451 #[test]
1454 fn an_intent_with_no_workflow_waits_then_goes() {
1455 let mut record = record_of_the_fixture();
1456 record.uid = None;
1457 let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
1458 let young = resolve(record.clone(), &empty, record.submitted + 60);
1459 assert!(!young.leaves);
1460 let old = resolve(
1461 record.clone(),
1462 &empty,
1463 record.submitted + INTENT_GRACE_SECS + 1,
1464 );
1465 assert!(old.leaves);
1466 assert_eq!(old.notes.len(), 1);
1467 }
1468
1469 #[test]
1472 fn a_pass_whose_token_cannot_be_written_keeps_the_record() {
1473 let record = record_of_the_fixture();
1474 let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
1475 let refuse = |_: &Pass| Err(Fallback::NotProved("git refused".into()));
1476 let first = settle_with(resolve(record.clone(), &list, 1_700_000_100), refuse, None);
1477 assert_eq!(first.written, 0);
1478 assert!(
1479 first.settled.is_none(),
1480 "the run has not ended for the person"
1481 );
1482 let kept = first.record.expect("the record survives");
1483 assert_eq!(kept.gates[0].state, GateState::Waiting);
1484
1485 let mut tokens = Vec::new();
1486 let second = settle_with(
1487 resolve(kept, &list, 1_700_000_200),
1488 |pass| {
1489 tokens.push(pass.token.clone());
1490 Ok(())
1491 },
1492 None,
1493 );
1494 assert_eq!(second.written, 1);
1495 assert_eq!(tokens, ["pre-push-lint@abc"]);
1496 assert!(second.record.is_none());
1497 let ended = second.settled.expect("now it ends");
1498 assert_eq!(ended.passed, ["pre-push-lint"]);
1499 }
1500
1501 #[test]
1503 fn an_unreadable_pod_status_on_a_finished_workflow_fails_the_gate() {
1504 let record = record_of_the_fixture();
1505 let list = list_for(&record, "Failed", "Failed", |p| {
1506 p.replace(
1507 "\"name\":\"greengate-rh-test\",\"namespace\"",
1508 "\"namex\":\"greengate-rh-test\",\"namespace\"",
1509 )
1510 });
1511 let done = collected(record, &list);
1512 assert!(done.passes.is_empty());
1513 assert_eq!(done.notes.len(), 1, "{done:?}");
1514 assert!(
1515 done.notes[0].1.contains("status cannot be read"),
1516 "{done:?}"
1517 );
1518 }
1519
1520 #[test]
1522 fn a_pod_without_a_node_id_is_not_bound() {
1523 let record = record_of_the_fixture();
1524 let list = list_for(&record, "Succeeded", "Succeeded", |p| {
1525 p.replace(
1526 "workflows.argoproj.io/node-id",
1527 "workflows.argoproj.io/node-idx",
1528 )
1529 });
1530 let done = collected(record, &list);
1531 assert!(done.passes.is_empty(), "{done:?}");
1532 }
1533
1534 #[test]
1535 fn a_record_older_than_the_ttl_expires_whatever_the_cluster_says() {
1536 let record = record_of_the_fixture();
1537 assert!(!is_expired(&record, record.submitted + TTL_SECS));
1538 assert!(is_expired(
1539 &record,
1540 record.submitted + TTL_SECS + EXPIRY_SLACK_SECS + 1
1541 ));
1542 }
1543}