Skip to main content

purple_ssh/
containers.rs

1use std::collections::HashMap;
2use std::time::{SystemTime, UNIX_EPOCH};
3
4use log::{error, info};
5
6use serde::{Deserialize, Serialize};
7
8use crate::ssh_context::{OwnedSshContext, SshContext};
9
10// ---------------------------------------------------------------------------
11// ContainerInfo model
12// ---------------------------------------------------------------------------
13
14/// Metadata for a single container (from `docker ps -a` / `podman ps -a`).
15///
16/// Deserialization is tolerant of both docker and podman JSON shapes.
17/// Docker uses `ID` plus scalar `Names`/`Ports`; podman uses `Id` plus
18/// `Names` as an array and `Ports` as an array of objects. The custom
19/// helpers below coerce both into the docker-shaped scalar fields the
20/// rest of purple (UI, cache, MCP) already understands.
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22pub struct ContainerInfo {
23    #[serde(rename = "ID", alias = "Id")]
24    pub id: String,
25    #[serde(rename = "Names", deserialize_with = "deserialize_names_field")]
26    pub names: String,
27    #[serde(rename = "Image")]
28    pub image: String,
29    #[serde(rename = "State")]
30    pub state: String,
31    #[serde(rename = "Status", default)]
32    pub status: String,
33    // `default` covers the missing-key case directly via Default::default()
34    // and bypasses `deserialize_with`. The custom deserializer therefore
35    // only runs when `Ports` is present (scalar, array or explicit null).
36    #[serde(
37        rename = "Ports",
38        deserialize_with = "deserialize_ports_field",
39        default
40    )]
41    pub ports: String,
42}
43
44/// Accept `Names` as either a scalar string (docker) or an array of
45/// strings (podman). Multiple names join with `,` to match docker's
46/// own comma-joined rendering. Unexpected shapes (number, object,
47/// null) propagate as serde errors; `parse_container_ps` drops the
48/// offending row via `.ok()`, which is the right behaviour for a row
49/// that has lost its identity.
50fn deserialize_names_field<'de, D>(deserializer: D) -> Result<String, D::Error>
51where
52    D: serde::Deserializer<'de>,
53{
54    #[derive(Deserialize)]
55    #[serde(untagged)]
56    enum NamesField {
57        Scalar(String),
58        Array(Vec<String>),
59    }
60    match NamesField::deserialize(deserializer)? {
61        NamesField::Scalar(s) => Ok(s),
62        NamesField::Array(arr) => Ok(arr.join(",")),
63    }
64}
65
66/// Accept `Ports` as either a scalar string (docker) or an array of
67/// port objects (podman). Podman entries are rendered into the same
68/// `host_ip:host_port->container_port/proto` form docker emits, so
69/// downstream UI rendering stays uniform. An explicit JSON null is
70/// tolerated and produces an empty string: podman uses `null` to mean
71/// "no ports published", which is semantically valid and the row must
72/// remain visible.
73fn deserialize_ports_field<'de, D>(deserializer: D) -> Result<String, D::Error>
74where
75    D: serde::Deserializer<'de>,
76{
77    #[derive(Deserialize)]
78    #[serde(untagged)]
79    enum PortsField {
80        Scalar(String),
81        Array(Vec<PodmanPort>),
82    }
83    match Option::<PortsField>::deserialize(deserializer)? {
84        Some(PortsField::Scalar(s)) => Ok(s),
85        Some(PortsField::Array(arr)) => Ok(format_podman_ports(&arr)),
86        None => Ok(String::new()),
87    }
88}
89
90#[derive(Deserialize)]
91struct PodmanPort {
92    #[serde(default)]
93    host_ip: String,
94    #[serde(default)]
95    container_port: u32,
96    #[serde(default)]
97    host_port: u32,
98    #[serde(default = "podman_port_default_range")]
99    range: u32,
100    #[serde(default)]
101    protocol: String,
102}
103
104fn podman_port_default_range() -> u32 {
105    1
106}
107
108fn format_podman_ports(ports: &[PodmanPort]) -> String {
109    // ~24 chars per typical port entry. Pre-allocating avoids the
110    // intermediate Vec<String> + repeated re-allocations that the prior
111    // map/collect/join chain produced for compose stacks with many
112    // published ports.
113    let mut out = String::with_capacity(ports.len().saturating_mul(24));
114    for (i, p) in ports.iter().enumerate() {
115        if i > 0 {
116            out.push_str(", ");
117        }
118        write_podman_port(p, &mut out);
119    }
120    out
121}
122
123fn write_podman_port(p: &PodmanPort, out: &mut String) {
124    use std::fmt::Write as _;
125    let protocol = if p.protocol.is_empty() {
126        "tcp"
127    } else {
128        p.protocol.as_str()
129    };
130    if p.host_port != 0 {
131        // Podman emits an empty `host_ip` for both IPv4 wildcard and IPv6
132        // wildcard binds. Omit the prefix when unknown rather than
133        // mis-claim IPv4. Concrete addresses (e.g. 127.0.0.1, ::1) render
134        // verbatim with the docker `addr:port->...` form.
135        if !p.host_ip.is_empty() {
136            let _ = write!(out, "{}:", p.host_ip);
137        }
138        if p.range > 1 {
139            let _ = write!(
140                out,
141                "{}-{}->",
142                p.host_port,
143                p.host_port.saturating_add(p.range.saturating_sub(1))
144            );
145        } else {
146            let _ = write!(out, "{}->", p.host_port);
147        }
148    }
149    if p.range > 1 {
150        let _ = write!(
151            out,
152            "{}-{}",
153            p.container_port,
154            p.container_port.saturating_add(p.range.saturating_sub(1))
155        );
156    } else {
157        let _ = write!(out, "{}", p.container_port);
158    }
159    let _ = write!(out, "/{protocol}");
160}
161
162/// Try to parse one NDJSON line into `ContainerInfo`. Returns `None`
163/// for blank/non-JSON lines (MOTD/banner) without logging. JSON-shaped
164/// lines that fail to match the schema log at debug level so missing
165/// containers can be correlated to a concrete parse error rather than
166/// guessed from a shrunken list.
167fn try_parse_container_line(trimmed: &str) -> Option<ContainerInfo> {
168    if trimmed.is_empty() {
169        return None;
170    }
171    match serde_json::from_str(trimmed) {
172        Ok(c) => Some(c),
173        Err(e) if trimmed.starts_with('{') => {
174            log::debug!(
175                "[external] container parse: dropped JSON line: {} (err: {})",
176                &trimmed[..trimmed.len().min(120)],
177                e
178            );
179            None
180        }
181        Err(_) => None,
182    }
183}
184
185/// Parse NDJSON output from `docker ps --format '{{json .}}'` or
186/// `podman ps --format '{{json .}}'`. Used by tests and the public
187/// crate API exposed via `lib.rs`; the live SSH path streams through
188/// `parse_container_output` directly, so the binary build sees this
189/// helper as unused and the lint must be silenced.
190#[allow(dead_code)]
191pub fn parse_container_ps(output: &str) -> Vec<ContainerInfo> {
192    output
193        .lines()
194        .filter_map(|line| try_parse_container_line(line.trim()))
195        .collect()
196}
197
198// ---------------------------------------------------------------------------
199// ContainerRuntime
200// ---------------------------------------------------------------------------
201
202/// Supported container runtimes.
203#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
204pub enum ContainerRuntime {
205    Docker,
206    Podman,
207}
208
209impl ContainerRuntime {
210    /// Returns the CLI binary name.
211    pub fn as_str(&self) -> &'static str {
212        match self {
213            ContainerRuntime::Docker => "docker",
214            ContainerRuntime::Podman => "podman",
215        }
216    }
217}
218
219/// Detect runtime from command output by matching the LAST non-empty trimmed
220/// line. Only "docker" or "podman" are accepted. MOTD-resilient.
221/// Currently unused (sentinel-based detection handles this inline) but kept
222/// as a public utility for potential future two-step detection paths.
223#[allow(dead_code)]
224pub fn parse_runtime(output: &str) -> Option<ContainerRuntime> {
225    let last = output
226        .lines()
227        .rev()
228        .map(|l| l.trim())
229        .find(|l| !l.is_empty())?;
230    match last {
231        "docker" => Some(ContainerRuntime::Docker),
232        "podman" => Some(ContainerRuntime::Podman),
233        _ => None,
234    }
235}
236
237// ---------------------------------------------------------------------------
238// ContainerAction
239// ---------------------------------------------------------------------------
240
241/// Actions that can be performed on a container.
242#[derive(Copy, Clone, Debug, PartialEq)]
243pub enum ContainerAction {
244    Start,
245    Stop,
246    Restart,
247}
248
249impl ContainerAction {
250    /// Returns the CLI sub-command string.
251    pub fn as_str(&self) -> &'static str {
252        match self {
253            ContainerAction::Start => "start",
254            ContainerAction::Stop => "stop",
255            ContainerAction::Restart => "restart",
256        }
257    }
258}
259
260/// Build the shell command to perform an action on a container.
261pub fn container_action_command(
262    runtime: ContainerRuntime,
263    action: ContainerAction,
264    container_id: &str,
265) -> String {
266    format!("{} {} {}", runtime.as_str(), action.as_str(), container_id)
267}
268
269// ---------------------------------------------------------------------------
270// Container ID validation
271// ---------------------------------------------------------------------------
272
273/// Validate a container ID or name.
274/// Accepts ASCII alphanumeric, hyphen, underscore, dot.
275/// Rejects empty, non-ASCII, shell metacharacters, colon.
276pub fn validate_container_id(id: &str) -> Result<(), String> {
277    if id.is_empty() {
278        return Err(crate::messages::CONTAINER_ID_EMPTY.to_string());
279    }
280    for c in id.chars() {
281        if !c.is_ascii_alphanumeric() && c != '-' && c != '_' && c != '.' {
282            return Err(crate::messages::container_id_invalid_char(c));
283        }
284    }
285    Ok(())
286}
287
288// ---------------------------------------------------------------------------
289// Combined SSH command + output parsing
290// ---------------------------------------------------------------------------
291
292/// Build the SSH command string for listing containers. Output is the
293/// container NDJSON, then the `##purple:engine##` sentinel, then the
294/// daemon version on its own line. The version subcall is suffixed with
295/// `|| true` so its failure cannot mask a `docker ps` error: the chain
296/// surfaces ps's exit code, while a missing version line just yields
297/// `engine_version: None` downstream.
298///
299/// - `Some(Docker)` / `Some(Podman)`: direct listing for the known runtime.
300/// - `None`: combined detection + listing with sentinel markers in one SSH call.
301pub fn container_list_command(runtime: Option<ContainerRuntime>) -> String {
302    match runtime {
303        Some(ContainerRuntime::Docker) => concat!(
304            "docker ps -a --format '{{json .}}' && ",
305            "echo '##purple:engine##' && ",
306            "{ docker version --format '{{.Server.Version}}' 2>/dev/null || true; }"
307        )
308        .to_string(),
309        Some(ContainerRuntime::Podman) => concat!(
310            "podman ps -a --format '{{json .}}' && ",
311            "echo '##purple:engine##' && ",
312            "{ podman version --format '{{.Server.Version}}' 2>/dev/null || true; }"
313        )
314        .to_string(),
315        None => concat!(
316            "if command -v docker >/dev/null 2>&1; then ",
317            "echo '##purple:docker##' && docker ps -a --format '{{json .}}' && ",
318            "echo '##purple:engine##' && ",
319            "{ docker version --format '{{.Server.Version}}' 2>/dev/null || true; }; ",
320            "elif command -v podman >/dev/null 2>&1; then ",
321            "echo '##purple:podman##' && podman ps -a --format '{{json .}}' && ",
322            "echo '##purple:engine##' && ",
323            "{ podman version --format '{{.Server.Version}}' 2>/dev/null || true; }; ",
324            "else echo '##purple:none##'; fi"
325        )
326        .to_string(),
327    }
328}
329
330/// Parsed result of a container listing command. `engine_version` is the
331/// daemon's `Server.Version` (best-effort, `None` when the version sub-call
332/// failed or the remote runtime predates the engine sentinel).
333#[derive(Debug, Clone, PartialEq)]
334pub struct ContainerListing {
335    pub runtime: ContainerRuntime,
336    pub engine_version: Option<String>,
337    pub containers: Vec<ContainerInfo>,
338}
339
340/// Parse the stdout of a container listing command.
341///
342/// When sentinels are present (combined detection run): extract runtime from
343/// the sentinel line, parse remaining lines as NDJSON. When `caller_runtime`
344/// is provided (subsequent run with known runtime): parse all lines as NDJSON.
345/// In both cases, `##purple:engine##` splits the listing from the optional
346/// trailing daemon version line.
347pub fn parse_container_output(
348    output: &str,
349    caller_runtime: Option<ContainerRuntime>,
350) -> Result<ContainerListing, String> {
351    let runtime = match output
352        .lines()
353        .map(str::trim)
354        .find(|l| l.starts_with("##purple:") && (*l != "##purple:engine##"))
355    {
356        Some("##purple:none##") => {
357            return Err(crate::messages::CONTAINER_RUNTIME_MISSING.to_string());
358        }
359        Some("##purple:docker##") => ContainerRuntime::Docker,
360        Some("##purple:podman##") => ContainerRuntime::Podman,
361        Some(other) => return Err(crate::messages::container_unknown_sentinel(other)),
362        None => match caller_runtime {
363            Some(rt) => rt,
364            None => return Err("No sentinel found and no runtime provided.".to_string()),
365        },
366    };
367
368    // Bound the version capture to the first non-empty post-sentinel line.
369    // A trailing logout banner or MOTD after `docker version` would
370    // otherwise concat into the cached engine_version and surface as
371    // "25.0.3\n-- session closed --" in the Runtime field.
372    let mut engine_version: Option<String> = None;
373    let mut after_engine = false;
374    let mut containers: Vec<ContainerInfo> = Vec::new();
375    // Stream-parse each NDJSON line during the sentinel sweep so we never
376    // build an intermediate copy of the listing block. At 1000 containers
377    // that intermediate buffer would cost ~300 KB and an extra `.lines()`
378    // walk; this loop is O(lines) with zero auxiliary allocation.
379    for line in output.lines() {
380        let trimmed = line.trim();
381        if trimmed == "##purple:engine##" {
382            after_engine = true;
383            continue;
384        }
385        if trimmed.starts_with("##purple:") {
386            continue;
387        }
388        if after_engine {
389            if !trimmed.is_empty() && engine_version.is_none() {
390                engine_version = Some(trimmed.to_string());
391            }
392            continue;
393        }
394        if let Some(c) = try_parse_container_line(trimmed) {
395            containers.push(c);
396        }
397    }
398
399    // Fedora CoreOS, podman-machine and other distros symlink `docker` to
400    // `podman`. Detection picks the docker branch but the JSON shape is
401    // pure podman (array `Names`, lowercase `Id`). When that happens we
402    // relabel the runtime so downstream consumers (MCP runtime field, host
403    // detail label, sort/filter by runtime) match reality.
404    let runtime = if matches!(runtime, ContainerRuntime::Docker) && looks_like_podman(output) {
405        log::debug!(
406            "[external] container detection: docker sentinel emitted podman-shaped JSON, relabeling runtime to Podman"
407        );
408        ContainerRuntime::Podman
409    } else {
410        runtime
411    };
412
413    log::debug!(
414        "[external] container listing parsed: runtime={:?} version={:?} containers={}",
415        runtime,
416        engine_version,
417        containers.len()
418    );
419    Ok(ContainerListing {
420        runtime,
421        engine_version,
422        containers,
423    })
424}
425
426/// Heuristic: does the raw `ps` output look like podman JSON?
427/// Podman emits `"Names":[` (array) and `"Id":` (lowercase d) for every row.
428/// Docker emits `"Names":"` (string) and `"ID":` (uppercase D). We sample the
429/// first JSON-shaped non-sentinel line. The check is fast (substring scan)
430/// and only matters when the docker sentinel was emitted by a podman shim.
431/// Accepts both `"Names":[` and `"Names": [` (pretty-printed) so handwritten
432/// test fixtures and any intermediate JSON formatter cannot defeat the
433/// detector silently.
434fn looks_like_podman(output: &str) -> bool {
435    for line in output.lines() {
436        let trimmed = line.trim();
437        if trimmed.is_empty() || trimmed.starts_with("##purple:") || !trimmed.starts_with('{') {
438            continue;
439        }
440        return trimmed.contains("\"Names\":[") || trimmed.contains("\"Names\": [");
441    }
442    false
443}
444
445// ---------------------------------------------------------------------------
446// SSH fetch functions
447// ---------------------------------------------------------------------------
448
449/// Error from a container listing operation. Preserves the detected runtime
450/// even when the `ps` command fails so it can be cached for future calls.
451#[derive(Debug)]
452pub struct ContainerError {
453    pub runtime: Option<ContainerRuntime>,
454    pub message: String,
455}
456
457impl std::fmt::Display for ContainerError {
458    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
459        write!(f, "{}", self.message)
460    }
461}
462
463/// Translate SSH stderr into a user-friendly error message.
464fn friendly_container_error(stderr: &str, code: Option<i32>) -> String {
465    let lower = stderr.to_lowercase();
466    if lower.contains("remote host identification has changed")
467        || (lower.contains("host key for") && lower.contains("has changed"))
468    {
469        log::debug!("[external] Host key CHANGED detected; returning HOST_KEY_CHANGED toast");
470        crate::messages::HOST_KEY_CHANGED.to_string()
471    } else if lower.contains("host key verification failed")
472        || lower.contains("no matching host key")
473        || lower.contains("no ed25519 host key is known")
474        || lower.contains("no rsa host key is known")
475        || lower.contains("no ecdsa host key is known")
476        || lower.contains("host key is not known")
477    {
478        log::debug!("[external] Host key UNKNOWN detected; returning HOST_KEY_UNKNOWN toast");
479        crate::messages::HOST_KEY_UNKNOWN.to_string()
480    } else if lower.contains("command not found") {
481        crate::messages::CONTAINER_RUNTIME_NOT_FOUND.to_string()
482    } else if lower.contains("permission denied") || lower.contains("got permission denied") {
483        crate::messages::CONTAINER_PERMISSION_DENIED.to_string()
484    } else if lower.contains("cannot connect to the docker daemon")
485        || lower.contains("cannot connect to podman")
486    {
487        crate::messages::CONTAINER_DAEMON_NOT_RUNNING.to_string()
488    } else if lower.contains("connection refused") {
489        crate::messages::CONTAINER_CONNECTION_REFUSED.to_string()
490    } else if lower.contains("no route to host") || lower.contains("network is unreachable") {
491        crate::messages::CONTAINER_HOST_UNREACHABLE.to_string()
492    } else {
493        crate::messages::container_command_failed(code.unwrap_or(1))
494    }
495}
496
497/// Fetch container list synchronously via SSH.
498/// Follows the `fetch_remote_listing` pattern.
499pub fn fetch_containers(
500    ctx: &SshContext<'_>,
501    cached_runtime: Option<ContainerRuntime>,
502) -> Result<ContainerListing, ContainerError> {
503    let command = container_list_command(cached_runtime);
504    let result = crate::snippet::run_snippet(
505        ctx.alias,
506        ctx.config_path,
507        ctx.env,
508        &command,
509        ctx.askpass,
510        ctx.bw_session,
511        true,
512        ctx.has_tunnel,
513    );
514    let alias = ctx.alias;
515    match result {
516        Ok(r) if r.status.success() => {
517            parse_container_output(&r.stdout, cached_runtime).map_err(|e| {
518                error!("[external] Container list parse failed: alias={alias}: {e}");
519                ContainerError {
520                    runtime: cached_runtime,
521                    message: e,
522                }
523            })
524        }
525        Ok(r) => {
526            let stderr = r.stderr.trim().to_string();
527            let msg = friendly_container_error(&stderr, r.status.code());
528            error!("[external] Container fetch failed: alias={alias}: {msg}");
529            Err(ContainerError {
530                runtime: cached_runtime,
531                message: msg,
532            })
533        }
534        Err(e) => {
535            error!("[external] Container fetch failed: alias={alias}: {e}");
536            Err(ContainerError {
537                runtime: cached_runtime,
538                message: e.to_string(),
539            })
540        }
541    }
542}
543
544/// Spawn a background thread to fetch container listings.
545/// Follows the `spawn_remote_listing` pattern.
546pub fn spawn_container_listing<F>(
547    ctx: OwnedSshContext,
548    cached_runtime: Option<ContainerRuntime>,
549    send: F,
550) where
551    F: FnOnce(String, Result<ContainerListing, ContainerError>) + Send + 'static,
552{
553    std::thread::spawn(move || {
554        let borrowed = SshContext {
555            alias: &ctx.alias,
556            config_path: &ctx.config_path,
557            askpass: ctx.askpass.as_deref(),
558            bw_session: ctx.bw_session.as_deref(),
559            has_tunnel: ctx.has_tunnel,
560            env: &ctx.env,
561        };
562        let result = fetch_containers(&borrowed, cached_runtime);
563        send(ctx.alias, result);
564    });
565}
566
567/// Spawn a background thread to perform a container action (start/stop/restart).
568/// Validates the container ID before executing.
569pub fn spawn_container_action<F>(
570    ctx: OwnedSshContext,
571    runtime: ContainerRuntime,
572    action: ContainerAction,
573    container_id: String,
574    send: F,
575) where
576    F: FnOnce(String, ContainerAction, Result<(), String>) + Send + 'static,
577{
578    std::thread::spawn(move || {
579        if let Err(e) = validate_container_id(&container_id) {
580            log::debug!(
581                "[purple] container action {} blocked on alias={}: invalid container_id: {}",
582                action.as_str(),
583                ctx.alias,
584                e
585            );
586            send(ctx.alias, action, Err(e));
587            return;
588        }
589        let alias = &ctx.alias;
590        info!(
591            "Container action: {} container={container_id} alias={alias}",
592            action.as_str()
593        );
594        let command = container_action_command(runtime, action, &container_id);
595        let result = crate::snippet::run_snippet(
596            alias,
597            &ctx.config_path,
598            &ctx.env,
599            &command,
600            ctx.askpass.as_deref(),
601            ctx.bw_session.as_deref(),
602            true,
603            ctx.has_tunnel,
604        );
605        match result {
606            Ok(r) if r.status.success() => send(ctx.alias, action, Ok(())),
607            Ok(r) => {
608                let err = friendly_container_error(r.stderr.trim(), r.status.code());
609                error!(
610                    "[external] Container {} failed: alias={alias} container={container_id}: {err}",
611                    action.as_str()
612                );
613                send(ctx.alias, action, Err(err));
614            }
615            Err(e) => {
616                error!(
617                    "[external] Container {} failed: alias={alias} container={container_id}: {e}",
618                    action.as_str()
619                );
620                send(ctx.alias, action, Err(e.to_string()));
621            }
622        }
623    });
624}
625
626// ---------------------------------------------------------------------------
627// ContainerInspect: subset of `docker inspect` output we surface in the UI
628// ---------------------------------------------------------------------------
629
630/// Parsed subset of `docker inspect <id>` (or `podman inspect`). Only the
631/// fields purple's container detail panel renders are extracted; the rest
632/// of the JSON document is discarded so cache size stays bounded.
633#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
634pub struct ContainerInspect {
635    pub exit_code: i32,
636    pub oom_killed: bool,
637    pub started_at: String,
638    pub finished_at: String,
639    pub created_at: String,
640    /// `Some("healthy" | "unhealthy" | "starting")` when the image defines
641    /// a HEALTHCHECK. `None` when no healthcheck is configured.
642    pub health: Option<String>,
643    pub restart_count: u32,
644    pub command: Option<Vec<String>>,
645    pub entrypoint: Option<Vec<String>>,
646    pub env_count: usize,
647    pub mount_count: usize,
648    pub networks: Vec<NetworkInfo>,
649    // Audit-relevant fields surfaced in the right-side detail panel.
650    pub image_digest: Option<String>,
651    pub restart_policy: Option<String>,
652    pub user: Option<String>,
653    pub privileged: bool,
654    pub readonly_rootfs: bool,
655    pub apparmor_profile: Option<String>,
656    pub seccomp_profile: Option<String>,
657    pub cap_add: Vec<String>,
658    pub cap_drop: Vec<String>,
659    pub mounts: Vec<MountInfo>,
660    pub compose_project: Option<String>,
661    pub compose_service: Option<String>,
662    // Lifecycle / runtime details surfaced in the LIFECYCLE card.
663    pub pid: Option<u32>,
664    pub stop_signal: Option<String>,
665    pub stop_timeout: Option<u32>,
666    // App identity from OCI image labels (visible in APP card).
667    pub image_version: Option<String>,
668    pub image_revision: Option<String>,
669    pub image_source: Option<String>,
670    pub working_dir: Option<String>,
671    pub hostname: Option<String>,
672    // Resource constraints (RESOURCES card). 0 / None means unlimited.
673    pub memory_limit: Option<u64>,
674    pub cpu_limit_nanos: Option<u64>,
675    pub pids_limit: Option<i64>,
676    pub log_driver: Option<String>,
677    // Network mode (NETWORK card): bridge / host / none / container:xyz.
678    pub network_mode: Option<String>,
679    // Healthcheck definition + recent stats (HEALTH card when present).
680    pub health_test: Option<Vec<String>>,
681    pub health_interval_ns: Option<u64>,
682    pub health_failing_streak: Option<u32>,
683}
684
685#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
686pub struct NetworkInfo {
687    pub name: String,
688    pub ip_address: String,
689}
690
691#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
692pub struct MountInfo {
693    pub source: String,
694    pub destination: String,
695    pub read_only: bool,
696}
697
698/// Build the SSH command string for inspecting a single container.
699///
700/// Callers MUST validate `container_id` with `validate_container_id` before
701/// reaching this builder. Restricted to crate visibility so a future caller
702/// outside this crate cannot accidentally skip the guard.
703pub(crate) fn container_inspect_command(runtime: ContainerRuntime, container_id: &str) -> String {
704    format!("{} inspect {}", runtime.as_str(), container_id)
705}
706
707/// Translate a non-zero docker/podman exit code into a short
708/// human-readable hint. Returns `None` for codes without a well-known
709/// meaning so the UI can fall back to the bare number. Exit 0 has no
710/// entry because the detail panel only annotates failed exits.
711/// Sources: docker docs + Linux signal table.
712pub fn exit_code_meaning(code: i32) -> Option<&'static str> {
713    match code {
714        1 => Some("application error"),
715        125 => Some("docker run failed"),
716        126 => Some("command not executable"),
717        127 => Some("command not found"),
718        130 => Some("interrupted (SIGINT)"),
719        137 => Some("killed (SIGKILL / OOM)"),
720        139 => Some("segfault (SIGSEGV)"),
721        143 => Some("terminated (SIGTERM)"),
722        _ => None,
723    }
724}
725
726/// Parse `docker inspect <id>` stdout into `ContainerInspect`. The command
727/// always returns a JSON array; we take the first element. Missing fields
728/// degrade to defaults rather than fail so a partial response still
729/// renders something useful.
730pub fn parse_container_inspect(output: &str) -> Result<ContainerInspect, String> {
731    let trimmed = output.trim();
732    if trimmed.is_empty() {
733        return Err(crate::messages::CONTAINER_INSPECT_EMPTY.to_string());
734    }
735    let value: serde_json::Value = serde_json::from_str(trimmed)
736        .map_err(|e| crate::messages::container_inspect_parse_failed(&e.to_string()))?;
737    let entry = value
738        .as_array()
739        .and_then(|a| a.first())
740        .ok_or_else(|| crate::messages::CONTAINER_INSPECT_EMPTY.to_string())?;
741
742    let state = &entry["State"];
743    let config = &entry["Config"];
744    let network_settings = &entry["NetworkSettings"];
745
746    let exit_code = state["ExitCode"].as_i64().unwrap_or(0) as i32;
747    // Podman 5.x and docker both emit `OOMKilled`. Podman 3.x (still the
748    // packaged default on Ubuntu 22.04 LTS) emits `OomKilled`. Try both so
749    // OOM-killed containers surface in the ATTENTION card regardless of
750    // remote runtime version.
751    let oom_killed = state["OOMKilled"]
752        .as_bool()
753        .or_else(|| state["OomKilled"].as_bool())
754        .unwrap_or(false);
755    let started_at = state["StartedAt"].as_str().unwrap_or("").to_string();
756    let finished_at = state["FinishedAt"].as_str().unwrap_or("").to_string();
757    let health = state
758        .get("Health")
759        .and_then(|h| h.get("Status"))
760        .and_then(|s| s.as_str())
761        .map(|s| s.to_string());
762    let restart_count = entry["RestartCount"].as_u64().unwrap_or(0) as u32;
763
764    let command = config["Cmd"].as_array().map(|arr| {
765        arr.iter()
766            .filter_map(|v| v.as_str().map(|s| s.to_string()))
767            .collect()
768    });
769    let entrypoint = config["Entrypoint"].as_array().map(|arr| {
770        arr.iter()
771            .filter_map(|v| v.as_str().map(|s| s.to_string()))
772            .collect()
773    });
774    let env_count = config["Env"].as_array().map(|arr| arr.len()).unwrap_or(0);
775    let mount_count = entry["Mounts"].as_array().map(|arr| arr.len()).unwrap_or(0);
776
777    let networks = network_settings
778        .get("Networks")
779        .and_then(|n| n.as_object())
780        .map(|map| {
781            map.iter()
782                .map(|(name, cfg)| NetworkInfo {
783                    name: name.clone(),
784                    ip_address: cfg
785                        .get("IPAddress")
786                        .and_then(|v| v.as_str())
787                        .unwrap_or("")
788                        .to_string(),
789                })
790                .collect::<Vec<_>>()
791        })
792        .unwrap_or_default();
793
794    let host_config = &entry["HostConfig"];
795
796    let image_digest = entry["Image"]
797        .as_str()
798        .filter(|s| !s.is_empty())
799        .map(|s| s.to_string());
800    let restart_policy = host_config
801        .get("RestartPolicy")
802        .and_then(|p| p.get("Name"))
803        .and_then(|s| s.as_str())
804        .filter(|s| !s.is_empty() && *s != "no")
805        .map(|s| s.to_string());
806    let user = config["User"]
807        .as_str()
808        .filter(|s| !s.is_empty())
809        .map(|s| s.to_string());
810    let privileged = host_config["Privileged"].as_bool().unwrap_or(false);
811    let readonly_rootfs = host_config["ReadonlyRootfs"].as_bool().unwrap_or(false);
812    let apparmor_profile = host_config["AppArmorProfile"]
813        .as_str()
814        .or_else(|| entry["AppArmorProfile"].as_str())
815        .filter(|s| !s.is_empty())
816        .map(|s| s.to_string());
817    let seccomp_profile = host_config["SecurityOpt"].as_array().and_then(|arr| {
818        arr.iter()
819            .filter_map(|v| v.as_str())
820            .find_map(|s| s.strip_prefix("seccomp=").map(|v| v.to_string()))
821    });
822    let cap_add = host_config["CapAdd"]
823        .as_array()
824        .map(|arr| {
825            arr.iter()
826                .filter_map(|v| v.as_str().map(|s| s.to_string()))
827                .collect()
828        })
829        .unwrap_or_default();
830    let cap_drop = host_config["CapDrop"]
831        .as_array()
832        .map(|arr| {
833            arr.iter()
834                .filter_map(|v| v.as_str().map(|s| s.to_string()))
835                .collect()
836        })
837        .unwrap_or_default();
838    let mounts = entry["Mounts"]
839        .as_array()
840        .map(|arr| {
841            arr.iter()
842                .map(|m| MountInfo {
843                    source: m["Source"].as_str().unwrap_or("").to_string(),
844                    destination: m["Destination"].as_str().unwrap_or("").to_string(),
845                    read_only: !m["RW"].as_bool().unwrap_or(true),
846                })
847                .collect()
848        })
849        .unwrap_or_default();
850    let labels = config.get("Labels").and_then(|l| l.as_object());
851    let label = |key: &str| {
852        labels
853            .and_then(|l| l.get(key))
854            .and_then(|v| v.as_str())
855            .filter(|s| !s.is_empty())
856            .map(|s| s.to_string())
857    };
858    let compose_project = label("com.docker.compose.project");
859    let compose_service = label("com.docker.compose.service");
860    let image_version = label("org.opencontainers.image.version");
861    let image_revision = label("org.opencontainers.image.revision");
862    let image_source = label("org.opencontainers.image.source");
863
864    let created_at = entry["Created"].as_str().unwrap_or("").to_string();
865    // State.Pid is `0` when the container is not running. Drop the zero so
866    // the UI does not render a misleading "pid 0" row for exited rows.
867    let pid = state["Pid"].as_u64().filter(|n| *n > 0).map(|n| n as u32);
868    let hostname = config["Hostname"]
869        .as_str()
870        .filter(|s| !s.is_empty())
871        .map(|s| s.to_string());
872    let working_dir = config["WorkingDir"]
873        .as_str()
874        .filter(|s| !s.is_empty())
875        .map(|s| s.to_string());
876    let stop_signal = config["StopSignal"]
877        .as_str()
878        .filter(|s| !s.is_empty())
879        .map(|s| s.to_string());
880    let stop_timeout = config["StopTimeout"].as_u64().map(|n| n as u32);
881
882    let network_mode = host_config["NetworkMode"]
883        .as_str()
884        .filter(|s| !s.is_empty() && *s != "default")
885        .map(|s| s.to_string());
886    // HostConfig.Memory is bytes, 0 = unlimited (drop). Same for NanoCpus.
887    let memory_limit = host_config["Memory"].as_u64().filter(|n| *n > 0);
888    let cpu_limit_nanos = host_config["NanoCpus"].as_u64().filter(|n| *n > 0);
889    // PidsLimit is i64. 0 or -1 means unlimited; drop both.
890    let pids_limit = host_config["PidsLimit"].as_i64().filter(|n| *n > 0);
891    // LogConfig.Type defaults to "json-file" on docker. Always carry it
892    // so the renderer can decide whether to surface "Logs" only when
893    // non-default.
894    let log_driver = host_config
895        .get("LogConfig")
896        .and_then(|l| l.get("Type"))
897        .and_then(|v| v.as_str())
898        .filter(|s| !s.is_empty())
899        .map(|s| s.to_string());
900
901    let healthcheck = config.get("Healthcheck");
902    let health_test = healthcheck
903        .and_then(|h| h.get("Test"))
904        .and_then(|t| t.as_array())
905        .map(|arr| {
906            arr.iter()
907                .filter_map(|v| v.as_str().map(|s| s.to_string()))
908                .collect::<Vec<_>>()
909        })
910        .filter(|v| !v.is_empty());
911    let health_interval_ns = healthcheck
912        .and_then(|h| h.get("Interval"))
913        .and_then(|v| v.as_u64())
914        .filter(|n| *n > 0);
915    let health_failing_streak = state
916        .get("Health")
917        .and_then(|h| h.get("FailingStreak"))
918        .and_then(|v| v.as_u64())
919        .map(|n| n as u32);
920
921    Ok(ContainerInspect {
922        exit_code,
923        oom_killed,
924        started_at,
925        finished_at,
926        created_at,
927        health,
928        restart_count,
929        command,
930        entrypoint,
931        env_count,
932        mount_count,
933        networks,
934        image_digest,
935        restart_policy,
936        user,
937        privileged,
938        readonly_rootfs,
939        apparmor_profile,
940        seccomp_profile,
941        cap_add,
942        cap_drop,
943        mounts,
944        compose_project,
945        compose_service,
946        pid,
947        stop_signal,
948        stop_timeout,
949        image_version,
950        image_revision,
951        image_source,
952        working_dir,
953        hostname,
954        memory_limit,
955        cpu_limit_nanos,
956        pids_limit,
957        log_driver,
958        network_mode,
959        health_test,
960        health_interval_ns,
961        health_failing_streak,
962    })
963}
964
965/// Parse a Docker `Up …` status string into a compact uptime label.
966/// Returns `None` for any non-running state (Exited, Created, Restarting,
967/// Paused without an `Up` prefix, empty). Cells render `<1m` for
968/// sub-minute uptimes, `1m` / `5m` / `12h` / `5w` / `3mo` / `2y` otherwise.
969/// Format follows Docker's `units.HumanDuration`.
970pub fn parse_uptime_from_status(s: &str) -> Option<String> {
971    let body = s.strip_prefix("Up ")?;
972    let body = body.split('(').next()?.trim();
973    if body == "Less than a second" {
974        return Some("<1m".to_string());
975    }
976    if body == "About a minute" {
977        return Some("1m".to_string());
978    }
979    if body == "About an hour" {
980        return Some("1h".to_string());
981    }
982    let mut parts = body.split_whitespace();
983    let count: u64 = parts.next()?.parse().ok()?;
984    let unit = parts.next()?;
985    let suffix = match unit {
986        "second" | "seconds" => return Some("<1m".to_string()),
987        "minute" | "minutes" => "m",
988        "hour" | "hours" => "h",
989        "day" | "days" => "d",
990        "week" | "weeks" => "w",
991        "month" | "months" => "mo",
992        "year" | "years" => "y",
993        _ => return None,
994    };
995    Some(format!("{count}{suffix}"))
996}
997
998/// Synchronously fetch + parse `container inspect`. Validates the
999/// container ID before issuing the SSH call.
1000pub fn fetch_container_inspect(
1001    ctx: &SshContext<'_>,
1002    runtime: ContainerRuntime,
1003    container_id: &str,
1004) -> Result<ContainerInspect, String> {
1005    validate_container_id(container_id)?;
1006    let command = container_inspect_command(runtime, container_id);
1007    let result = crate::snippet::run_snippet(
1008        ctx.alias,
1009        ctx.config_path,
1010        ctx.env,
1011        &command,
1012        ctx.askpass,
1013        ctx.bw_session,
1014        true,
1015        ctx.has_tunnel,
1016    );
1017    match result {
1018        Ok(r) if r.status.success() => parse_container_inspect(&r.stdout),
1019        Ok(r) => Err(crate::messages::container_command_failed(
1020            r.status.code().unwrap_or(1),
1021        )),
1022        Err(e) => Err(e.to_string()),
1023    }
1024}
1025
1026/// Spawn a background thread to run `container inspect`. Mirrors the
1027/// `spawn_container_listing` pattern so the call site looks identical.
1028pub fn spawn_container_inspect_listing<F>(
1029    ctx: OwnedSshContext,
1030    runtime: ContainerRuntime,
1031    container_id: String,
1032    send: F,
1033) where
1034    F: FnOnce(String, String, Result<ContainerInspect, String>) + Send + 'static,
1035{
1036    std::thread::spawn(move || {
1037        let borrowed = SshContext {
1038            alias: &ctx.alias,
1039            config_path: &ctx.config_path,
1040            askpass: ctx.askpass.as_deref(),
1041            bw_session: ctx.bw_session.as_deref(),
1042            has_tunnel: ctx.has_tunnel,
1043            env: &ctx.env,
1044        };
1045        let result = fetch_container_inspect(&borrowed, runtime, &container_id);
1046        send(ctx.alias, container_id, result);
1047    });
1048}
1049
1050/// Build the `<runtime> logs --tail <n> <id>` command. The
1051/// `--tail` cap is enforced server-side so the SSH stream stays
1052/// bounded even on a noisy container.
1053pub(crate) fn container_logs_command(
1054    runtime: ContainerRuntime,
1055    container_id: &str,
1056    tail: usize,
1057) -> String {
1058    format!("{} logs --tail {} {}", runtime.as_str(), tail, container_id)
1059}
1060
1061/// Synchronously fetch logs and split into lines. Returns the raw
1062/// captured stdout split on `\n` so the renderer does not have to
1063/// re-parse. Empty trailing lines are dropped.
1064pub fn fetch_container_logs(
1065    ctx: &SshContext<'_>,
1066    runtime: ContainerRuntime,
1067    container_id: &str,
1068    tail: usize,
1069) -> Result<Vec<String>, String> {
1070    validate_container_id(container_id)?;
1071    let command = container_logs_command(runtime, container_id, tail);
1072    let result = crate::snippet::run_snippet(
1073        ctx.alias,
1074        ctx.config_path,
1075        ctx.env,
1076        &command,
1077        ctx.askpass,
1078        ctx.bw_session,
1079        true,
1080        ctx.has_tunnel,
1081    );
1082    match result {
1083        Ok(r) if r.status.success() => Ok(parse_log_output(&r.stdout, &r.stderr)),
1084        Ok(r) => Err(crate::messages::container_command_failed(
1085            r.status.code().unwrap_or(1),
1086        )),
1087        Err(e) => Err(e.to_string()),
1088    }
1089}
1090
1091/// Merge stdout (app logs) and stderr (errors) into a single chronological
1092/// stream. Many container runtimes split levels across the two streams;
1093/// re-interleaving them is closer to what `docker logs` shows on a TTY.
1094/// Trailing blank lines are stripped from each stream before merging so a
1095/// stdout block that ends in a newline does not introduce a phantom empty
1096/// row between the two streams.
1097pub(crate) fn parse_log_output(stdout: &str, stderr: &str) -> Vec<String> {
1098    let mut lines: Vec<String> = stdout.lines().map(|s| s.to_string()).collect();
1099    while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1100        lines.pop();
1101    }
1102    for s in stderr.lines() {
1103        lines.push(s.to_string());
1104    }
1105    while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1106        lines.pop();
1107    }
1108    lines
1109}
1110
1111/// Spawn a background thread to run `container logs`. Same shape as
1112/// `spawn_container_inspect_listing`. In demo mode the SSH call is
1113/// short-circuited with a deterministic synthetic log stream so the
1114/// logs viewer (and its `/` search) is exercisable without a remote.
1115pub fn spawn_container_logs_fetch<F>(
1116    ctx: OwnedSshContext,
1117    runtime: ContainerRuntime,
1118    container_id: String,
1119    container_name: String,
1120    tail: usize,
1121    send: F,
1122) where
1123    F: FnOnce(String, String, String, Result<Vec<String>, String>) + Send + 'static,
1124{
1125    if crate::demo_flag::is_demo() {
1126        let lines = demo_log_lines(&container_name, tail);
1127        log::debug!(
1128            "[purple] container_logs_fetch: demo short-circuit alias={} id={} lines={}",
1129            ctx.alias,
1130            container_id,
1131            lines.len()
1132        );
1133        send(ctx.alias, container_id, container_name, Ok(lines));
1134        return;
1135    }
1136    std::thread::spawn(move || {
1137        let borrowed = SshContext {
1138            alias: &ctx.alias,
1139            config_path: &ctx.config_path,
1140            askpass: ctx.askpass.as_deref(),
1141            bw_session: ctx.bw_session.as_deref(),
1142            has_tunnel: ctx.has_tunnel,
1143            env: &ctx.env,
1144        };
1145        let result = fetch_container_logs(&borrowed, runtime, &container_id, tail);
1146        send(ctx.alias, container_id, container_name, result);
1147    });
1148}
1149
1150/// Generate a deterministic stream of fake log lines for demo mode.
1151/// Mixes INFO / WARN / ERROR / DEBUG with realistic-looking content
1152/// (HTTP requests, DB pings, retries, timeouts) so the user can
1153/// usefully press `/` and find matches under `--demo`. Anchored to
1154/// `demo_flag::now_secs()` so timestamps stay stable across renders.
1155pub(crate) fn demo_log_lines(container_name: &str, tail: usize) -> Vec<String> {
1156    use std::time::{Duration, UNIX_EPOCH};
1157    // Cheap hash to fan out per-container variation without bringing
1158    // `rand` into the binary.
1159    let seed: u32 = container_name
1160        .bytes()
1161        .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32));
1162
1163    // Templates rotate every line. Index 0 is the freshest log line.
1164    let templates: &[&str] = &[
1165        "INFO  [{}] handled GET /api/v1/health 200 in 14ms",
1166        "INFO  [{}] handled POST /api/v1/orders 201 in 38ms (user_id={user})",
1167        "DEBUG [{}] cache hit key=session:{user} ttl=3600",
1168        "INFO  [{}] handled GET /api/v1/users/{user} 200 in 11ms",
1169        "WARN  [{}] slow query detected duration=812ms statement=SELECT FROM orders",
1170        "INFO  [{}] connection pool size=12 idle=8 in_use=4",
1171        "DEBUG [{}] flushing metrics batch size=64",
1172        "INFO  [{}] handled GET /api/v1/inventory 200 in 22ms",
1173        "ERROR [{}] upstream timeout after 5000ms target=payments retry=1",
1174        "WARN  [{}] retrying request attempt=2 backoff=250ms",
1175        "INFO  [{}] handled POST /api/v1/login 200 in 31ms",
1176        "DEBUG [{}] gc cycle reclaimed=42MB took=18ms",
1177        "INFO  [{}] heartbeat ok rss=128MB cpu=4%",
1178        "ERROR [{}] failed to acquire lock resource=cache_warmer waiter=3",
1179        "INFO  [{}] handled DELETE /api/v1/sessions/{user} 204 in 9ms",
1180        "WARN  [{}] disk usage at 78% mount=/data threshold=80%",
1181        "INFO  [{}] handled GET /api/v1/search?q=widget 200 in 47ms",
1182        "DEBUG [{}] websocket ping rtt=12ms",
1183    ];
1184
1185    // Always use `demo_flag::now_secs()` even outside demo mode: the
1186    // helper's OnceLock caches the first wallclock value, so repeated
1187    // calls within a process return the same instant. Branching on
1188    // `is_demo()` would let tests cross a second boundary and flake.
1189    let now = crate::demo_flag::now_secs();
1190
1191    // Map each line to a timestamp working backwards from now. One log
1192    // every 3 seconds keeps the time range realistic for a 200-line tail.
1193    let mut lines = Vec::with_capacity(tail);
1194    for i in 0..tail {
1195        let template = templates[(i + seed as usize) % templates.len()];
1196        let user = 1000 + ((seed as usize + i * 7) % 50);
1197        let secs_back = (i as u64) * 3;
1198        let line_time = UNIX_EPOCH + Duration::from_secs(now.saturating_sub(secs_back));
1199        let ts = format_demo_timestamp(line_time);
1200        let body = template
1201            .replace("{}", container_name)
1202            .replace("{user}", &user.to_string());
1203        lines.push(format!("{} {}", ts, body));
1204    }
1205    // Render flush-top with the newest line at the bottom of the
1206    // viewport, matching real `docker logs --tail` output.
1207    lines.reverse();
1208    lines
1209}
1210
1211fn format_demo_timestamp(t: std::time::SystemTime) -> String {
1212    use std::time::UNIX_EPOCH;
1213    let secs = t
1214        .duration_since(UNIX_EPOCH)
1215        .map(|d| d.as_secs())
1216        .unwrap_or(0);
1217    // Fast UTC breakdown without dragging in chrono. Good enough for a
1218    // demo timestamp where leap seconds / DST are irrelevant.
1219    let days_since_epoch = (secs / 86_400) as i64;
1220    let seconds_in_day = (secs % 86_400) as u32;
1221    let h = seconds_in_day / 3600;
1222    let m = (seconds_in_day % 3600) / 60;
1223    let s = seconds_in_day % 60;
1224    let (y, mo, d) = civil_from_days(days_since_epoch);
1225    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", y, mo, d, h, m, s)
1226}
1227
1228/// Convert days-since-1970-01-01 to (year, month, day). Howard Hinnant's
1229/// civil_from_days algorithm — proleptic Gregorian, 1970 = day 0.
1230fn civil_from_days(z: i64) -> (i32, u32, u32) {
1231    let z = z + 719_468;
1232    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
1233    let doe = (z - era * 146_097) as u64;
1234    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1235    let y = yoe as i64 + era * 400;
1236    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1237    let mp = (5 * doy + 2) / 153;
1238    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
1239    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1240    let y = if m <= 2 { y + 1 } else { y };
1241    (y as i32, m, d)
1242}
1243
1244// ---------------------------------------------------------------------------
1245// JSON lines cache
1246// ---------------------------------------------------------------------------
1247
1248/// A cached container listing for a single host. `engine_version` is the
1249/// daemon's `Server.Version` captured during the last refresh, surfaced in
1250/// the host detail panel; `None` means the version sub-call did not return
1251/// or the cache was written by an older purple build.
1252#[derive(Debug, Clone)]
1253pub struct ContainerCacheEntry {
1254    pub timestamp: u64,
1255    pub runtime: ContainerRuntime,
1256    pub engine_version: Option<String>,
1257    pub containers: Vec<ContainerInfo>,
1258}
1259
1260/// Serde helper for a single JSON line in the cache file. `engine_version`
1261/// uses `serde(default)` so cache files written before this field existed
1262/// still deserialize cleanly.
1263#[derive(Serialize, Deserialize)]
1264struct CacheLine {
1265    alias: String,
1266    timestamp: u64,
1267    runtime: ContainerRuntime,
1268    #[serde(default, skip_serializing_if = "Option::is_none")]
1269    engine_version: Option<String>,
1270    containers: Vec<ContainerInfo>,
1271}
1272
1273fn cache_path(paths: Option<&crate::runtime::env::Paths>) -> Option<std::path::PathBuf> {
1274    paths.map(crate::runtime::env::Paths::container_cache)
1275}
1276
1277/// Load container cache from `~/.purple/container_cache.jsonl`.
1278/// Malformed lines are silently ignored. Duplicate aliases: last-write-wins.
1279pub fn load_container_cache(
1280    paths: Option<&crate::runtime::env::Paths>,
1281) -> HashMap<String, ContainerCacheEntry> {
1282    let mut map = HashMap::new();
1283    let Some(path) = cache_path(paths) else {
1284        return map;
1285    };
1286    let Ok(content) = std::fs::read_to_string(&path) else {
1287        return map;
1288    };
1289    for line in content.lines() {
1290        let trimmed = line.trim();
1291        if trimmed.is_empty() {
1292            continue;
1293        }
1294        if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1295            map.insert(
1296                entry.alias,
1297                ContainerCacheEntry {
1298                    timestamp: entry.timestamp,
1299                    runtime: entry.runtime,
1300                    engine_version: entry.engine_version,
1301                    containers: entry.containers,
1302                },
1303            );
1304        }
1305    }
1306    map
1307}
1308
1309/// Parse container cache from JSONL content string (for demo/test use).
1310pub fn parse_container_cache_content(content: &str) -> HashMap<String, ContainerCacheEntry> {
1311    let mut map = HashMap::new();
1312    for line in content.lines() {
1313        let trimmed = line.trim();
1314        if trimmed.is_empty() {
1315            continue;
1316        }
1317        if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1318            map.insert(
1319                entry.alias,
1320                ContainerCacheEntry {
1321                    timestamp: entry.timestamp,
1322                    runtime: entry.runtime,
1323                    engine_version: entry.engine_version,
1324                    containers: entry.containers,
1325                },
1326            );
1327        }
1328    }
1329    map
1330}
1331
1332/// Save container cache to `~/.purple/container_cache.jsonl` via atomic write.
1333pub fn save_container_cache(
1334    paths: Option<&crate::runtime::env::Paths>,
1335    cache: &HashMap<String, ContainerCacheEntry>,
1336) {
1337    if crate::demo_flag::is_demo() {
1338        return;
1339    }
1340    let Some(path) = cache_path(paths) else {
1341        return;
1342    };
1343    let mut lines = Vec::with_capacity(cache.len());
1344    for (alias, entry) in cache {
1345        let line = CacheLine {
1346            alias: alias.clone(),
1347            timestamp: entry.timestamp,
1348            runtime: entry.runtime,
1349            engine_version: entry.engine_version.clone(),
1350            containers: entry.containers.clone(),
1351        };
1352        if let Ok(s) = serde_json::to_string(&line) {
1353            lines.push(s);
1354        }
1355    }
1356    let content = lines.join("\n");
1357    log::debug!(
1358        "[purple] save_container_cache: {} host entries, {} bytes -> {}",
1359        cache.len(),
1360        content.len(),
1361        path.display()
1362    );
1363    if let Err(e) = crate::fs_util::atomic_write(&path, content.as_bytes()) {
1364        log::warn!(
1365            "[config] Failed to write container cache {}: {e}",
1366            path.display()
1367        );
1368    }
1369}
1370
1371// ---------------------------------------------------------------------------
1372// String truncation
1373// ---------------------------------------------------------------------------
1374
1375/// Truncate a string to at most `max` characters. Appends ".." if truncated.
1376pub fn truncate_str(s: &str, max: usize) -> String {
1377    let count = s.chars().count();
1378    if count <= max {
1379        s.to_string()
1380    } else {
1381        let cut = max.saturating_sub(2);
1382        let end = s.char_indices().nth(cut).map(|(i, _)| i).unwrap_or(s.len());
1383        format!("{}..", &s[..end])
1384    }
1385}
1386
1387// ---------------------------------------------------------------------------
1388// Relative time
1389// ---------------------------------------------------------------------------
1390
1391/// Format a duration in seconds as a compact label (`12s`, `5m`,
1392/// `2h`, `3d`). Used for the in-border staleness badge where width
1393/// is precious and the surrounding label (`synced`) already says
1394/// "ago" without the suffix.
1395pub fn format_uptime_short(seconds: u64) -> String {
1396    if seconds < 60 {
1397        format!("{seconds}s")
1398    } else if seconds < 3600 {
1399        format!("{}m", seconds / 60)
1400    } else if seconds < 86400 {
1401        format!("{}h", seconds / 3600)
1402    } else {
1403        format!("{}d", seconds / 86400)
1404    }
1405}
1406
1407/// Format a Unix timestamp as a human-readable relative time string.
1408/// Honours `demo_flag::now_secs()` when demo mode is active so visual
1409/// regression goldens stay byte-stable across long-running test
1410/// processes (same pattern as `history::format_time_ago`).
1411pub fn format_relative_time(timestamp: u64) -> String {
1412    let now = if crate::demo_flag::is_demo() {
1413        crate::demo_flag::now_secs()
1414    } else {
1415        SystemTime::now()
1416            .duration_since(UNIX_EPOCH)
1417            .unwrap_or_default()
1418            .as_secs()
1419    };
1420    let diff = now.saturating_sub(timestamp);
1421    if diff < 60 {
1422        "just now".to_string()
1423    } else if diff < 3600 {
1424        format!("{}m ago", diff / 60)
1425    } else if diff < 86400 {
1426        format!("{}h ago", diff / 3600)
1427    } else {
1428        format!("{}d ago", diff / 86400)
1429    }
1430}
1431
1432// ---------------------------------------------------------------------------
1433// Tests
1434// ---------------------------------------------------------------------------
1435
1436#[cfg(test)]
1437#[path = "containers_tests.rs"]
1438mod tests;