Skip to main content

agentmux_srv_core/backend/
container_task_probe.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Docker side of the container liveness sweep (`background_task_container_sweep`): ask a container,
5//! through the exec API, whether a process is still there and when it started.
6
7use std::sync::Arc;
8use std::time::Duration;
9
10use futures_util::future::BoxFuture;
11use futures_util::StreamExt;
12
13use super::background_task_container_sweep::{verdict_of, ContainerProbe, Verdict};
14use super::container::runtime::ContainerRuntimeHandle;
15use super::container::{ContainerError, ContainerManager};
16
17/// How long one probe may take, start to answer. A container that does not answer is not one to end rows for.
18const PROBE_LIMIT: Duration = Duration::from_secs(15);
19
20/// Prints `gone`, or `alive <start of the process, unix seconds>` (`alive` alone when the start can't be read).
21/// A zombie is gone. The start comes from `/proc/<pid>/stat` (field 22, in clock ticks since boot) and the
22/// kernel's boot time, which is how `pid_alive_since` reads a host pid's. The pid is an argument, never part of
23/// the script's text.
24const SCRIPT: &str = r#"p="$1"
25[ -r "/proc/$p/stat" ] || { echo gone; exit 0; }
26rest=$(sed 's/^.*) //' "/proc/$p/stat" 2>/dev/null)
27state=${rest%% *}
28[ "$state" = "Z" ] || [ "$state" = "X" ] && { echo gone; exit 0; }
29ticks=$(echo "$rest" | cut -d' ' -f20)
30boot=$(awk '/^btime/ {print $2}' /proc/stat 2>/dev/null)
31hz=$(getconf CLK_TCK 2>/dev/null || echo 100)
32if [ -n "$ticks" ] && [ -n "$boot" ] && [ "$hz" -gt 0 ] 2>/dev/null; then echo "alive $((boot + ticks / hz))"; else echo alive; fi"#;
33
34/// Whether a refused exec means the container is not running: Docker answers 404 for one that does not exist
35/// and 409 for one that is stopped, paused or restarting.
36fn container_is_down(e: &ContainerError) -> bool {
37    matches!(e, ContainerError::Docker(bollard::errors::Error::DockerResponseServerError { status_code: 404 | 409, .. }))
38}
39
40/// Run the probe for `pid` in `container`.
41pub async fn probe(cm: &ContainerManager, container: &str, pid: u32, task_started_ms: i64) -> Verdict {
42    let argv: Vec<String> = ["sh", "-c", SCRIPT, "sh"].iter().map(|s| s.to_string()).chain(std::iter::once(pid.to_string())).collect();
43    let ask = async {
44        let session = match cm.exec(container, &argv, None, &[], false).await {
45            Ok(session) => session,
46            Err(e) if container_is_down(&e) => return Verdict::ContainerDown,
47            Err(_) => return Verdict::Unknown,
48        };
49        let mut stream = session.output;
50        let mut printed = String::new();
51        while let Some(Ok(chunk)) = stream.next().await {
52            printed.push_str(&String::from_utf8_lossy(&chunk.into_bytes()));
53            if printed.len() > 4096 {
54                break;
55            }
56        }
57        // The stream ending is not the exit: a shell that failed to run the script printed nothing readable.
58        verdict_of(&printed, task_started_ms)
59    };
60    tokio::time::timeout(PROBE_LIMIT, ask).await.unwrap_or(Verdict::Unknown)
61}
62
63/// The sweep's probe, through whichever container runtime srv is connected to now.
64pub struct DockerProbe {
65    pub runtime: Arc<ContainerRuntimeHandle>,
66}
67
68impl ContainerProbe for DockerProbe {
69    fn probe<'a>(&'a self, container: &'a str, pid: u32, task_started_ms: i64) -> BoxFuture<'a, Verdict> {
70        Box::pin(async move {
71            match self.runtime.get().await {
72                Some(cm) => probe(&cm, container, pid, task_started_ms).await,
73                None => Verdict::Unknown,
74            }
75        })
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[cfg(target_os = "linux")]
84    fn run(args: &[&str]) -> String {
85        let out = std::process::Command::new("sh").arg("-c").arg(SCRIPT).arg("sh").args(args).output().expect("sh runs");
86        String::from_utf8_lossy(&out.stdout).trim().to_string()
87    }
88
89    #[test]
90    fn a_refused_exec_means_down_only_for_a_missing_or_stopped_container() {
91        let refused = |status_code| ContainerError::Docker(bollard::errors::Error::DockerResponseServerError { status_code, message: String::new() });
92        assert!(container_is_down(&refused(404)) && container_is_down(&refused(409)));
93        assert!(!container_is_down(&refused(500)), "a daemon error says nothing about the container");
94        assert!(!container_is_down(&ContainerError::NotAvailable("no docker".into())));
95    }
96
97    /// The script, run where /proc is Linux's: a process of this test is alive with a start time that is not
98    /// after now; a pid no process has is gone.
99    #[cfg(target_os = "linux")]
100    #[test]
101    fn the_script_reads_a_live_process_and_a_missing_one() {
102        let now = agentmux_common::time::now_ms() / 1000;
103        let mine = run(&[&std::process::id().to_string()]);
104        let started: i64 = mine.strip_prefix("alive ").expect(&mine).parse().unwrap();
105        assert!(started <= now + 2 && started > now - 7 * 24 * 3600, "{mine}");
106        assert_eq!(run(&["4194999"]), "gone");
107        assert_eq!(verdict_of(&mine, now * 1000), Verdict::Alive);
108    }
109}