Skip to main content

strop_containers/
engine.rs

1//! The local engine conversation: probe, discovery and identity
2//! resolution. Every `docker` invocation is a supervised capture — argv
3//! arrays, a caller's [`CancelToken`], a deadline and bounded retention —
4//! and every non-zero exit is classified into a typed refusal.
5
6use crate::identity::{validate_name, ContainerIdentity, ContainerRef};
7use crate::ContainerError;
8use std::process::Command;
9use std::time::Duration;
10use strop_core::process::{
11    capture_with, stream_with, CaptureError, CapturePolicy, StdinPolicy, StreamError, StreamPolicy,
12};
13use strop_core::worker::CancelToken;
14
15/// Wall-clock budget for the `docker info` probe.
16const INFO_DEADLINE: Duration = Duration::from_secs(10);
17/// Budget for discovery/inspect metadata commands.
18const META_DEADLINE: Duration = Duration::from_secs(15);
19/// Budget for one filesystem read (`docker cp` tar stream).
20pub(crate) const READ_DEADLINE: Duration = Duration::from_secs(30);
21/// Retained stderr for diagnostics (tails only ever reach errors).
22const STDERR_LIMIT: u64 = 64 * 1024;
23/// Retained stdout for metadata commands (`info`/`ps`/`inspect`).
24const META_LIMIT: u64 = 4 * 1024 * 1024;
25/// Retained metadata for one directory listing: the direct children's
26/// names and kinds. The listing's tar stream itself is consumed
27/// incrementally and never retained, so a subtree's bulk no longer
28/// counts — only a listing with an absurd direct-child set is refused,
29/// never presented partially.
30pub(crate) const LIST_LIMIT: u64 = 16 * 1024 * 1024;
31
32/// The local Docker engine, proven reachable by a bounded probe.
33///
34/// v1 is local-only by construction: there is no endpoint field to
35/// parse, and there is deliberately no way to construct one without the
36/// probe — a remote-engine field is earned with DC5, not reserved.
37#[derive(Debug, Clone)]
38pub struct EngineRef {
39    server_version: String,
40}
41
42impl EngineRef {
43    /// `ServerVersion` as the probe reported it.
44    pub fn server_version(&self) -> &str {
45        &self.server_version
46    }
47}
48
49/// One supervised `docker` run's retained bytes — public for the
50/// `exec_capture` boundary.
51pub struct Captured {
52    pub code: Option<i32>,
53    pub stdout: Vec<u8>,
54    pub stderr: Vec<u8>,
55    pub stdout_dropped: u64,
56}
57
58/// Run `docker <args>` under supervision: own process group, the caller's
59/// token, `deadline`, bounded pipes, no stdin. Spawn failure means the
60/// CLI itself is missing — that is the engine being unavailable.
61pub(crate) fn capture(
62    args: &[&str],
63    stdout_limit: u64,
64    deadline: Duration,
65    token: &CancelToken,
66) -> Result<Captured, ContainerError> {
67    let mut command = Command::new("docker");
68    command.args(args);
69    let policy = CapturePolicy {
70        stdout_limit,
71        stderr_limit: STDERR_LIMIT,
72        stderr_tail: 0,
73        deadline,
74        stdin: StdinPolicy::Null,
75    };
76    let output = capture_with(&mut command, token, &policy).map_err(|error| match error {
77        CaptureError::Spawn(detail) => ContainerError::EngineUnavailable { detail },
78        CaptureError::Cancelled => ContainerError::Cancelled,
79        CaptureError::TimedOut(deadline) => ContainerError::Io {
80            detail: format!(
81                "docker {} timed out after {}s",
82                args.first().copied().unwrap_or("<none>"),
83                deadline.as_secs()
84            ),
85        },
86        CaptureError::Failure(failure) => ContainerError::Io {
87            detail: failure.message,
88        },
89    })?;
90    Ok(Captured {
91        code: output.status.code(),
92        stdout: output.stdout,
93        stderr: output.stderr,
94        stdout_dropped: output.stdout_dropped,
95    })
96}
97
98/// One supervised `docker` run whose stdout streamed through a consumer.
99pub(crate) struct Streamed {
100    pub code: Option<i32>,
101    pub stderr: Vec<u8>,
102}
103
104/// Run `docker <args>` under [`capture`]'s supervision while stdout
105/// streams through `consume` chunk by chunk: nothing is retained by the
106/// supervisor, so a transfer larger than any retention limit stays
107/// bounded by what the consumer keeps. Stderr retention, the deadline
108/// and cancellation behave exactly as in [`capture`]; a consumer error
109/// kills the child and surfaces as its own typed [`ContainerError`].
110pub(crate) fn stream(
111    args: &[&str],
112    deadline: Duration,
113    token: &CancelToken,
114    consume: impl FnMut(&[u8]) -> Result<(), ContainerError>,
115) -> Result<Streamed, ContainerError> {
116    let mut command = Command::new("docker");
117    command.args(args);
118    let policy = StreamPolicy {
119        stderr_limit: STDERR_LIMIT,
120        stderr_tail: 0,
121        deadline,
122    };
123    let output =
124        stream_with(&mut command, token, &policy, consume).map_err(|error| match error {
125            StreamError::Spawn(detail) => ContainerError::EngineUnavailable { detail },
126            StreamError::Cancelled => ContainerError::Cancelled,
127            StreamError::TimedOut(deadline) => ContainerError::Io {
128                detail: format!(
129                    "docker {} timed out after {}s",
130                    args.first().copied().unwrap_or("<none>"),
131                    deadline.as_secs()
132                ),
133            },
134            StreamError::Failure(failure) => ContainerError::Io {
135                detail: failure.message,
136            },
137            StreamError::Consumer(error) => error,
138        })?;
139    Ok(Streamed {
140        code: output.status.code(),
141        stderr: output.stderr,
142    })
143}
144
145/// The last bytes of stderr, lossy-decoded and single-lined — bounded
146/// context for a typed failure, never an unbounded dump.
147pub(crate) fn stderr_tail(stderr: &[u8]) -> String {
148    let text = String::from_utf8_lossy(stderr);
149    let tail: String = text.chars().rev().take(300).collect::<String>();
150    tail.chars().rev().collect::<String>().replace('\n', " ")
151}
152
153/// Probe the local engine: `docker info` must succeed and report a
154/// server version. CLI missing, daemon down or a timed-out probe are all
155/// [`ContainerError::EngineUnavailable`].
156pub fn engine(token: &CancelToken) -> Result<EngineRef, ContainerError> {
157    let output = capture(
158        &["info", "--format", "{{json .ServerVersion}}"],
159        META_LIMIT,
160        INFO_DEADLINE,
161        token,
162    )?;
163    if output.code != Some(0) {
164        return Err(ContainerError::EngineUnavailable {
165            detail: stderr_tail(&output.stderr),
166        });
167    }
168    let server_version: String =
169        serde_json::from_slice(&output.stdout).map_err(|error| ContainerError::Protocol {
170            detail: format!("docker info reported no server version: {error}"),
171        })?;
172    if server_version.is_empty() {
173        return Err(ContainerError::Protocol {
174            detail: "docker info reported an empty server version".into(),
175        });
176    }
177    Ok(EngineRef { server_version })
178}
179
180/// The engine's running containers as full identities: `ps` for the id
181/// set, one batched `inspect` for the records. Containers that stop in
182/// between are dropped — this lists running containers only.
183pub fn list_running(
184    engine: &EngineRef,
185    token: &CancelToken,
186) -> Result<Vec<ContainerIdentity>, ContainerError> {
187    let _ = engine;
188    let output = capture(
189        &["ps", "--quiet", "--no-trunc"],
190        META_LIMIT,
191        META_DEADLINE,
192        token,
193    )?;
194    if output.code != Some(0) {
195        return Err(ContainerError::EngineUnavailable {
196            detail: stderr_tail(&output.stderr),
197        });
198    }
199    let text = String::from_utf8(output.stdout).map_err(|_| ContainerError::Protocol {
200        detail: "docker ps answered in non-UTF-8".into(),
201    })?;
202    let ids: Vec<&str> = text.lines().filter(|line| !line.is_empty()).collect();
203    for id in &ids {
204        if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
205            return Err(ContainerError::Protocol {
206                detail: format!("docker ps reported a non-canonical id {id:?}"),
207            });
208        }
209    }
210    if ids.is_empty() {
211        return Ok(Vec::new());
212    }
213    let mut args = vec!["inspect"];
214    args.extend(ids);
215    let output = capture(&args, META_LIMIT, META_DEADLINE, token)?;
216    inspect_records("docker ps ids", &output)?
217        .into_iter()
218        .filter(|record| record.state.running)
219        .map(identity)
220        .collect()
221}
222
223/// Resolve a name or id prefix to the container's identity, canonical
224/// 64-hex id included. Names are validated before the engine sees them;
225/// an unknown name is [`ContainerError::NoSuchContainer`], never a
226/// best-effort guess.
227pub fn inspect(
228    engine: &EngineRef,
229    name_or_id: &str,
230    token: &CancelToken,
231) -> Result<ContainerIdentity, ContainerError> {
232    let _ = engine;
233    validate_name(name_or_id)?;
234    let output = capture(&["inspect", name_or_id], META_LIMIT, META_DEADLINE, token)?;
235    identity(inspect_record(name_or_id, &output)?)
236}
237
238/// Re-resolve a previously inspected identity by name. The stale-identity
239/// refusal lives here: a name that now maps to a different id, or the same
240/// id restarted since, must not silently inherit the old identity's
241/// reads, caches or completions.
242pub fn revalidate(
243    engine: &EngineRef,
244    held: &ContainerIdentity,
245    token: &CancelToken,
246) -> Result<ContainerRef, ContainerError> {
247    let current = inspect(engine, &held.name, token)?;
248    if current.id != held.id || current.started_at != held.started_at {
249        return Err(ContainerError::StaleIdentity {
250            name: held.name.clone(),
251            expected: format!("{}@{}", held.id, held.started_at),
252            found: format!("{}@{}", current.id, current.started_at),
253        });
254    }
255    ContainerRef::of(&current)
256}
257
258/// The cheap pre-read re-check: the container behind `reference` must
259/// still exist, still be the same incarnation (`StartedAt`), and still be
260/// running. One bounded `inspect` per read — the price of never serving
261/// bytes from a restarted container as if they were the old one's.
262pub(crate) fn refresh(
263    engine: &EngineRef,
264    reference: &ContainerRef,
265    token: &CancelToken,
266) -> Result<(), ContainerError> {
267    let _ = engine;
268    let id = reference.id().as_str();
269    let output = capture(&["inspect", id], META_LIMIT, META_DEADLINE, token)?;
270    let record = inspect_record(id, &output)?;
271    if record.state.started_at != reference.started_at() {
272        return Err(ContainerError::StaleIdentity {
273            name: id.to_string(),
274            expected: reference.incarnation(),
275            found: format!("{id}@{}", record.state.started_at),
276        });
277    }
278    if !record.state.running {
279        return Err(ContainerError::NotRunning { id: id.to_string() });
280    }
281    Ok(())
282}
283
284/// The fields of `docker inspect`'s JSON record this backend consumes.
285#[derive(serde::Deserialize)]
286struct InspectRecord {
287    #[serde(rename = "Id")]
288    id: String,
289    #[serde(rename = "Name", default)]
290    name: String,
291    #[serde(rename = "Config", default)]
292    config: InspectConfig,
293    #[serde(rename = "State", default)]
294    state: InspectState,
295}
296
297#[derive(Default, serde::Deserialize)]
298struct InspectConfig {
299    #[serde(rename = "Image", default)]
300    image: String,
301    #[serde(rename = "User", default)]
302    user: String,
303    /// The container's working directory (Config.WorkingDir); empty means
304    /// the image default ("/").
305    #[serde(rename = "WorkingDir", default)]
306    workdir: String,
307}
308
309#[derive(Default, serde::Deserialize)]
310struct InspectState {
311    #[serde(rename = "Running", default)]
312    running: bool,
313    #[serde(rename = "StartedAt", default)]
314    started_at: String,
315}
316
317/// Decode the single-record inspect answer, classifying failure output.
318fn inspect_record(name_or_id: &str, output: &Captured) -> Result<InspectRecord, ContainerError> {
319    Ok(inspect_records(name_or_id, output)?.remove(0))
320}
321
322/// Decode an inspect answer's JSON array; a non-zero exit naming a
323/// missing object is [`ContainerError::NoSuchContainer`].
324fn inspect_records(what: &str, output: &Captured) -> Result<Vec<InspectRecord>, ContainerError> {
325    if output.code != Some(0) {
326        let tail = stderr_tail(&output.stderr);
327        // Older daemons print "No such object", newer ones "no such object".
328        if tail.to_ascii_lowercase().contains("no such object") {
329            return Err(ContainerError::NoSuchContainer {
330                name: what.to_string(),
331            });
332        }
333        return Err(ContainerError::Io {
334            detail: format!("docker inspect failed: {tail}"),
335        });
336    }
337    if output.stdout_dropped > 0 {
338        return Err(ContainerError::OutputTooLarge {
339            what: "docker inspect output".into(),
340        });
341    }
342    let records: Vec<InspectRecord> =
343        serde_json::from_slice(&output.stdout).map_err(|error| ContainerError::Protocol {
344            detail: format!("docker inspect answered malformed JSON: {error}"),
345        })?;
346    if records.is_empty() {
347        return Err(ContainerError::Protocol {
348            detail: format!("docker inspect of {what} returned no record"),
349        });
350    }
351    Ok(records)
352}
353
354/// The identity view of one inspect record; the id must already be the
355/// canonical 64-hex form (a short-id answer would mean the engine broke
356/// its own contract).
357fn identity(record: InspectRecord) -> Result<ContainerIdentity, ContainerError> {
358    strop_workspace::ContainerId::canonical(record.id.clone()).map_err(|_| {
359        ContainerError::Protocol {
360            detail: format!("inspect id {:?} is not the canonical 64-hex id", record.id),
361        }
362    })?;
363    Ok(ContainerIdentity {
364        id: record.id,
365        name: record.name.trim_start_matches('/').to_string(),
366        image: record.config.image,
367        started_at: record.state.started_at,
368        user: record.config.user,
369        workdir: record.config.workdir,
370    })
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    fn captured(code: Option<i32>, stdout: &[u8], stderr: &[u8]) -> Captured {
378        Captured {
379            code,
380            stdout: stdout.to_vec(),
381            stderr: stderr.to_vec(),
382            stdout_dropped: 0,
383        }
384    }
385
386    const INSPECT_JSON: &str = r#"[{
387        "Id": "5b04229f99d2c4b8ae3c4e38b7a887cf1c5c1ea51f2a1b2c3d4e5f60718293a4",
388        "Name": "/fixture",
389        "Config": {"Image": "busybox:latest", "User": "root"},
390        "State": {"Running": true, "StartedAt": "2026-09-10T08:00:00.123Z"}
391    }]"#;
392
393    #[test]
394    fn inspect_json_decodes_to_identity() {
395        let output = captured(Some(0), INSPECT_JSON.as_bytes(), b"");
396        let identity = identity(inspect_record("fixture", &output).unwrap()).unwrap();
397        assert_eq!(identity.id.len(), 64);
398        assert_eq!(identity.name, "fixture", "leading slash stripped");
399        assert_eq!(identity.image, "busybox:latest");
400        assert_eq!(identity.started_at, "2026-09-10T08:00:00.123Z");
401        assert_eq!(identity.user, "root");
402    }
403
404    #[test]
405    fn missing_object_and_daemon_errors_classify() {
406        let missing = captured(
407            Some(1),
408            b"[]",
409            b"Error response from daemon: No such object: ghost\n",
410        );
411        assert!(matches!(
412            inspect_record("ghost", &missing),
413            Err(ContainerError::NoSuchContainer { .. })
414        ));
415        // Docker 29's lowercase daemon spelling.
416        let lowercase = captured(Some(1), b"[]", b"error: no such object: ghost\n");
417        assert!(matches!(
418            inspect_record("ghost", &lowercase),
419            Err(ContainerError::NoSuchContainer { .. })
420        ));
421        let down = captured(
422            Some(1),
423            b"",
424            b"Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
425        );
426        assert!(matches!(
427            inspect_record("ghost", &down),
428            Err(ContainerError::Io { .. })
429        ));
430        let malformed = captured(Some(0), b"[{]", b"");
431        assert!(matches!(
432            inspect_record("ghost", &malformed),
433            Err(ContainerError::Protocol { .. })
434        ));
435    }
436
437    #[test]
438    fn non_canonical_ids_are_protocol_violations() {
439        let json = INSPECT_JSON.replace(
440            "5b04229f99d2c4b8ae3c4e38b7a887cf1c5c1ea51f2a1b2c3d4e5f60718293a4",
441            "5b04229f99d2",
442        );
443        let output = captured(Some(0), json.as_bytes(), b"");
444        assert!(matches!(
445            inspect_record("x", &output).and_then(identity),
446            Err(ContainerError::Protocol { .. })
447        ));
448    }
449
450    #[test]
451    fn stderr_tail_is_bounded_and_single_line() {
452        let noisy = format!("{}\nfinal line", "x".repeat(1000));
453        let tail = stderr_tail(noisy.as_bytes());
454        assert!(tail.len() <= 300);
455        assert!(tail.ends_with("final line"));
456        assert!(!tail.contains('\n'));
457    }
458}