agentmux_srv_core/backend/container_status/
docker_event.rs1use bollard::models::{ContainerSummary, EventMessage, EventMessageTypeEnum};
8
9use super::{AGENT_LABEL, NAME_PREFIX};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Action {
14 Create,
15 Start,
16 Stop,
17 Die,
18 Destroy,
19}
20
21impl Action {
22 fn parse(action: &str) -> Option<Self> {
25 match action {
26 "create" => Some(Self::Create),
27 "start" => Some(Self::Start),
28 "stop" => Some(Self::Stop),
29 "die" => Some(Self::Die),
30 "destroy" => Some(Self::Destroy),
31 _ => None,
32 }
33 }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct DockerEvent {
39 pub action: Action,
40 pub name: String,
41 pub image: String,
42 pub labelled: bool,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Listed {
48 pub name: String,
49 pub image: String,
50 pub running: bool,
51 pub labelled: bool,
52}
53
54pub fn event_from(message: EventMessage) -> Option<DockerEvent> {
56 if message.typ != Some(EventMessageTypeEnum::CONTAINER) {
57 return None;
58 }
59 let action = Action::parse(message.action.as_deref()?)?;
60 let attributes = message.actor?.attributes?;
61 let name = attributes.get("name")?.trim_start_matches('/').to_string();
62 name.starts_with(NAME_PREFIX).then(|| DockerEvent {
63 action,
64 image: attributes.get("image").cloned().unwrap_or_default(),
65 labelled: attributes.contains_key(AGENT_LABEL),
66 name,
67 })
68}
69
70pub fn listed_from(summary: ContainerSummary) -> Option<Listed> {
72 let name = summary.names?.into_iter().map(|n| n.trim_start_matches('/').to_string()).find(|n| n.starts_with(NAME_PREFIX))?;
73 Some(Listed {
74 name,
75 image: summary.image.unwrap_or_default(),
76 running: matches!(summary.state.as_deref(), Some("running" | "paused" | "restarting")),
77 labelled: summary.labels.is_some_and(|l| l.contains_key(AGENT_LABEL)),
78 })
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84 use bollard::models::EventActor;
85 use std::collections::HashMap;
86
87 fn message(action: &str, name: &str, extra: &[(&str, &str)]) -> EventMessage {
88 let mut attributes: HashMap<String, String> = extra.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
89 attributes.insert("name".into(), name.into());
90 attributes.insert("image".into(), "agentmux-agent:1".into());
91 EventMessage {
92 typ: Some(EventMessageTypeEnum::CONTAINER),
93 action: Some(action.into()),
94 actor: Some(EventActor { id: Some("c1".into()), attributes: Some(attributes) }),
95 ..Default::default()
96 }
97 }
98
99 #[test]
100 fn the_five_actions_map_and_the_others_are_left_to_the_list() {
101 for (word, action) in [("create", Action::Create), ("start", Action::Start), ("stop", Action::Stop), ("die", Action::Die), ("destroy", Action::Destroy)] {
102 let e = event_from(message(word, "agentmux-a1", &[])).unwrap();
103 assert_eq!((e.action, e.name.as_str(), e.image.as_str(), e.labelled), (action, "agentmux-a1", "agentmux-agent:1", false));
104 }
105 for word in ["pause", "exec_start: sh", "attach", "kill", "oom"] {
106 assert_eq!(event_from(message(word, "agentmux-a1", &[])), None, "{word}");
107 }
108 }
109
110 #[test]
111 fn only_agent_containers_are_read() {
112 assert_eq!(event_from(message("start", "postgres", &[])), None);
113 assert_eq!(event_from(message("start", "amx-dev-relay", &[])), None);
114 let mut volume = message("start", "agentmux-a1", &[]);
115 volume.typ = Some(EventMessageTypeEnum::VOLUME);
116 assert_eq!(event_from(volume), None);
117 assert!(event_from(message("start", "agentmux-a1", &[(AGENT_LABEL, "a1")])).unwrap().labelled);
118 }
119
120 #[test]
121 fn a_listed_container_says_whether_it_runs_and_carries_the_label() {
122 let summary = |name: &str, state: &str, labelled: bool| ContainerSummary {
123 names: Some(vec![format!("/{name}")]),
124 image: Some("agentmux-agent:1".into()),
125 state: Some(state.into()),
126 labels: labelled.then(|| HashMap::from([(AGENT_LABEL.to_string(), "a1".to_string())])),
127 ..Default::default()
128 };
129 let running = listed_from(summary("agentmux-a1", "running", true)).unwrap();
130 assert_eq!((running.name.as_str(), running.running, running.labelled), ("agentmux-a1", true, true));
131 assert!(!listed_from(summary("agentmux-a1", "exited", false)).unwrap().running);
132 assert!(!listed_from(summary("agentmux-a1", "created", false)).unwrap().running);
133 assert_eq!(listed_from(summary("nginx", "running", false)), None);
134 }
135}