1use std::collections::HashMap;
13use std::time::Instant;
14
15use bollard::container::{AttachContainerOptions, Config, CreateContainerOptions, LogOutput, RemoveContainerOptions, StartContainerOptions, WaitContainerOptions};
16use bollard::models::{HostConfig, HostConfigLogConfig};
17use bollard::Docker;
18use futures_util::StreamExt as _;
19
20use super::ContainerManager;
21
22pub const OUTPUT_CAP: usize = 64 * 1024;
24pub const LABEL: &str = "agentmux.drone-run";
26const USER: &str = "65534:65534";
28const MEMORY_BYTES: i64 = 512 * 1024 * 1024;
29const PIDS: i64 = 256;
30const NANO_CPUS: i64 = 1_000_000_000;
32
33#[derive(Debug, Clone, PartialEq)]
35pub struct OneShot {
36 pub image: String,
37 pub argv: Vec<String>,
39 pub env: Vec<(String, String)>,
40 pub cwd: Option<String>,
42}
43
44#[derive(Debug, Clone, PartialEq)]
46pub struct OneShotOutcome {
47 pub exit_code: i64,
48 pub stdout: String,
49 pub stderr: String,
50 pub truncated: bool,
52 pub duration_ms: u64,
53}
54
55pub fn oneshot_config(spec: &OneShot) -> Config<String> {
57 let (program, args) = spec.argv.split_first().expect("an argv has a program");
58 Config {
59 image: Some(spec.image.clone()),
60 entrypoint: Some(vec![program.clone()]),
62 cmd: Some(args.to_vec()),
63 env: Some(spec.env.iter().map(|(k, v)| format!("{k}={v}")).collect()),
64 working_dir: spec.cwd.clone(),
65 user: Some(USER.to_string()),
66 network_disabled: Some(true),
67 tty: Some(false),
68 open_stdin: Some(false),
69 labels: Some(HashMap::from([(LABEL.to_string(), "1".to_string())])),
70 host_config: Some(HostConfig {
71 network_mode: Some("none".to_string()),
72 readonly_rootfs: Some(true),
73 cap_drop: Some(vec!["ALL".to_string()]),
74 security_opt: Some(vec!["no-new-privileges".to_string()]),
75 memory: Some(MEMORY_BYTES),
76 memory_swap: Some(MEMORY_BYTES),
77 pids_limit: Some(PIDS),
78 nano_cpus: Some(NANO_CPUS),
79 init: Some(true),
80 tmpfs: Some(HashMap::from([("/tmp".to_string(), "rw,noexec,nosuid,size=64m".to_string())])),
82 log_config: Some(HostConfigLogConfig { typ: Some("none".to_string()), config: None }),
84 ..Default::default()
85 }),
86 ..Default::default()
87 }
88}
89
90struct Remove {
93 docker: Docker,
94 name: String,
95 done: bool,
96}
97
98impl Remove {
99 async fn now(mut self) {
100 remove(&self.docker, &self.name).await;
101 self.done = true;
103 }
104}
105
106impl Drop for Remove {
107 fn drop(&mut self) {
108 if self.done {
109 return;
110 }
111 let (docker, name) = (self.docker.clone(), self.name.clone());
112 if let Ok(handle) = tokio::runtime::Handle::try_current() {
113 handle.spawn(async move { remove(&docker, &name).await });
114 }
115 }
116}
117
118async fn remove(docker: &Docker, name: &str) {
119 let _ = docker.remove_container(name, Some(RemoveContainerOptions { force: true, v: true, ..Default::default() })).await;
120}
121
122impl ContainerManager {
123 pub async fn run_oneshot(&self, spec: &OneShot) -> Result<OneShotOutcome, String> {
126 let docker = &self.inner.docker;
127 let mut spec = spec.clone();
128 if !self.has_image_locally(&spec.image).await {
129 spec.image = self.pull_with_fallback(&spec.image, &|_| {}).await.map_err(|e| e.to_string())?;
130 }
131 let name = format!("agentmux-drone-run-{}", uuid::Uuid::new_v4().simple());
132 docker
133 .create_container(Some(CreateContainerOptions { name: name.as_str(), platform: None }), oneshot_config(&spec))
134 .await
135 .map_err(|e| format!("couldn't create the container: {e}"))?;
136 let remove = Remove { docker: docker.clone(), name: name.clone(), done: false };
137 let attached = docker
140 .attach_container(
141 &name,
142 Some(AttachContainerOptions::<String> { stream: Some(true), stdout: Some(true), stderr: Some(true), logs: Some(false), ..Default::default() }),
143 )
144 .await
145 .map_err(|e| format!("couldn't attach to the container: {e}"))?;
146 let started = Instant::now();
147 docker.start_container(&name, None::<StartContainerOptions<String>>).await.map_err(|e| format!("couldn't start the container: {e}"))?;
148 let (ended, logs) = tokio::join!(wait(docker, &name), read_output(attached.output));
149 let duration_ms = started.elapsed().as_millis() as u64;
150 remove.now().await;
151 let exit_code = ended?;
152 let (stdout, stderr, truncated) = logs?;
153 Ok(OneShotOutcome { exit_code, stdout, stderr, truncated, duration_ms })
154 }
155}
156
157pub(super) async fn wait(docker: &Docker, name: &str) -> Result<i64, String> {
159 let mut ended = docker.wait_container(name, Some(WaitContainerOptions { condition: "not-running" }));
160 match ended.next().await {
161 Some(Ok(done)) => Ok(done.status_code),
162 Some(Err(bollard::errors::Error::DockerContainerWaitError { code, .. })) => Ok(code),
164 Some(Err(e)) => Err(format!("couldn't wait for the container: {e}")),
165 None => Err("the container's end was not reported".to_string()),
166 }
167}
168
169async fn read_output(mut logs: impl futures_util::Stream<Item = Result<LogOutput, bollard::errors::Error>> + Unpin) -> Result<(String, String, bool), String> {
171 let (mut out, mut err) = (Vec::new(), Vec::new());
172 let mut truncated = false;
173 while let Some(line) = logs.next().await {
174 let (into, bytes) = match line.map_err(|e| format!("couldn't read the container's output: {e}"))? {
175 LogOutput::StdOut { message } => (&mut out, message),
176 LogOutput::StdErr { message } => (&mut err, message),
177 _ => continue,
178 };
179 let room = OUTPUT_CAP.saturating_sub(into.len());
180 truncated |= bytes.len() > room;
181 into.extend_from_slice(&bytes[..bytes.len().min(room)]);
182 }
183 Ok((lossy(out), lossy(err), truncated))
184}
185
186fn lossy(bytes: Vec<u8>) -> String {
188 String::from_utf8_lossy(&bytes).into_owned()
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 fn spec(argv: &[&str]) -> OneShot {
196 OneShot { image: "img:1".into(), argv: argv.iter().map(|s| s.to_string()).collect(), env: vec![("A".into(), "b".into())], cwd: None }
197 }
198
199 #[test]
200 fn the_program_is_run_as_given_and_nothing_else_is() {
201 let c = oneshot_config(&spec(&["echo", "hi", "there"]));
202 assert_eq!(c.entrypoint, Some(vec!["echo".to_string()]), "the image's own entrypoint is replaced");
203 assert_eq!(c.cmd, Some(vec!["hi".to_string(), "there".to_string()]));
204 assert_eq!(c.env, Some(vec!["A=b".to_string()]));
205 }
206
207 #[test]
208 fn the_container_has_no_network_no_host_files_and_no_privilege() {
209 let c = oneshot_config(&spec(&["true"]));
210 let h = c.host_config.unwrap();
211 assert_eq!(c.network_disabled, Some(true));
212 assert_eq!(h.network_mode.as_deref(), Some("none"));
213 assert_eq!(h.readonly_rootfs, Some(true));
214 assert_eq!(h.cap_drop, Some(vec!["ALL".to_string()]));
215 assert_eq!(h.security_opt, Some(vec!["no-new-privileges".to_string()]));
216 assert!(h.mounts.is_none() && h.binds.is_none(), "nothing from the host is mounted");
217 assert_eq!(h.privileged, None);
218 assert_ne!(c.user.as_deref(), Some("root"));
219 assert_eq!(h.pids_limit, Some(PIDS));
220 assert_eq!(h.memory, Some(MEMORY_BYTES));
221 assert_eq!(h.memory_swap, Some(MEMORY_BYTES), "no swap beyond the limit");
222 }
223
224 #[test]
225 fn it_is_labelled_so_a_leftover_can_be_found() {
226 assert_eq!(oneshot_config(&spec(&["true"])).labels.unwrap().get(LABEL).map(String::as_str), Some("1"));
227 }
228
229 #[tokio::test]
231 #[ignore]
232 async fn one_shot_runs_a_command_in_a_container_and_gives_its_output() {
233 let cm = ContainerManager::connect_detected().await.expect("a container runtime");
234 let image = super::super::image::resolve_container_image(super::super::image::DEFAULT_AGENT_IMAGE);
235 let run = |argv: &[&str]| {
236 let cm = cm.clone();
237 let s = OneShot { image: image.clone(), argv: argv.iter().map(|s| s.to_string()).collect(), env: vec![("GREETING".into(), "hello".into())], cwd: None };
238 async move { cm.run_oneshot(&s).await.unwrap() }
239 };
240 let echo = run(&["printenv", "GREETING"]).await;
241 assert_eq!((echo.exit_code, echo.stdout.trim()), (0, "hello"));
242 let fails = run(&["sh", "-c", "echo oops >&2; exit 3"]).await;
243 assert_eq!((fails.exit_code, fails.stderr.trim()), (3, "oops"));
244 let net = run(&["sh", "-c", "wget -q -T 3 -O - http://1.1.1.1/ || curl -sS -m 3 http://1.1.1.1/"]).await;
246 assert_ne!(net.exit_code, 0, "{net:?}");
247 assert_ne!(run(&["touch", "/etc/x"]).await.exit_code, 0);
249 assert_eq!(run(&["touch", "/tmp/x"]).await.exit_code, 0);
250 let big = run(&["sh", "-c", "head -c 200000 /dev/zero | tr '\\0' a"]).await;
252 assert_eq!(big.stdout.len(), OUTPUT_CAP);
253 assert!(big.truncated);
254 let loud = run(&["sh", "-c", "echo first >&2; head -c 3000000 /dev/zero | tr '\\0' a"]).await;
256 assert_eq!(loud.stderr.trim(), "first");
257 assert_eq!(loud.stdout.len(), OUTPUT_CAP);
258 assert!(loud.truncated);
259 }
260}