Skip to main content

agentmux_srv_core/backend/container/mounts/
dev_exec.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Running a container agent's dev server for it: started detached, and asked whether it is listening.
5
6use bollard::exec::{CreateExecOptions, StartExecOptions};
7
8use super::ContainerManager;
9use crate::backend::container::ContainerError;
10
11impl ContainerManager {
12    /// The dev-proxy routing table, once wired in.
13    pub(crate) fn dev_proxy_registry(&self) -> Option<&crate::backend::dev_proxy::DevProxyRegistry> {
14        self.inner.dev_proxy.get()
15    }
16
17    /// Whether something in `container` is listening on `port`.
18    pub(crate) async fn port_listening(&self, container: &str, port: u16) -> bool {
19        let probe = format!("exec 3<>/dev/tcp/127.0.0.1/{port}");
20        let argv = ["bash".to_string(), "-c".to_string(), probe];
21        matches!(
22            self.exec_collect(container, &argv, std::time::Duration::from_secs(5)).await,
23            Ok(out) if !out.timed_out && out.exit == Some(0)
24        )
25    }
26
27    /// Starts `command` in `dir` inside `container`, detached (like `docker exec -d`), as the container's own user,
28    /// with `env` added and its output in `log`. It keeps running after this returns, until the container stops.
29    pub(crate) async fn start_dev_server(
30        &self,
31        container: &str,
32        command: &str,
33        dir: &str,
34        env: &[(String, String)],
35        log: &str,
36    ) -> Result<(), ContainerError> {
37        let env: Vec<String> = env.iter().map(|(k, v)| format!("{k}={v}")).collect();
38        // The command is the shell's `$0`, the log its `$1`: never spliced into a script.
39        let script = r#"exec setsid nohup sh -c "$0" >"$1" 2>&1 </dev/null"#;
40        let exec = self
41            .inner
42            .docker
43            .create_exec(
44                container,
45                CreateExecOptions {
46                    cmd: Some(vec!["sh", "-c", script, command, log]),
47                    working_dir: Some(dir),
48                    env: if env.is_empty() { None } else { Some(env.iter().map(String::as_str).collect()) },
49                    attach_stdout: Some(false),
50                    attach_stderr: Some(false),
51                    ..Default::default()
52                },
53            )
54            .await?;
55        self.inner.docker.start_exec(&exec.id, Some(StartExecOptions { detach: true, ..Default::default() })).await?;
56        Ok(())
57    }
58}