agentmux_srv_core/backend/
background_task_container_sweep.rs1use std::collections::BTreeSet;
22use std::sync::Arc;
23
24use futures_util::future::BoxFuture;
25
26use super::storage::background_tasks::BackgroundTaskStatus;
27use super::storage::store::Store;
28
29const START_SLACK_MS: i64 = 60_000;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Verdict {
37 Alive,
39 Gone,
41 ContainerDown,
43 Unknown,
45}
46
47pub trait ContainerProbe: Send + Sync {
49 fn probe<'a>(&'a self, container: &'a str, pid: u32, task_started_ms: i64) -> BoxFuture<'a, Verdict>;
51}
52
53pub fn verdict_of(output: &str, task_started_ms: i64) -> Verdict {
55 let Some(line) = output.lines().map(str::trim).rev().find(|l| *l == "gone" || l.starts_with("alive")) else {
56 return Verdict::Unknown;
57 };
58 if line == "gone" {
59 return Verdict::Gone;
60 }
61 match line["alive".len()..].trim().parse::<i64>() {
62 Ok(started_s) if started_s.saturating_mul(1000) > task_started_ms.saturating_add(START_SLACK_MS) => Verdict::Gone,
63 _ => Verdict::Alive,
64 }
65}
66
67pub async fn sweep(store: &Arc<Store>, now_ms: i64, probe: &dyn ContainerProbe) -> BTreeSet<String> {
69 let mut changed = BTreeSet::new();
70 let reader = Arc::clone(store);
71 let rows = match tokio::task::spawn_blocking(move || reader.background_container_running()).await {
72 Ok(Ok(rows)) => rows,
73 Ok(Err(e)) => {
74 tracing::warn!(target: "background_tasks", error = %e, "container liveness sweep: could not list the running tasks");
75 return changed;
76 }
77 Err(_) => return changed,
78 };
79 let mut down: BTreeSet<&str> = BTreeSet::new();
80 for task in &rows {
81 if down.contains(task.container.as_str()) {
82 continue;
83 }
84 let Some(pid) = u32::try_from(task.pid).ok().filter(|p| *p > 0) else { continue };
85 match probe.probe(&task.container, pid, task.started_at_ms).await {
86 Verdict::Alive | Verdict::Unknown => {}
87 Verdict::Gone => {
88 if end(store, &task.id, now_ms).await {
89 tracing::info!(target: "background_tasks", block_id = %task.block_id, node_id = %task.id,
90 "container liveness sweep: a background task whose process is gone is stopped");
91 changed.insert(task.block_id.clone());
92 }
93 }
94 Verdict::ContainerDown => {
95 down.insert(task.container.as_str());
96 }
97 }
98 }
99 for task in rows.iter().filter(|t| down.contains(t.container.as_str())) {
100 let (store, block_id) = (Arc::clone(store), task.block_id.clone());
101 let ended = tokio::task::spawn_blocking(move || store.background_task_end_unchecked_for_block(&block_id)).await;
102 if matches!(ended, Ok(Ok(n)) if n > 0) {
103 tracing::info!(target: "background_tasks", block_id = %task.block_id, container = %task.container,
104 "container liveness sweep: the container is not running, its background tasks are over");
105 changed.insert(task.block_id.clone());
106 }
107 }
108 changed
109}
110
111async fn end(store: &Arc<Store>, id: &str, now_ms: i64) -> bool {
113 let (store, id) = (Arc::clone(store), id.to_string());
114 let ended = tokio::task::spawn_blocking(move || store.background_task_end_if_running(&id, BackgroundTaskStatus::Stopped, now_ms)).await;
115 matches!(ended, Ok(Ok(true)))
116}
117
118#[cfg(test)]
119#[path = "background_task_container_sweep_tests.rs"]
120mod tests;