1use serde::Serialize;
15
16use crate::backend::storage::cron::CronJob;
17pub use crate::backend::work_claims::holds_claim;
18pub(crate) use crate::backend::work_claims::claims_held_by;
19use crate::server::AppState;
20
21#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
24pub struct ProcessEntry {
25 pub pid: u32,
26 pub command: String,
27 pub started_at_ms: u64,
30}
31
32#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
34pub struct BackgroundTaskEntry {
35 pub id: String,
36 pub label: String,
37 pub pid: Option<i64>,
38 pub started_at_ms: i64,
40 pub last_seen_ms: i64,
42}
43
44#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
46pub struct ShellEntry {
47 pub shell_id: String,
48 pub cmd: String,
49}
50
51#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
53pub struct AgentResources {
54 pub block_id: String,
55 pub processes: Vec<ProcessEntry>,
57 pub background_tasks: Vec<BackgroundTaskEntry>,
59 pub shell_sessions: Vec<ShellEntry>,
61 pub sub_blocks: Vec<String>,
63 pub container: Option<String>,
65 pub cwd: String,
68}
69
70#[derive(Clone, Debug, Default)]
73pub struct AgentIdentity {
74 pub agent_id: String,
75 pub uid: Option<String>,
76}
77
78impl AgentIdentity {
79 pub fn of(state: &AppState, block_id: &str) -> Self {
81 let reg = state.reactive_handler.get_agent_by_block(block_id);
82 Self {
83 agent_id: reg.as_ref().map(|a| a.agent_id.clone()).unwrap_or_default(),
84 uid: reg.and_then(|a| a.uid),
85 }
86 }
87
88 pub fn label(&self, block_id: &str) -> String {
90 if self.agent_id.is_empty() { block_id.to_string() } else { self.agent_id.clone() }
91 }
92}
93
94pub fn snapshot(state: &AppState, block_id: &str) -> AgentResources {
98 let mut processes: Vec<ProcessEntry> = state
99 .process_tracker
100 .list_block(block_id)
101 .into_iter()
102 .map(|p| ProcessEntry { pid: p.pid, command: p.command, started_at_ms: p.started_at_ms })
103 .collect();
104 let missing: Vec<u32> = processes.iter().filter(|p| p.started_at_ms == 0).map(|p| p.pid).collect();
107 if !missing.is_empty() {
108 let times = start_times(&missing);
109 processes.retain_mut(|p| {
112 if p.started_at_ms == 0 {
113 match times.get(&p.pid) {
114 Some(t) => p.started_at_ms = *t,
115 None => return false,
116 }
117 }
118 true
119 });
120 }
121 let background_tasks = state
122 .mstore
123 .background_task_list_for_block(block_id)
124 .unwrap_or_default()
125 .into_iter()
126 .filter(|t| t.ended_at_ms.is_none())
127 .map(|t| BackgroundTaskEntry { id: t.id, label: t.label, pid: t.pid, started_at_ms: t.started_at_ms, last_seen_ms: t.last_seen_ms })
128 .collect();
129 let shell_sessions = state
130 .shell_sessions
131 .list_active()
132 .into_iter()
133 .filter(|s| s.block_id == block_id)
134 .map(|s| ShellEntry { shell_id: s.shell_id, cmd: s.cmd })
135 .collect();
136 let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten();
137 let container = block.as_ref().and_then(container_of);
138 let cwd = block
139 .as_ref()
140 .map(|b| crate::backend::obj::meta_get_string(&b.meta, "cmd:cwd", ""))
141 .unwrap_or_default();
142 let sub_blocks = block.and_then(|b| b.subblockids).unwrap_or_default();
143 AgentResources { block_id: block_id.to_string(), processes, background_tasks, shell_sessions, sub_blocks, container, cwd }
144}
145
146pub fn container_of(block: &crate::backend::obj::Block) -> Option<String> {
149 crate::backend::container::container_of_meta(&block.meta)
150}
151
152pub fn container_shared(state: &AppState, block_id: &str, container: &str) -> bool {
155 crate::backend::blockcontroller::get_all_controllers()
156 .into_keys()
157 .filter(|id| id != block_id)
158 .filter_map(|id| state.mstore.get::<crate::backend::obj::Block>(&id).ok().flatten())
159 .any(|b| container_of(&b).as_deref() == Some(container))
160}
161
162pub fn start_times(pids: &[u32]) -> std::collections::HashMap<u32, u64> {
166 if pids.is_empty() {
167 return Default::default();
168 }
169 let list: Vec<sysinfo::Pid> = pids.iter().map(|p| sysinfo::Pid::from_u32(*p)).collect();
170 let mut sys = sysinfo::System::new();
171 sys.refresh_processes_specifics(
172 sysinfo::ProcessesToUpdate::Some(&list),
173 true,
174 sysinfo::ProcessRefreshKind::nothing(),
175 );
176 sys.processes().iter().map(|(pid, p)| (pid.as_u32(), p.start_time() * 1000)).collect()
177}
178
179pub fn survivors(before: &[ProcessEntry]) -> Vec<ProcessEntry> {
183 let pids: Vec<u32> = before.iter().map(|p| p.pid).collect();
184 let live = start_times(&pids);
185 before
186 .iter()
187 .filter(|p| live.get(&p.pid).is_some_and(|now| same_start(p.started_at_ms, *now)))
188 .cloned()
189 .collect()
190}
191
192pub fn live_background_pids(tasks: &[BackgroundTaskEntry]) -> Vec<u32> {
201 let pids: Vec<u32> = tasks.iter().filter_map(|t| t.pid.and_then(|p| u32::try_from(p).ok())).filter(|p| *p > 1).collect();
202 let live = start_times(&pids);
203 tasks
204 .iter()
205 .filter_map(|t| {
206 let pid = u32::try_from(t.pid?).ok()?;
207 let started = *live.get(&pid)?;
208 (started <= (t.last_seen_ms.max(t.started_at_ms).max(0) as u64) + 1_000).then_some(pid)
210 })
211 .collect()
212}
213
214pub fn force_kill_tree(pid: u32, started_at_ms: u64) -> usize {
219 let mut sys = sysinfo::System::new();
220 sys.refresh_processes_specifics(sysinfo::ProcessesToUpdate::All, true, sysinfo::ProcessRefreshKind::nothing());
221 let root = sysinfo::Pid::from_u32(pid);
222 match sys.process(root) {
223 Some(p) if same_start(started_at_ms, p.start_time() * 1000) => {}
224 _ => return 0, }
226 let procs: Vec<ProcLink> = sys.processes().iter().map(|(id, p)| (id.as_u32(), p.parent().map(|pp| pp.as_u32()), p.start_time())).collect();
227 tree_of(pid, &procs)
229 .iter()
230 .rev()
231 .filter(|id| {
232 sys.process(sysinfo::Pid::from_u32(**id)).is_some_and(|p| p.kill_with(sysinfo::Signal::Kill).unwrap_or_else(|| p.kill()))
233 })
234 .count()
235}
236
237type ProcLink = (u32, Option<u32>, u64);
240
241fn tree_of(root: u32, procs: &[ProcLink]) -> Vec<u32> {
249 let started: std::collections::HashMap<u32, u64> = procs.iter().map(|(pid, _, start)| (*pid, *start)).collect();
250 let mut tree = vec![root];
251 let mut i = 0;
252 while i < tree.len() {
253 let parent = tree[i];
254 let parent_start = started.get(&parent).copied().unwrap_or(0);
255 let children: Vec<u32> = procs
256 .iter()
257 .filter(|(pid, names, start)| *names == Some(parent) && (*start == 0 || *start >= parent_start) && !tree.contains(pid))
258 .map(|(pid, _, _)| *pid)
259 .collect();
260 tree.extend(children);
261 i += 1;
262 }
263 tree
264}
265
266fn same_start(recorded_ms: u64, now_ms: u64) -> bool {
268 recorded_ms == 0 || recorded_ms.abs_diff(now_ms) <= 1000
269}
270
271pub fn cron_targets(target: &str, target_uid: &str, agent_id: &str, uid: Option<&str>) -> bool {
276 match uid.filter(|u| !u.is_empty()) {
277 Some(u) if !target_uid.is_empty() => target_uid == u,
278 _ => !agent_id.is_empty() && target.eq_ignore_ascii_case(agent_id),
279 }
280}
281
282pub(crate) fn crons_targeting(jobs: &[CronJob], agent_id: &str, uid: Option<&str>) -> Vec<String> {
284 jobs.iter()
285 .filter(|j| cron_targets(&j.target, &j.target_uid, agent_id, uid))
286 .map(|j| j.name.clone())
287 .collect()
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293
294 #[test]
295 fn a_live_process_survives_and_a_reused_pid_does_not() {
296 let me = std::process::id();
297 let started = *start_times(&[me]).get(&me).expect("this process is running");
298 assert!(started > 0);
299 let entry = |started_at_ms| ProcessEntry { pid: me, command: "test".into(), started_at_ms };
300 assert_eq!(survivors(&[entry(started)]).len(), 1, "same pid, same start: still running");
301 assert_eq!(survivors(&[entry(0)]).len(), 1, "unknown start time: judged by pid");
302 assert!(survivors(&[entry(started - 60_000)]).is_empty(), "same pid, other start: a reused pid");
303 }
304
305 #[test]
306 fn a_background_task_pid_counts_only_while_it_is_that_task() {
307 let me = std::process::id();
308 let started = *start_times(&[me]).get(&me).unwrap() as i64;
309 let task = |started_at_ms, last_seen_ms| BackgroundTaskEntry {
310 id: "t".into(),
311 label: "task dev".into(),
312 pid: Some(me as i64),
313 started_at_ms,
314 last_seen_ms,
315 };
316 assert_eq!(live_background_pids(&[task(started + 500, started + 500)]), vec![me], "seen just after it started");
317 assert_eq!(
318 live_background_pids(&[task(started - 60_000, started + 10_000)]),
319 vec![me],
320 "declared a minute before it started (a permission prompt), seen running since: still the task"
321 );
322 assert!(
323 live_background_pids(&[task(started - 60_000, started - 30_000)]).is_empty(),
324 "last seen before this process started: the PID was reused"
325 );
326 let no_pid = BackgroundTaskEntry { pid: None, ..task(started, started) };
327 assert!(live_background_pids(&[no_pid]).is_empty());
328 }
329
330 #[test]
331 fn a_tree_is_the_root_and_what_it_started_parents_first() {
332 let procs = [(10, Some(1), 100), (4, Some(10), 100), (5, Some(10), 101), (6, Some(5), 102), (7, Some(1), 90)];
334 let tree = tree_of(10, &procs);
335 assert_eq!(tree[0], 10);
336 let place = |pid: u32| tree.iter().position(|p| *p == pid).unwrap_or_else(|| panic!("{pid} is not in {tree:?}"));
337 assert!(place(5) < place(6), "a parent comes before its child: {tree:?}");
338 assert_eq!(tree.len(), 4, "{tree:?}");
339 assert_eq!(tree_of(99, &procs), vec![99]);
341 }
342
343 #[test]
346 fn a_process_that_started_before_the_parent_it_names_is_not_its_child() {
347 let procs = [(20, Some(1), 500), (30, Some(20), 100), (31, Some(30), 150), (21, Some(20), 500), (22, Some(20), 0)];
350 let mut tree = tree_of(20, &procs);
351 tree.sort_unstable();
352 assert_eq!(tree, vec![20, 21, 22]);
353 }
354
355 #[test]
357 fn processes_that_name_each_other_as_parent_are_walked_once() {
358 let procs = [(40, Some(41), 100), (41, Some(40), 100), (42, Some(42), 100)];
359 let mut tree = tree_of(40, &procs);
360 tree.sort_unstable();
361 assert_eq!(tree, vec![40, 41]);
362 assert_eq!(tree_of(42, &procs), vec![42], "a process that names itself");
363 }
364
365 #[test]
368 fn force_kill_tree_takes_the_child_too() {
369 use std::time::{Duration, Instant};
370 #[cfg(windows)]
371 let (mut parent, child_name) =
372 (std::process::Command::new("cmd").args(["/C", "ping -n 30 127.0.0.1 > nul"]).spawn().unwrap(), "ping");
373 #[cfg(unix)]
374 let (mut parent, child_name) =
375 (std::process::Command::new("sh").args(["-c", "trap '' TERM; sleep 30 & wait"]).spawn().unwrap(), "sleep");
376 let pid = parent.id();
377 let child_of = |pid: u32| {
380 let mut sys = sysinfo::System::new();
381 sys.refresh_processes_specifics(sysinfo::ProcessesToUpdate::All, true, sysinfo::ProcessRefreshKind::nothing());
382 sys.processes()
383 .iter()
384 .find(|(_, p)| {
385 p.parent() == Some(sysinfo::Pid::from_u32(pid)) && p.name().to_string_lossy().to_ascii_lowercase().starts_with(child_name)
386 })
387 .map(|(id, p)| (id.as_u32(), p.start_time()))
388 };
389 let until = Instant::now() + Duration::from_secs(10);
390 let mut child = None;
391 while child.is_none() && Instant::now() < until {
392 std::thread::sleep(Duration::from_millis(100));
393 child = child_of(pid);
394 }
395 let (child, child_started_s) = child.expect("the shell started its child");
396 let now_s = agentmux_common::time::now_secs_u64;
399 let until = Instant::now() + Duration::from_secs(5);
400 while now_s() <= child_started_s && Instant::now() < until {
401 std::thread::sleep(Duration::from_millis(50));
402 }
403
404 assert_eq!(force_kill_tree(pid, 60_000), 0, "a start time that doesn't match: not this process, nothing killed");
405 assert!(force_kill_tree(pid, 0) >= 1);
408
409 let until = Instant::now() + Duration::from_secs(10);
411 let mut exited = parent.try_wait().unwrap().is_some();
412 while !exited && Instant::now() < until {
413 std::thread::sleep(Duration::from_millis(50));
414 exited = parent.try_wait().unwrap().is_some();
415 }
416 if !exited {
417 let _ = parent.kill();
418 let _ = parent.wait();
419 }
420 assert!(exited, "the parent is gone");
421 let child_runs = || start_times(&[child]).get(&child).is_some_and(|started_ms| *started_ms == child_started_s * 1000);
423 let until = Instant::now() + Duration::from_secs(10);
424 while child_runs() && Instant::now() < until {
425 std::thread::sleep(Duration::from_millis(50));
426 }
427 assert!(!child_runs(), "the child is gone");
428 }
429
430 #[test]
431 fn only_a_container_agent_has_a_container() {
432 let block = |meta: &[(&str, &str)]| crate::backend::obj::Block {
433 meta: meta.iter().map(|(k, v)| (k.to_string(), serde_json::json!(v))).collect(),
434 ..Default::default()
435 };
436 assert_eq!(
437 container_of(&block(&[("agentMode", "container"), ("agentId", "lark")])).as_deref(),
438 Some(crate::backend::container::container_name_for_slug("lark").as_str())
439 );
440 assert_eq!(container_of(&block(&[("agentMode", "host"), ("agentId", "lark")])), None);
441 assert_eq!(container_of(&block(&[("agentMode", "container")])), None, "no agentId, no name");
442 }
443
444 #[test]
449 fn an_exited_process_is_not_a_survivor() {
450 #[cfg(windows)]
452 let mut child = std::process::Command::new("cmd").args(["/C", "set /p x="]).stdin(std::process::Stdio::piped()).spawn().unwrap();
453 #[cfg(unix)]
454 let mut child = std::process::Command::new("sh").args(["-c", "read x"]).stdin(std::process::Stdio::piped()).spawn().unwrap();
455 let pid = child.id();
456 let until = std::time::Instant::now() + std::time::Duration::from_secs(10);
457 let mut started_at_ms = 0;
458 while started_at_ms == 0 && std::time::Instant::now() < until {
459 started_at_ms = start_times(&[pid]).get(&pid).copied().unwrap_or(0);
460 if started_at_ms == 0 {
461 std::thread::sleep(std::time::Duration::from_millis(25));
462 }
463 }
464 assert_ne!(started_at_ms, 0, "the running child has a start time");
465 let entry = ProcessEntry { pid, command: "gone".into(), started_at_ms };
466 assert_eq!(survivors(std::slice::from_ref(&entry)).len(), 1, "a running process is a survivor");
467 child.kill().unwrap();
468 child.wait().unwrap();
469 drop(child);
470 let until = std::time::Instant::now() + std::time::Duration::from_secs(10);
471 while !survivors(std::slice::from_ref(&entry)).is_empty() && std::time::Instant::now() < until {
472 std::thread::sleep(std::time::Duration::from_millis(25));
473 }
474 assert!(survivors(std::slice::from_ref(&entry)).is_empty(), "an exited process is not a survivor");
475 }
476}