1use serde::{Deserialize, Serialize};
26
27use crate::capability_report::LogsCapabilities;
28
29pub const STANDING_WORK_STATUSES: [&str; 4] = ["active", "paused", "superseded", "revoked"];
34
35pub const ONE_SHOT_WORK_STATUSES: [&str; 9] = [
37 "dispatched",
38 "accepted",
39 "running",
40 "paused",
41 "succeeded",
42 "failed",
43 "timed_out",
44 "canceled",
45 "expired",
46];
47
48pub const AGENT_REPORTABLE_WORK_STATUSES: [&str; 3] = ["running", "succeeded", "failed"];
54
55pub const ONE_SHOT_TERMINAL_STATUSES: [&str; 5] =
57 ["succeeded", "failed", "timed_out", "canceled", "expired"];
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ::jumo_derive::Jumo)]
61#[jumo(kind = "state", domain = "Control", module = "Control.Agent.Work")]
62#[serde(rename_all = "PascalCase")]
63pub enum WorkKind {
64 Standing,
66 OneShot,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ::jumo_derive::Jumo)]
76#[jumo(kind = "struct", domain = "Control", module = "Control.Agent.Work")]
77#[serde(deny_unknown_fields)]
78pub struct StandingWork {
79 pub work_id: String,
80 pub agent_id: String,
81 pub family: String,
83 pub spec: String,
85 pub catalog_version: i64,
87 #[serde(default)]
89 pub proposal_id: Option<String>,
90 pub plan_version: i64,
92 pub effective_from: String,
93 pub status: String,
95 pub updated_by: String,
96 pub updated_at: String,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ::jumo_derive::Jumo)]
101#[jumo(kind = "struct", domain = "Control", module = "Control.Agent.Work")]
102#[serde(deny_unknown_fields)]
103pub struct OneShotWork {
104 pub work_id: String,
105 pub agent_id: String,
106 pub action: String,
108 pub spec: String,
109 pub scheduled_at: String,
111 pub deadline_at: String,
113 pub timeout_seconds: i64,
115 pub interruptible: bool,
117 pub status: String,
119 #[serde(default)]
121 pub paused_at: Option<String>,
122 pub paused_total_seconds: i64,
124 #[serde(default)]
126 pub current_step: Option<String>,
127 #[serde(default)]
128 pub completed_steps: Vec<String>,
129 pub attempt: i64,
131 pub issued_by: String,
132 pub issued_at: String,
133}
134
135impl OneShotWork {
136 pub fn is_outstanding(&self) -> bool {
138 !ONE_SHOT_TERMINAL_STATUSES.contains(&self.status.as_str())
139 }
140
141 pub fn can_pause(&self) -> bool {
146 self.interruptible && matches!(self.status.as_str(), "accepted" | "running")
147 }
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ::jumo_derive::Jumo)]
152#[jumo(kind = "struct", domain = "Control", module = "Control.Agent.Work")]
153#[serde(deny_unknown_fields)]
154pub struct WorkReceipt {
155 pub work_id: String,
156 pub agent_id: String,
157 pub work_kind: WorkKind,
158 pub status: String,
160 pub plan_version: i64,
161 pub created_at: String,
162}
163
164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181#[serde(deny_unknown_fields)]
182pub struct WorkSpec {
183 #[serde(default)]
185 pub units: Vec<WorkSpecUnit>,
186}
187
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
194#[serde(deny_unknown_fields)]
195pub struct WorkSpecUnit {
196 pub unit_id: String,
197 pub capability: String,
199 #[serde(default)]
201 pub rule_ref: String,
202 #[serde(default)]
205 pub requires_privilege: String,
206 #[serde(default)]
207 pub sources: Vec<WorkSpecSource>,
208}
209
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(deny_unknown_fields)]
216pub struct WorkSpecSource {
217 pub kind: String,
218 pub target: String,
219 #[serde(default = "default_multiline")]
225 pub multiline: String,
226 #[serde(default, skip_serializing_if = "Vec::is_empty")]
236 pub exclude_globs: Vec<String>,
237 #[serde(default, skip_serializing_if = "ContainerFilters::is_empty")]
247 pub filters: ContainerFilters,
248 #[serde(default, skip_serializing_if = "Vec::is_empty")]
260 pub drop_if_contains: Vec<String>,
261}
262
263pub const CONTAINER_LOG_ROOT: &str = "/var/log/containers";
268
269#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
283#[serde(deny_unknown_fields)]
284pub struct ContainerFilters {
285 #[serde(default, skip_serializing_if = "Vec::is_empty")]
287 pub namespace_in: Vec<String>,
288 #[serde(default, skip_serializing_if = "Vec::is_empty")]
290 pub pod_not_in: Vec<String>,
291 #[serde(default, skip_serializing_if = "Vec::is_empty")]
299 pub name_in: Vec<String>,
300 #[serde(default, skip_serializing_if = "Vec::is_empty")]
305 pub name_not_in: Vec<String>,
306}
307
308pub const FILTER_NAMESPACE_IN: &str = "namespace_in";
313pub const FILTER_POD_NOT_IN: &str = "pod_not_in";
315pub const FILTER_NAME_IN: &str = "name_in";
317pub const FILTER_NAME_NOT_IN: &str = "name_not_in";
319
320pub const CONTAINER_FILTERS: &[&str] = &[
328 FILTER_NAMESPACE_IN,
329 FILTER_POD_NOT_IN,
330 FILTER_NAME_IN,
331 FILTER_NAME_NOT_IN,
332];
333
334pub const DROP_IF_CONTAINS_SUBSTRING: &str = "substring";
339pub const DROP_IF_CONTAINS_MODES: &[&str] = &[DROP_IF_CONTAINS_SUBSTRING];
341
342pub const DROP_IF_CONTAINS_MAX_ITEMS: usize = 8;
344pub const DROP_IF_CONTAINS_MAX_BYTES: usize = 200;
346
347pub fn validate_drop_if_contains(needles: &[String]) -> Result<(), String> {
352 if needles.len() > DROP_IF_CONTAINS_MAX_ITEMS {
353 return Err(format!(
354 "drop_if_contains 条数过多({},上限 {DROP_IF_CONTAINS_MAX_ITEMS})",
355 needles.len()
356 ));
357 }
358 for (index, needle) in needles.iter().enumerate() {
359 if needle.trim().is_empty() {
360 return Err(format!("drop_if_contains[{index}] 是空串"));
361 }
362 if needle.trim() != needle {
363 return Err(format!("drop_if_contains[{index}] {needle:?} 带首尾空白"));
364 }
365 if needle.chars().any(char::is_control) {
366 return Err(format!("drop_if_contains[{index}] {needle:?} 含控制字符"));
367 }
368 if needle.len() > DROP_IF_CONTAINS_MAX_BYTES {
369 return Err(format!(
370 "drop_if_contains[{index}] 过长({} 字节,上限 {DROP_IF_CONTAINS_MAX_BYTES})",
371 needle.len()
372 ));
373 }
374 if needles[..index].contains(needle) {
375 return Err(format!("drop_if_contains[{index}] {needle:?} 重复"));
376 }
377 }
378 Ok(())
379}
380
381impl ContainerFilters {
382 pub fn is_empty(&self) -> bool {
384 self.namespace_in.is_empty()
385 && self.pod_not_in.is_empty()
386 && self.name_in.is_empty()
387 && self.name_not_in.is_empty()
388 }
389
390 pub fn used_dimensions(&self) -> Vec<&'static str> {
395 let mut used = Vec::new();
396 if !self.namespace_in.is_empty() {
397 used.push(FILTER_NAMESPACE_IN);
398 }
399 if !self.pod_not_in.is_empty() {
400 used.push(FILTER_POD_NOT_IN);
401 }
402 if !self.name_in.is_empty() {
403 used.push(FILTER_NAME_IN);
404 }
405 if !self.name_not_in.is_empty() {
406 used.push(FILTER_NAME_NOT_IN);
407 }
408 used
409 }
410
411 pub fn validate(&self) -> Result<(), String> {
417 for (field, values) in [
418 (FILTER_NAMESPACE_IN, &self.namespace_in),
419 (FILTER_POD_NOT_IN, &self.pod_not_in),
420 (FILTER_NAME_IN, &self.name_in),
421 (FILTER_NAME_NOT_IN, &self.name_not_in),
422 ] {
423 for value in values {
424 if value.trim().is_empty() {
425 return Err(format!("{field} 里有空值"));
426 }
427 if value.trim() != value {
428 return Err(format!("{field} 里 {value:?} 带首尾空白"));
429 }
430 if value.contains(['*', '?', '[', ']']) {
431 return Err(format!(
432 "{field} 里 {value:?} 含通配符(这里是精确名字,不是 pattern)"
433 ));
434 }
435 if value.len() > 253 {
436 return Err(format!("{field} 里 {value:?} 过长(>253)"));
437 }
438 }
439 }
440 Ok(())
441 }
442}
443
444fn default_multiline() -> String {
445 "none".to_string()
446}
447
448impl WorkSpec {
449 pub fn parse(spec: &str) -> Result<Self, serde_json::Error> {
454 serde_json::from_str(spec)
455 }
456
457 pub fn encode(&self) -> Result<String, serde_json::Error> {
460 serde_json::to_string(self)
461 }
462
463 pub fn metric_interval_seconds(&self) -> Option<i64> {
468 self.units
469 .iter()
470 .flat_map(|unit| unit.sources.iter())
471 .filter(|source| source.kind == "MetricInterval")
472 .filter_map(|source| parse_interval_seconds(&source.target))
473 .min()
474 }
475
476 pub fn collects_logs(&self) -> bool {
478 self.units
479 .iter()
480 .any(|unit| unit.capability == "collect_logs")
481 }
482}
483
484pub const EXECUTABLE_SOURCE_KINDS: &[&str] = &["FileGlob", "MetricInterval", "Exporter"];
490
491pub fn has_glob_meta(target: &str) -> bool {
493 target.contains(['*', '?', '['])
494}
495
496pub fn is_explicit_path(target: &str) -> bool {
506 target.starts_with('/') && !has_glob_meta(target)
507}
508
509pub fn is_glob_path(target: &str) -> bool {
515 target.starts_with('/') && has_glob_meta(target) && !target.contains("**")
516}
517
518pub fn is_file_target(target: &str) -> bool {
523 is_explicit_path(target) || is_glob_path(target)
524}
525
526pub fn is_container_log_target(target: &str) -> bool {
535 target.starts_with('/') && target.split('/').any(|segment| segment == "containers")
536}
537
538pub const KERNEL_LOG_EXPORTER: &str = "journalctl-kernel";
547
548pub fn missing_log_capabilities(
566 source: &WorkSpecSource,
567 declared: &LogsCapabilities,
568) -> Option<Vec<String>> {
569 let declared_has = |bucket: &[String], value: &str| bucket.iter().any(|item| item == value);
570 let kind = source.kind.as_str();
571 let target = source.target.as_str();
572
573 match kind {
574 "FileGlob" => {
575 if !is_file_target(target) {
577 return None;
578 }
579 let mut missing = Vec::new();
580 let need = if is_glob_path(target) {
581 FILE_INPUT_GLOB
582 } else {
583 FILE_INPUT_ABSOLUTE_PATH
584 };
585 if !declared_has(&declared.file_inputs, need) {
586 missing.push(format!("file_inputs:{need}"));
587 }
588 if source.multiline != "none"
590 && !declared_has(&declared.multiline_modes, &source.multiline)
591 {
592 missing.push(format!("multiline_modes:{}", source.multiline));
593 }
594 for dimension in source.filters.used_dimensions() {
597 if !declared_has(&declared.filters, dimension) {
598 missing.push(format!("filters:{dimension}"));
599 }
600 }
601 if !source.drop_if_contains.is_empty()
605 && !declared_has(&declared.drop_if_contains, DROP_IF_CONTAINS_SUBSTRING)
606 {
607 missing.push(format!("drop_if_contains:{DROP_IF_CONTAINS_SUBSTRING}"));
608 }
609 Some(missing)
610 }
611 "Exporter" => {
612 let (id, _) = parse_exporter_target(target)?;
613 Some(if declared_has(&declared.exporters, id) {
614 Vec::new()
615 } else {
616 vec![format!("exporters:{id}")]
617 })
618 }
619 _ => None,
620 }
621}
622
623pub const FILE_INPUT_ABSOLUTE_PATH: &str = "absolute-path";
627pub const FILE_INPUT_GLOB: &str = "glob";
629
630pub const MULTILINE_MODES: &[&str] = &["none", "indented", "mysql_slow", "postgres_csv"];
636
637pub const EXPORTER_IDS: &[&str] = &[
645 "journalctl-unit",
646 "journalctl-shutdown",
647 "last-reboot",
648 "nft-ruleset",
649 "iptables-save",
650 "smartctl",
651 "dmesg",
652 "auditd-execve",
653 KERNEL_LOG_EXPORTER,
654];
655
656pub fn parse_exporter_target(target: &str) -> Option<(&str, Option<&str>)> {
661 let (id, arg) = match target.split_once(':') {
662 Some((id, arg)) => (id, Some(arg)),
663 None => (target, None),
664 };
665 let id = id.trim();
666 if id.is_empty() || id.contains(char::is_whitespace) {
667 return None;
668 }
669 Some((id, arg))
670}
671
672pub fn is_known_exporter(target: &str) -> bool {
674 match parse_exporter_target(target) {
675 Some((id, _)) => EXPORTER_IDS.contains(&id),
676 None => false,
677 }
678}
679
680pub fn is_executable_source(kind: &str, target: &str) -> bool {
686 match kind {
687 "FileGlob" => is_file_target(target),
689 "MetricInterval" => true,
691 "Exporter" => is_known_exporter(target),
693 _ => false,
694 }
695}
696
697impl WorkSpecUnit {
698 pub fn file_sources(&self) -> Vec<&WorkSpecSource> {
703 self.sources
704 .iter()
705 .filter(|source| source.kind == "FileGlob")
706 .collect()
707 }
708
709 pub fn unsupported_sources(&self) -> Vec<&WorkSpecSource> {
711 self.sources
712 .iter()
713 .filter(|source| !is_executable_source(&source.kind, &source.target))
714 .collect()
715 }
716
717 pub fn has_executable_source(&self) -> bool {
722 self.sources
723 .iter()
724 .any(|source| is_executable_source(&source.kind, &source.target))
725 }
726}
727
728pub fn parse_interval_seconds(raw: &str) -> Option<i64> {
733 let raw = raw.trim();
734 if let Some(value) = raw.strip_suffix('s') {
735 return value.trim().parse::<i64>().ok().filter(|value| *value > 0);
736 }
737 if let Some(value) = raw.strip_suffix('m') {
738 let minutes = value.trim().parse::<i64>().ok()?;
739 return minutes.checked_mul(60).filter(|value| *value > 0);
743 }
744 None
745}
746
747#[cfg(test)]
748mod tests {
749 use super::*;
750 use crate::capability_report::LogsCapabilities;
751
752 fn one_shot(status: &str, interruptible: bool) -> OneShotWork {
753 OneShotWork {
754 work_id: "work-1".to_string(),
755 agent_id: "agent-1".to_string(),
756 action: "upgrade".to_string(),
757 spec: "0.1.4".to_string(),
758 scheduled_at: "2026-09-23T00:00:00Z".to_string(),
759 deadline_at: "2026-09-24T00:00:00Z".to_string(),
760 timeout_seconds: 600,
761 interruptible,
762 status: status.to_string(),
763 paused_at: None,
764 paused_total_seconds: 0,
765 current_step: None,
766 completed_steps: vec![],
767 attempt: 0,
768 issued_by: "admin".to_string(),
769 issued_at: "2026-09-23T00:00:00Z".to_string(),
770 }
771 }
772
773 #[test]
774 fn terminal_one_shot_work_is_not_outstanding() {
775 for status in ONE_SHOT_TERMINAL_STATUSES {
777 assert!(!one_shot(status, true).is_outstanding(), "{status}");
778 }
779 for status in ["dispatched", "accepted", "running", "paused"] {
780 assert!(one_shot(status, true).is_outstanding(), "{status}");
781 }
782 }
783
784 #[test]
785 fn only_interruptible_running_work_can_pause() {
786 assert!(!one_shot("running", false).can_pause());
788 assert!(!one_shot("dispatched", true).can_pause());
790 assert!(!one_shot("succeeded", true).can_pause());
791 assert!(one_shot("accepted", true).can_pause());
792 assert!(one_shot("running", true).can_pause());
793 }
794
795 #[test]
796 fn work_kind_serializes_as_the_model_names() {
797 assert_eq!(
798 serde_json::to_string(&WorkKind::Standing).expect("serialize"),
799 "\"Standing\""
800 );
801 assert_eq!(
802 serde_json::to_string(&WorkKind::OneShot).expect("serialize"),
803 "\"OneShot\""
804 );
805 }
806
807 #[test]
808 fn only_explicit_absolute_paths_are_collectable_file_targets() {
809 assert!(is_explicit_path("/var/log/install.log"));
812 assert!(!is_explicit_path("/var/log/wifi.log*"));
813 assert!(!is_explicit_path("/Library/Logs/DiagnosticReports/*.ips"));
814 assert!(!is_explicit_path("~/Library/Logs/Homebrew/*"));
815 assert!(!is_explicit_path("relative/app.log"));
816 }
817
818 #[test]
819 fn file_targets_accept_single_level_globs_and_reject_recursion() {
820 assert!(is_glob_path("/var/log/containers/*.log"));
822 assert!(is_glob_path("/var/log/pods/*/*/*.log"));
823 assert!(is_glob_path("/var/lib/postgresql/*/data/log/*.csv"));
824 assert!(is_file_target("/var/log/containers/*.log"));
825 assert!(is_file_target("/var/log/auth.log"));
827 assert!(!is_glob_path("/var/log/**/*.log"));
829 assert!(!is_file_target("/var/log/**/*.log"));
830 assert!(!is_glob_path("~/Library/Logs/*.log"));
832 assert!(!is_file_target("relative/*.log"));
833 assert!(!is_file_target(""));
835 }
836
837 #[test]
838 fn executability_needs_both_a_supported_kind_and_a_supported_target() {
839 assert!(is_executable_source("MetricInterval", "15s"));
841 assert!(is_executable_source("FileGlob", "/var/log/app.log"));
843 assert!(is_executable_source(
844 "FileGlob",
845 "/var/log/containers/*.log"
846 ));
847 assert!(!is_executable_source("FileGlob", "/var/log/**/*.log"));
848 assert!(!is_executable_source("FileGlob", "~/logs/*.log"));
849 assert!(is_executable_source("Exporter", "smartctl"));
851 assert!(is_executable_source("Exporter", "dmesg:panic"));
852 assert!(!is_executable_source("Exporter", "last,lastb"));
853 assert!(!is_executable_source("UnifiedLogPredicate", "syspolicyd"));
855 }
856
857 #[test]
858 fn exporter_targets_split_into_a_known_id_and_an_optional_arg() {
859 assert_eq!(parse_exporter_target("smartctl"), Some(("smartctl", None)));
860 assert_eq!(
861 parse_exporter_target("dmesg:panic"),
862 Some(("dmesg", Some("panic")))
863 );
864 assert_eq!(parse_exporter_target(":panic"), None);
866 assert_eq!(parse_exporter_target(" dm esg"), None);
867 assert!(is_known_exporter("dmesg:nvidia-xid"));
869 assert!(!is_known_exporter("nope"));
870 }
871
872 #[test]
873 fn the_kernel_log_exporter_is_in_the_contract_vocabulary() {
874 assert!(EXPORTER_IDS.contains(&KERNEL_LOG_EXPORTER));
877 assert!(is_known_exporter(KERNEL_LOG_EXPORTER));
878 assert!(is_executable_source("Exporter", KERNEL_LOG_EXPORTER));
879 assert!(!is_known_exporter("journalctl-kernelx"));
881 }
882
883 fn source(kind: &str, target: &str, multiline: &str) -> WorkSpecSource {
887 WorkSpecSource {
888 kind: kind.to_string(),
889 target: target.to_string(),
890 multiline: multiline.to_string(),
891 exclude_globs: Vec::new(),
892 filters: ContainerFilters::default(),
893 drop_if_contains: Vec::new(),
894 }
895 }
896
897 fn container_source(target: &str, filters: ContainerFilters) -> WorkSpecSource {
899 WorkSpecSource {
900 filters,
901 ..source("FileGlob", target, "none")
902 }
903 }
904
905 fn missing(
907 kind: &str,
908 target: &str,
909 multiline: &str,
910 declared: &LogsCapabilities,
911 ) -> Option<Vec<String>> {
912 missing_log_capabilities(&source(kind, target, multiline), declared)
913 }
914
915 fn full_logs() -> LogsCapabilities {
917 LogsCapabilities {
918 file_inputs: vec![
919 FILE_INPUT_ABSOLUTE_PATH.to_string(),
920 FILE_INPUT_GLOB.to_string(),
921 ],
922 multiline_modes: MULTILINE_MODES
923 .iter()
924 .map(|mode| mode.to_string())
925 .collect(),
926 exporters: EXPORTER_IDS.iter().map(|id| id.to_string()).collect(),
927 filters: CONTAINER_FILTERS.iter().map(|di| di.to_string()).collect(),
928 drop_if_contains: DROP_IF_CONTAINS_MODES
929 .iter()
930 .map(|m| m.to_string())
931 .collect(),
932 ..LogsCapabilities::default()
933 }
934 }
935
936 #[test]
937 fn capability_gaps_name_the_bucket_and_value() {
938 let old_agent = LogsCapabilities {
939 file_inputs: vec![FILE_INPUT_ABSOLUTE_PATH.to_string()],
941 ..LogsCapabilities::default()
942 };
943 assert_eq!(
944 missing("FileGlob", "/var/log/app.log", "none", &old_agent),
945 Some(Vec::new())
946 );
947 assert_eq!(
948 missing("FileGlob", "/var/log/app/*.log", "none", &old_agent),
949 Some(vec!["file_inputs:glob".to_string()])
950 );
951 assert_eq!(
953 missing("FileGlob", "/var/log/a.log", "indented", &old_agent),
954 Some(vec!["multiline_modes:indented".to_string()])
955 );
956 assert_eq!(
958 missing("Exporter", KERNEL_LOG_EXPORTER, "none", &old_agent),
959 Some(vec![format!("exporters:{KERNEL_LOG_EXPORTER}")])
960 );
961 assert_eq!(
963 missing("Exporter", "dmesg:panic", "none", &full_logs()),
964 Some(Vec::new())
965 );
966 assert_eq!(
968 missing("FileGlob", "/var/log/containers/*.log", "none", &old_agent),
969 Some(vec!["file_inputs:glob".to_string()])
970 );
971 }
972
973 #[test]
974 fn container_filter_dimensions_are_negotiated_separately() {
975 let before_w2 = LogsCapabilities {
978 filters: Vec::new(),
979 ..full_logs()
980 };
981 let namespace_only = ContainerFilters {
982 namespace_in: vec!["prod".to_string()],
983 pod_not_in: Vec::new(),
984
985 name_in: Vec::new(),
986 name_not_in: Vec::new(),
987 };
988 let target = "/var/log/containers/*.log";
989 assert_eq!(
990 missing_log_capabilities(&container_source(target, namespace_only), &before_w2),
991 Some(vec!["filters:namespace_in".to_string()])
992 );
993 let both = ContainerFilters {
995 namespace_in: vec!["prod".to_string()],
996 pod_not_in: vec!["debug-pod".to_string()],
997
998 name_in: Vec::new(),
999 name_not_in: Vec::new(),
1000 };
1001 assert_eq!(
1002 missing_log_capabilities(&container_source(target, both.clone()), &before_w2),
1003 Some(vec![
1004 "filters:namespace_in".to_string(),
1005 "filters:pod_not_in".to_string(),
1006 ])
1007 );
1008 assert_eq!(
1010 missing_log_capabilities(&container_source(target, both), &full_logs()),
1011 Some(Vec::new())
1012 );
1013 assert_eq!(
1015 ContainerFilters {
1016 namespace_in: vec!["a".to_string()],
1017 pod_not_in: vec!["b".to_string()],
1018
1019 name_in: Vec::new(),
1020 name_not_in: Vec::new(),
1021 }
1022 .used_dimensions(),
1023 vec![FILTER_NAMESPACE_IN, FILTER_POD_NOT_IN]
1024 );
1025 assert!(ContainerFilters::default().used_dimensions().is_empty());
1026 }
1027
1028 #[test]
1029 fn noise_drop_needles_are_a_capability_of_their_own() {
1030 let before_w4 = LogsCapabilities {
1033 drop_if_contains: Vec::new(),
1034 ..full_logs()
1035 };
1036 let mut source = source("FileGlob", "/var/log/auth.log", "none");
1037 source.drop_if_contains = vec!["pam_unix(cron:session)".to_string()];
1038 assert_eq!(
1039 missing_log_capabilities(&source, &before_w4),
1040 Some(vec!["drop_if_contains:substring".to_string()])
1041 );
1042 assert_eq!(
1044 missing_log_capabilities(&source, &full_logs()),
1045 Some(Vec::new())
1046 );
1047 }
1048
1049 #[test]
1050 fn drop_if_contains_is_substring_shaped_and_stays_out_of_the_wire_when_empty() {
1051 let mut source = source("FileGlob", "/var/log/auth.log", "none");
1053 assert!(
1054 !serde_json::to_string(&source)
1055 .expect("serialize")
1056 .contains("drop_if_contains")
1057 );
1058
1059 source.drop_if_contains = vec!["pam_unix(cron:session)".to_string()];
1060 let json = serde_json::to_string(&source).expect("serialize");
1061 assert!(
1062 json.contains(r#""drop_if_contains":["pam_unix(cron:session)"]"#),
1063 "{json}"
1064 );
1065 assert_eq!(
1066 serde_json::from_str::<WorkSpecSource>(&json).expect("parse"),
1067 source
1068 );
1069
1070 assert!(validate_drop_if_contains(&["ok".to_string()]).is_ok());
1072 assert!(validate_drop_if_contains(&[]).is_ok());
1073 for bad in ["", " x", "x ", "line\nbreak", " nul\0"] {
1074 assert!(
1075 validate_drop_if_contains(&[bad.to_string()]).is_err(),
1076 "{bad:?} should be rejected"
1077 );
1078 }
1079 assert!(validate_drop_if_contains(&["x".repeat(DROP_IF_CONTAINS_MAX_BYTES + 1)]).is_err());
1080 let too_many: Vec<String> = (0..=DROP_IF_CONTAINS_MAX_ITEMS)
1081 .map(|i| format!("needle-{i}"))
1082 .collect();
1083 assert!(validate_drop_if_contains(&too_many).is_err());
1084 assert!(validate_drop_if_contains(&["dup".to_string(), "dup".to_string()]).is_err());
1085 }
1086
1087 #[test]
1088 fn the_new_multiline_modes_are_in_the_contract_vocabulary() {
1089 for mode in ["mysql_slow", "postgres_csv"] {
1091 assert!(MULTILINE_MODES.contains(&mode), "{mode}");
1092 }
1093 let old_agent = LogsCapabilities {
1095 multiline_modes: vec!["none".to_string(), "indented".to_string()],
1096 ..full_logs()
1097 };
1098 assert_eq!(
1099 missing(
1100 "FileGlob",
1101 "/var/log/postgresql/x.csv",
1102 "postgres_csv",
1103 &old_agent
1104 ),
1105 Some(vec!["multiline_modes:postgres_csv".to_string()])
1106 );
1107 assert_eq!(
1108 missing(
1109 "FileGlob",
1110 "/var/log/mysql/slow.log",
1111 "mysql_slow",
1112 &old_agent
1113 ),
1114 Some(vec!["multiline_modes:mysql_slow".to_string()])
1115 );
1116 }
1117
1118 #[test]
1119 fn an_exporter_id_outside_the_vocabulary_is_reported_as_missing() {
1120 assert_eq!(
1123 missing("Exporter", "journalctl-kernelx", "none", &full_logs()),
1124 Some(vec!["exporters:journalctl-kernelx".to_string()])
1125 );
1126 assert_eq!(
1128 missing("Exporter", "dmesg:panic", "none", &old_style_logs()),
1129 Some(vec!["exporters:dmesg".to_string()])
1130 );
1131 }
1132
1133 fn old_style_logs() -> LogsCapabilities {
1135 LogsCapabilities {
1136 file_inputs: vec![FILE_INPUT_ABSOLUTE_PATH.to_string()],
1137 exporters: vec!["smartctl".to_string()],
1138 ..LogsCapabilities::default()
1139 }
1140 }
1141
1142 #[test]
1143 fn capability_checks_say_nothing_about_things_they_do_not_own() {
1144 assert_eq!(missing("MetricInterval", "15s", "none", &full_logs()), None);
1146 assert_eq!(missing("FileGlob", "~/a/*.log", "none", &full_logs()), None);
1147 assert_eq!(
1148 missing("UnifiedLogPredicate", "syspolicyd", "none", &full_logs()),
1149 None
1150 );
1151 }
1152
1153 #[test]
1154 fn a_fully_declared_agent_is_missing_nothing_the_contract_calls_executable() {
1155 let full = full_logs();
1158 for target in ["/var/log/a.log", "/var/log/containers/*.log"] {
1159 assert_eq!(
1160 missing("FileGlob", target, "none", &full),
1161 Some(Vec::new()),
1162 "{target}"
1163 );
1164 }
1165 for mode in MULTILINE_MODES {
1166 assert_eq!(
1167 missing("FileGlob", "/var/log/a.log", mode, &full),
1168 Some(Vec::new()),
1169 "{mode}"
1170 );
1171 }
1172 for id in EXPORTER_IDS {
1173 assert_eq!(
1174 missing("Exporter", id, "none", &full),
1175 Some(Vec::new()),
1176 "{id}"
1177 );
1178 }
1179 let filters = ContainerFilters {
1181 namespace_in: vec!["prod".to_string()],
1182 pod_not_in: vec!["debug-pod".to_string()],
1183 name_in: vec!["mysql".to_string()],
1184 name_not_in: vec!["fluent-bit".to_string()],
1185 };
1186 assert_eq!(
1187 filters.used_dimensions(),
1188 CONTAINER_FILTERS,
1189 "`used_dimensions` 与 `CONTAINER_FILTERS` 漂了"
1190 );
1191 assert_eq!(
1192 missing_log_capabilities(
1193 &container_source("/var/log/containers/*.log", filters),
1194 &full
1195 ),
1196 Some(Vec::new())
1197 );
1198 }
1199
1200 #[test]
1201 fn every_filter_dimension_alone_pins_is_empty_serialization_and_capability_name() {
1202 let cases: [(ContainerFilters, &'static str); 4] = [
1209 (
1210 ContainerFilters {
1211 namespace_in: vec!["prod".to_string()],
1212 ..Default::default()
1213 },
1214 FILTER_NAMESPACE_IN,
1215 ),
1216 (
1217 ContainerFilters {
1218 pod_not_in: vec!["debug-pod".to_string()],
1219 ..Default::default()
1220 },
1221 FILTER_POD_NOT_IN,
1222 ),
1223 (
1224 ContainerFilters {
1225 name_in: vec!["mysql".to_string()],
1226 ..Default::default()
1227 },
1228 FILTER_NAME_IN,
1229 ),
1230 (
1231 ContainerFilters {
1232 name_not_in: vec!["fluent-bit".to_string()],
1233 ..Default::default()
1234 },
1235 FILTER_NAME_NOT_IN,
1236 ),
1237 ];
1238 for (filters, dimension) in cases {
1239 assert!(
1240 !filters.is_empty(),
1241 "{dimension} 非空时 is_empty 必须为 false"
1242 );
1243 assert_eq!(filters.used_dimensions(), vec![dimension], "{dimension}");
1244 let json = serde_json::to_value(&filters).expect("serialize");
1245 let object = json.as_object().expect("object");
1246 assert_eq!(
1247 object.keys().map(String::as_str).collect::<Vec<_>>(),
1248 vec![dimension],
1249 "{dimension}:序列化键名必须与能力名逐字一致"
1250 );
1251 assert_eq!(
1252 object[dimension].as_array().map(Vec::len),
1253 Some(1),
1254 "{dimension}:该维的值要完整发出去"
1255 );
1256 }
1257 assert!(ContainerFilters::default().is_empty());
1259 assert_eq!(
1260 serde_json::to_value(ContainerFilters::default()).expect("serialize"),
1261 serde_json::json!({})
1262 );
1263 }
1264
1265 fn spec() -> WorkSpec {
1268 WorkSpec {
1269 units: vec![
1270 WorkSpecUnit {
1271 unit_id: "mac-host-metrics".to_string(),
1272 capability: "collect_metrics".to_string(),
1273 rule_ref: "agent_uplink".to_string(),
1274 requires_privilege: "none".to_string(),
1275 sources: vec![WorkSpecSource {
1276 kind: "MetricInterval".to_string(),
1277 target: "15s".to_string(),
1278 multiline: "none".to_string(),
1279 exclude_globs: Vec::new(),
1280 filters: ContainerFilters::default(),
1281 drop_if_contains: Vec::new(),
1282 }],
1283 },
1284 WorkSpecUnit {
1285 unit_id: "mac-privacy-tcc".to_string(),
1286 capability: "collect_logs".to_string(),
1287 rule_ref: "macos/tcc".to_string(),
1288 requires_privilege: "fda".to_string(),
1289 sources: vec![
1290 WorkSpecSource {
1291 kind: "Exporter".to_string(),
1292 target: "sqlite-snapshot(TCC.db)".to_string(),
1293 multiline: "none".to_string(),
1294 exclude_globs: Vec::new(),
1295 filters: ContainerFilters::default(),
1296 drop_if_contains: Vec::new(),
1297 },
1298 WorkSpecSource {
1299 kind: "FileGlob".to_string(),
1300 target: "/var/log/tccd.log".to_string(),
1302 multiline: "indented".to_string(),
1304 exclude_globs: Vec::new(),
1305 filters: ContainerFilters::default(),
1306 drop_if_contains: Vec::new(),
1307 },
1308 ],
1309 },
1310 ],
1311 }
1312 }
1313
1314 #[test]
1315 fn spec_round_trips_and_reports_what_agentd_can_do() {
1316 let encoded = spec().encode().expect("encode");
1317 let decoded = WorkSpec::parse(&encoded).expect("parse");
1318 assert_eq!(decoded, spec());
1319
1320 assert!(decoded.collects_logs());
1321 assert_eq!(decoded.metric_interval_seconds(), Some(15));
1323 let files = decoded.units[1].file_sources();
1325 assert_eq!(files.len(), 1);
1326 assert_eq!(files[0].target, "/var/log/tccd.log");
1327 assert_eq!(files[0].multiline, "indented");
1328 assert_eq!(decoded.units[1].unsupported_sources().len(), 1);
1329 assert_eq!(decoded.units[1].unsupported_sources()[0].kind, "Exporter");
1330 }
1331
1332 #[test]
1333 fn a_glob_file_source_is_collectable_but_recursive_globs_are_not() {
1334 let mut unit = WorkSpecUnit {
1336 unit_id: "linux-container-stdout".to_string(),
1337 capability: "collect_logs".to_string(),
1338 rule_ref: String::new(),
1339 requires_privilege: "root".to_string(),
1340 sources: vec![WorkSpecSource {
1341 kind: "FileGlob".to_string(),
1342 target: "/var/log/containers/*.log".to_string(),
1343 multiline: "none".to_string(),
1344 exclude_globs: vec!["/var/log/containers/*_kube-system_*.log".to_string()],
1345 filters: ContainerFilters::default(),
1346 drop_if_contains: Vec::new(),
1347 }],
1348 };
1349 assert_eq!(unit.file_sources().len(), 1, "它是一条文件来源");
1350 assert!(unit.unsupported_sources().is_empty());
1351 assert!(unit.has_executable_source());
1352
1353 unit.sources[0].target = "/var/log/**/*.log".to_string();
1355 assert_eq!(unit.unsupported_sources().len(), 1);
1356 assert!(!unit.has_executable_source());
1357 }
1358
1359 #[test]
1360 fn exclude_globs_round_trip_and_stay_out_of_the_wire_when_empty() {
1361 let mut source = WorkSpecSource {
1362 kind: "FileGlob".to_string(),
1363 target: "/var/log/containers/*.log".to_string(),
1364 multiline: "none".to_string(),
1365 exclude_globs: Vec::new(),
1366 filters: ContainerFilters::default(),
1367 drop_if_contains: Vec::new(),
1368 };
1369 assert_eq!(
1371 serde_json::to_string(&source).expect("serialize"),
1372 r#"{"kind":"FileGlob","target":"/var/log/containers/*.log","multiline":"none"}"#
1373 );
1374
1375 source.exclude_globs = vec!["/var/log/containers/*_kube-system_*.log".to_string()];
1376 let json = serde_json::to_string(&source).expect("serialize");
1377 assert_eq!(
1378 serde_json::from_str::<WorkSpecSource>(&json).expect("parse"),
1379 source
1380 );
1381 let old = r#"{"kind":"FileGlob","target":"/a/*"}"#;
1383 let parsed: WorkSpecSource = serde_json::from_str(old).expect("parse legacy source");
1384 assert!(parsed.exclude_globs.is_empty());
1385 assert!(parsed.filters.is_empty());
1386 assert_eq!(parsed.multiline, "none");
1387 }
1388
1389 #[test]
1390 fn container_filters_round_trip_and_stay_out_of_the_wire_when_empty() {
1391 let mut source = WorkSpecSource {
1392 kind: "FileGlob".to_string(),
1393 target: "/var/log/containers/*.log".to_string(),
1394 multiline: "none".to_string(),
1395 exclude_globs: Vec::new(),
1396 filters: ContainerFilters::default(),
1397 drop_if_contains: Vec::new(),
1398 };
1399 let json = serde_json::to_string(&source).expect("serialize");
1401 assert!(!json.contains("filters"), "{json}");
1402
1403 source.filters = ContainerFilters {
1404 namespace_in: vec!["prod".to_string()],
1405 pod_not_in: vec!["debug-pod".to_string()],
1406
1407 name_in: Vec::new(),
1408 name_not_in: Vec::new(),
1409 };
1410 let json = serde_json::to_string(&source).expect("serialize");
1411 assert!(
1412 json.contains(r#""filters":{"namespace_in":["prod"],"pod_not_in":["debug-pod"]}"#),
1413 "{json}"
1414 );
1415 assert_eq!(
1416 serde_json::from_str::<WorkSpecSource>(&json).expect("parse"),
1417 source
1418 );
1419
1420 let half = r#"{"kind":"FileGlob","target":"/var/log/containers/*.log","filters":{"namespace_in":["prod"]}}"#;
1422 let parsed: WorkSpecSource = serde_json::from_str(half).expect("parse half filters");
1423 assert_eq!(parsed.filters.namespace_in, vec!["prod".to_string()]);
1424 assert!(parsed.filters.pod_not_in.is_empty());
1425 }
1426
1427 #[test]
1428 fn an_explicitly_empty_filters_object_is_not_serialized() {
1429 let source = WorkSpecSource {
1432 kind: "FileGlob".to_string(),
1433 target: "/var/log/containers/*.log".to_string(),
1434 multiline: "none".to_string(),
1435 exclude_globs: Vec::new(),
1436 filters: ContainerFilters {
1437 namespace_in: Vec::new(),
1438 pod_not_in: Vec::new(),
1439
1440 name_in: Vec::new(),
1441 name_not_in: Vec::new(),
1442 },
1443 drop_if_contains: Vec::new(),
1444 };
1445 let json = serde_json::to_string(&source).expect("serialize");
1446 assert!(!json.contains("filters"), "{json}");
1447 }
1448
1449 #[test]
1450 fn name_filters_are_a_capability_of_their_own() {
1451 let include = ContainerFilters {
1454 name_in: vec!["mysql".to_string()],
1455 ..ContainerFilters::default()
1456 };
1457 assert_eq!(include.used_dimensions(), vec![FILTER_NAME_IN]);
1458 let exclude = ContainerFilters {
1459 name_not_in: vec!["fluent-bit".to_string()],
1460 ..ContainerFilters::default()
1461 };
1462 assert_eq!(exclude.used_dimensions(), vec![FILTER_NAME_NOT_IN]);
1463
1464 assert!(
1466 ContainerFilters {
1467 name_in: vec!["mysql*".to_string()],
1468 ..ContainerFilters::default()
1469 }
1470 .validate()
1471 .is_err()
1472 );
1473 assert!(
1474 ContainerFilters {
1475 name_not_in: vec![" ".to_string()],
1476 ..ContainerFilters::default()
1477 }
1478 .validate()
1479 .is_err()
1480 );
1481 assert!(include.validate().is_ok());
1482 }
1483
1484 #[test]
1485 fn container_filters_keep_values_verbatim() {
1486 let filters = ContainerFilters {
1489 namespace_in: vec!["Prod".to_string()],
1490 pod_not_in: vec!["debug-pod".to_string()],
1491
1492 name_in: Vec::new(),
1493 name_not_in: Vec::new(),
1494 };
1495 let json = serde_json::to_string(&filters).expect("serialize");
1496 let parsed: ContainerFilters = serde_json::from_str(&json).expect("parse");
1497 assert_eq!(parsed.namespace_in, vec!["Prod".to_string()]);
1498 assert_eq!(parsed.pod_not_in, vec!["debug-pod".to_string()]);
1499 }
1500
1501 #[test]
1502 fn container_filters_reject_unknown_keys() {
1503 assert!(serde_json::from_str::<ContainerFilters>(r#"{"namespaces":["prod"]}"#).is_err());
1506 assert!(serde_json::from_str::<ContainerFilters>(r#"{"namespace_in":["prod"]}"#).is_ok());
1507 }
1508
1509 #[test]
1510 fn container_filters_reject_values_that_can_never_match() {
1511 let ok = |namespace: &[&str], pods: &[&str]| ContainerFilters {
1512 namespace_in: namespace.iter().map(|v| v.to_string()).collect(),
1513 pod_not_in: pods.iter().map(|v| v.to_string()).collect(),
1514
1515 name_in: Vec::new(),
1516 name_not_in: Vec::new(),
1517 };
1518
1519 assert!(
1520 ok(&["prod", "kube-system"], &["debug-pod"])
1521 .validate()
1522 .is_ok()
1523 );
1524 assert!(ok(&[], &[]).is_empty());
1525 assert!(ok(&[""], &[]).validate().is_err());
1527 assert!(ok(&[" prod"], &[]).validate().is_err());
1528 assert!(ok(&["prod*"], &[]).validate().is_err());
1529 assert!(ok(&[], &["debug?pod"]).validate().is_err());
1530 assert!(ok(&[&"x".repeat(254)], &[]).validate().is_err());
1531 }
1532
1533 #[test]
1534 fn a_source_without_multiline_decodes_as_single_line() {
1535 let json = r#"{"units":[{"unit_id":"u","capability":"collect_logs","sources":[{"kind":"FileGlob","target":"/a/*"}]}]}"#;
1538 let spec = WorkSpec::parse(json).expect("parse");
1539 assert_eq!(spec.units[0].sources[0].multiline, "none");
1540 assert_eq!(
1542 spec.encode().expect("encode"),
1543 r#"{"units":[{"unit_id":"u","capability":"collect_logs","rule_ref":"","requires_privilege":"","sources":[{"kind":"FileGlob","target":"/a/*","multiline":"none"}]}]}"#
1544 );
1545 }
1546
1547 #[test]
1548 fn a_broken_spec_is_an_error_not_an_empty_work() {
1549 assert!(WorkSpec::parse("mac-host-metrics").is_err());
1551 assert!(WorkSpec::parse("{").is_err());
1552 assert!(WorkSpec::parse(r#"{"units":[]}"#).unwrap().units.is_empty());
1554 assert_eq!(
1555 WorkSpec::parse(r#"{"units":[]}"#)
1556 .unwrap()
1557 .metric_interval_seconds(),
1558 None
1559 );
1560 }
1561
1562 #[test]
1563 fn interval_parsing_accepts_seconds_and_minutes_only() {
1564 assert_eq!(parse_interval_seconds("15s"), Some(15));
1565 assert_eq!(parse_interval_seconds(" 5s "), Some(5));
1566 assert_eq!(parse_interval_seconds("5m"), Some(300));
1567 assert_eq!(parse_interval_seconds("15"), None);
1569 assert_eq!(parse_interval_seconds("0s"), None);
1570 assert_eq!(parse_interval_seconds(""), None);
1571 }
1572
1573 #[test]
1574 fn interval_parsing_never_overflows_on_huge_values() {
1575 assert_eq!(parse_interval_seconds("922337203685477580m"), None);
1578 assert_eq!(parse_interval_seconds("153722867280912931m"), None);
1579 assert_eq!(parse_interval_seconds("99999999999999999999s"), None);
1581 assert_eq!(parse_interval_seconds("600m"), Some(36_000));
1583 }
1584
1585 #[test]
1586 fn metric_interval_ignores_unparseable_targets_instead_of_treating_them_as_zero() {
1587 let unit = |target: &str| WorkSpecUnit {
1589 unit_id: "u".to_string(),
1590 capability: "collect_metrics".to_string(),
1591 rule_ref: String::new(),
1592 requires_privilege: String::new(),
1593 sources: vec![WorkSpecSource {
1594 kind: "MetricInterval".to_string(),
1595 target: target.to_string(),
1596 multiline: "none".to_string(),
1597 exclude_globs: Vec::new(),
1598 filters: ContainerFilters::default(),
1599 drop_if_contains: Vec::new(),
1600 }],
1601 };
1602 let mixed = WorkSpec {
1603 units: vec![unit("garbage"), unit("30s")],
1604 };
1605 assert_eq!(mixed.metric_interval_seconds(), Some(30));
1606
1607 let all_bad = WorkSpec {
1608 units: vec![unit("nope")],
1609 };
1610 assert_eq!(all_bad.metric_interval_seconds(), None);
1611 }
1612}