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            // A non-zero remote exit (docker missing, daemon down, ...) is a
529            // routine remote status, not an ssh connection failure: keep it out
530            // of the error level.
531            log::log!(
532                crate::connection::remote_exit_log_level(r.status.code().unwrap_or(-1)),
533                "[external] Container fetch failed: alias={alias}: {msg}"
534            );
535            Err(ContainerError {
536                runtime: cached_runtime,
537                message: msg,
538            })
539        }
540        Err(e) => {
541            error!("[external] Container fetch failed: alias={alias}: {e}");
542            Err(ContainerError {
543                runtime: cached_runtime,
544                message: e.to_string(),
545            })
546        }
547    }
548}
549
550/// Spawn a background thread to fetch container listings.
551/// Follows the `spawn_remote_listing` pattern.
552pub fn spawn_container_listing<F>(
553    ctx: OwnedSshContext,
554    cached_runtime: Option<ContainerRuntime>,
555    send: F,
556) where
557    F: FnOnce(String, Result<ContainerListing, ContainerError>) + Send + 'static,
558{
559    std::thread::spawn(move || {
560        let borrowed = SshContext {
561            alias: &ctx.alias,
562            config_path: &ctx.config_path,
563            askpass: ctx.askpass.as_deref(),
564            bw_session: ctx.bw_session.as_deref(),
565            has_tunnel: ctx.has_tunnel,
566            env: &ctx.env,
567        };
568        let result = fetch_containers(&borrowed, cached_runtime);
569        send(ctx.alias, result);
570    });
571}
572
573/// Spawn a background thread to perform a container action (start/stop/restart).
574/// Validates the container ID before executing.
575pub fn spawn_container_action<F>(
576    ctx: OwnedSshContext,
577    runtime: ContainerRuntime,
578    action: ContainerAction,
579    container_id: String,
580    send: F,
581) where
582    F: FnOnce(String, ContainerAction, Result<(), String>) + Send + 'static,
583{
584    std::thread::spawn(move || {
585        if let Err(e) = validate_container_id(&container_id) {
586            log::debug!(
587                "[purple] container action {} blocked on alias={}: invalid container_id: {}",
588                action.as_str(),
589                ctx.alias,
590                e
591            );
592            send(ctx.alias, action, Err(e));
593            return;
594        }
595        let alias = &ctx.alias;
596        info!(
597            "[external] Container action: {} container={container_id} alias={alias}",
598            action.as_str()
599        );
600        let command = container_action_command(runtime, action, &container_id);
601        let result = crate::snippet::run_snippet(
602            alias,
603            &ctx.config_path,
604            &ctx.env,
605            &command,
606            ctx.askpass.as_deref(),
607            ctx.bw_session.as_deref(),
608            true,
609            ctx.has_tunnel,
610        );
611        match result {
612            Ok(r) if r.status.success() => send(ctx.alias, action, Ok(())),
613            Ok(r) => {
614                let err = friendly_container_error(r.stderr.trim(), r.status.code());
615                // Routine remote exit (already stopped, no such container, ...)
616                // stays out of the error level; only an ssh transport failure
617                // (255) is a genuine connection error.
618                log::log!(
619                    crate::connection::remote_exit_log_level(r.status.code().unwrap_or(-1)),
620                    "[external] Container {} failed: alias={alias} container={container_id}: {err}",
621                    action.as_str()
622                );
623                send(ctx.alias, action, Err(err));
624            }
625            Err(e) => {
626                error!(
627                    "[external] Container {} failed: alias={alias} container={container_id}: {e}",
628                    action.as_str()
629                );
630                send(ctx.alias, action, Err(e.to_string()));
631            }
632        }
633    });
634}
635
636// ---------------------------------------------------------------------------
637// ContainerInspect: subset of `docker inspect` output we surface in the UI
638// ---------------------------------------------------------------------------
639
640/// Parsed subset of `docker inspect <id>` (or `podman inspect`). Only the
641/// fields purple's container detail panel renders are extracted; the rest
642/// of the JSON document is discarded so cache size stays bounded.
643#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
644pub struct ContainerInspect {
645    pub exit_code: i32,
646    pub oom_killed: bool,
647    pub started_at: String,
648    pub finished_at: String,
649    pub created_at: String,
650    /// `Some("healthy" | "unhealthy" | "starting")` when the image defines
651    /// a HEALTHCHECK. `None` when no healthcheck is configured.
652    pub health: Option<String>,
653    pub restart_count: u32,
654    pub command: Option<Vec<String>>,
655    pub entrypoint: Option<Vec<String>>,
656    pub env_count: usize,
657    pub mount_count: usize,
658    pub networks: Vec<NetworkInfo>,
659    // Audit-relevant fields surfaced in the right-side detail panel.
660    pub image_digest: Option<String>,
661    pub restart_policy: Option<String>,
662    pub user: Option<String>,
663    pub privileged: bool,
664    pub readonly_rootfs: bool,
665    pub apparmor_profile: Option<String>,
666    pub seccomp_profile: Option<String>,
667    pub cap_add: Vec<String>,
668    pub cap_drop: Vec<String>,
669    pub mounts: Vec<MountInfo>,
670    pub compose_project: Option<String>,
671    pub compose_service: Option<String>,
672    // Lifecycle / runtime details surfaced in the LIFECYCLE card.
673    pub pid: Option<u32>,
674    pub stop_signal: Option<String>,
675    pub stop_timeout: Option<u32>,
676    // App identity from OCI image labels (visible in APP card).
677    pub image_version: Option<String>,
678    pub image_revision: Option<String>,
679    pub image_source: Option<String>,
680    pub working_dir: Option<String>,
681    pub hostname: Option<String>,
682    // Resource constraints (RESOURCES card). 0 / None means unlimited.
683    pub memory_limit: Option<u64>,
684    pub cpu_limit_nanos: Option<u64>,
685    pub pids_limit: Option<i64>,
686    pub log_driver: Option<String>,
687    // Network mode (NETWORK card): bridge / host / none / container:xyz.
688    pub network_mode: Option<String>,
689    // Healthcheck definition + recent stats (HEALTH card when present).
690    pub health_test: Option<Vec<String>>,
691    pub health_interval_ns: Option<u64>,
692    pub health_failing_streak: Option<u32>,
693}
694
695#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
696pub struct NetworkInfo {
697    pub name: String,
698    pub ip_address: String,
699}
700
701#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
702pub struct MountInfo {
703    pub source: String,
704    pub destination: String,
705    pub read_only: bool,
706}
707
708/// Build the SSH command string for inspecting a single container.
709///
710/// Callers MUST validate `container_id` with `validate_container_id` before
711/// reaching this builder. Restricted to crate visibility so a future caller
712/// outside this crate cannot accidentally skip the guard.
713pub(crate) fn container_inspect_command(runtime: ContainerRuntime, container_id: &str) -> String {
714    format!("{} inspect {}", runtime.as_str(), container_id)
715}
716
717/// Translate a non-zero docker/podman exit code into a short
718/// human-readable hint. Returns `None` for codes without a well-known
719/// meaning so the UI can fall back to the bare number. Exit 0 has no
720/// entry because the detail panel only annotates failed exits.
721/// Sources: docker docs + Linux signal table.
722pub fn exit_code_meaning(code: i32) -> Option<&'static str> {
723    match code {
724        1 => Some("application error"),
725        125 => Some("docker run failed"),
726        126 => Some("command not executable"),
727        127 => Some("command not found"),
728        130 => Some("interrupted (SIGINT)"),
729        137 => Some("killed (SIGKILL / OOM)"),
730        139 => Some("segfault (SIGSEGV)"),
731        143 => Some("terminated (SIGTERM)"),
732        _ => None,
733    }
734}
735
736/// Parse `docker inspect <id>` stdout into `ContainerInspect`. The command
737/// always returns a JSON array; we take the first element. Missing fields
738/// degrade to defaults rather than fail so a partial response still
739/// renders something useful.
740pub fn parse_container_inspect(output: &str) -> Result<ContainerInspect, String> {
741    let trimmed = output.trim();
742    if trimmed.is_empty() {
743        return Err(crate::messages::CONTAINER_INSPECT_EMPTY.to_string());
744    }
745    let value: serde_json::Value = serde_json::from_str(trimmed)
746        .map_err(|e| crate::messages::container_inspect_parse_failed(&e.to_string()))?;
747    let entry = value
748        .as_array()
749        .and_then(|a| a.first())
750        .ok_or_else(|| crate::messages::CONTAINER_INSPECT_EMPTY.to_string())?;
751
752    let state = &entry["State"];
753    let config = &entry["Config"];
754    let network_settings = &entry["NetworkSettings"];
755
756    let exit_code = state["ExitCode"].as_i64().unwrap_or(0) as i32;
757    // Podman 5.x and docker both emit `OOMKilled`. Podman 3.x (still the
758    // packaged default on Ubuntu 22.04 LTS) emits `OomKilled`. Try both so
759    // OOM-killed containers surface in the ATTENTION card regardless of
760    // remote runtime version.
761    let oom_killed = state["OOMKilled"]
762        .as_bool()
763        .or_else(|| state["OomKilled"].as_bool())
764        .unwrap_or(false);
765    let started_at = state["StartedAt"].as_str().unwrap_or("").to_string();
766    let finished_at = state["FinishedAt"].as_str().unwrap_or("").to_string();
767    let health = state
768        .get("Health")
769        .and_then(|h| h.get("Status"))
770        .and_then(|s| s.as_str())
771        .map(|s| s.to_string());
772    let restart_count = entry["RestartCount"].as_u64().unwrap_or(0) as u32;
773
774    let command = config["Cmd"].as_array().map(|arr| {
775        arr.iter()
776            .filter_map(|v| v.as_str().map(|s| s.to_string()))
777            .collect()
778    });
779    let entrypoint = config["Entrypoint"].as_array().map(|arr| {
780        arr.iter()
781            .filter_map(|v| v.as_str().map(|s| s.to_string()))
782            .collect()
783    });
784    let env_count = config["Env"].as_array().map(|arr| arr.len()).unwrap_or(0);
785    let mount_count = entry["Mounts"].as_array().map(|arr| arr.len()).unwrap_or(0);
786
787    let networks = network_settings
788        .get("Networks")
789        .and_then(|n| n.as_object())
790        .map(|map| {
791            map.iter()
792                .map(|(name, cfg)| NetworkInfo {
793                    name: name.clone(),
794                    ip_address: cfg
795                        .get("IPAddress")
796                        .and_then(|v| v.as_str())
797                        .unwrap_or("")
798                        .to_string(),
799                })
800                .collect::<Vec<_>>()
801        })
802        .unwrap_or_default();
803
804    let host_config = &entry["HostConfig"];
805
806    let image_digest = entry["Image"]
807        .as_str()
808        .filter(|s| !s.is_empty())
809        .map(|s| s.to_string());
810    let restart_policy = host_config
811        .get("RestartPolicy")
812        .and_then(|p| p.get("Name"))
813        .and_then(|s| s.as_str())
814        .filter(|s| !s.is_empty() && *s != "no")
815        .map(|s| s.to_string());
816    let user = config["User"]
817        .as_str()
818        .filter(|s| !s.is_empty())
819        .map(|s| s.to_string());
820    let privileged = host_config["Privileged"].as_bool().unwrap_or(false);
821    let readonly_rootfs = host_config["ReadonlyRootfs"].as_bool().unwrap_or(false);
822    let apparmor_profile = host_config["AppArmorProfile"]
823        .as_str()
824        .or_else(|| entry["AppArmorProfile"].as_str())
825        .filter(|s| !s.is_empty())
826        .map(|s| s.to_string());
827    let seccomp_profile = host_config["SecurityOpt"].as_array().and_then(|arr| {
828        arr.iter()
829            .filter_map(|v| v.as_str())
830            .find_map(|s| s.strip_prefix("seccomp=").map(|v| v.to_string()))
831    });
832    let cap_add = host_config["CapAdd"]
833        .as_array()
834        .map(|arr| {
835            arr.iter()
836                .filter_map(|v| v.as_str().map(|s| s.to_string()))
837                .collect()
838        })
839        .unwrap_or_default();
840    let cap_drop = host_config["CapDrop"]
841        .as_array()
842        .map(|arr| {
843            arr.iter()
844                .filter_map(|v| v.as_str().map(|s| s.to_string()))
845                .collect()
846        })
847        .unwrap_or_default();
848    let mounts = entry["Mounts"]
849        .as_array()
850        .map(|arr| {
851            arr.iter()
852                .map(|m| MountInfo {
853                    source: m["Source"].as_str().unwrap_or("").to_string(),
854                    destination: m["Destination"].as_str().unwrap_or("").to_string(),
855                    read_only: !m["RW"].as_bool().unwrap_or(true),
856                })
857                .collect()
858        })
859        .unwrap_or_default();
860    let labels = config.get("Labels").and_then(|l| l.as_object());
861    let label = |key: &str| {
862        labels
863            .and_then(|l| l.get(key))
864            .and_then(|v| v.as_str())
865            .filter(|s| !s.is_empty())
866            .map(|s| s.to_string())
867    };
868    let compose_project = label("com.docker.compose.project");
869    let compose_service = label("com.docker.compose.service");
870    let image_version = label("org.opencontainers.image.version");
871    let image_revision = label("org.opencontainers.image.revision");
872    let image_source = label("org.opencontainers.image.source");
873
874    let created_at = entry["Created"].as_str().unwrap_or("").to_string();
875    // State.Pid is `0` when the container is not running. Drop the zero so
876    // the UI does not render a misleading "pid 0" row for exited rows.
877    let pid = state["Pid"].as_u64().filter(|n| *n > 0).map(|n| n as u32);
878    let hostname = config["Hostname"]
879        .as_str()
880        .filter(|s| !s.is_empty())
881        .map(|s| s.to_string());
882    let working_dir = config["WorkingDir"]
883        .as_str()
884        .filter(|s| !s.is_empty())
885        .map(|s| s.to_string());
886    let stop_signal = config["StopSignal"]
887        .as_str()
888        .filter(|s| !s.is_empty())
889        .map(|s| s.to_string());
890    let stop_timeout = config["StopTimeout"].as_u64().map(|n| n as u32);
891
892    let network_mode = host_config["NetworkMode"]
893        .as_str()
894        .filter(|s| !s.is_empty() && *s != "default")
895        .map(|s| s.to_string());
896    // HostConfig.Memory is bytes, 0 = unlimited (drop). Same for NanoCpus.
897    let memory_limit = host_config["Memory"].as_u64().filter(|n| *n > 0);
898    let cpu_limit_nanos = host_config["NanoCpus"].as_u64().filter(|n| *n > 0);
899    // PidsLimit is i64. 0 or -1 means unlimited; drop both.
900    let pids_limit = host_config["PidsLimit"].as_i64().filter(|n| *n > 0);
901    // LogConfig.Type defaults to "json-file" on docker. Always carry it
902    // so the renderer can decide whether to surface "Logs" only when
903    // non-default.
904    let log_driver = host_config
905        .get("LogConfig")
906        .and_then(|l| l.get("Type"))
907        .and_then(|v| v.as_str())
908        .filter(|s| !s.is_empty())
909        .map(|s| s.to_string());
910
911    let healthcheck = config.get("Healthcheck");
912    let health_test = healthcheck
913        .and_then(|h| h.get("Test"))
914        .and_then(|t| t.as_array())
915        .map(|arr| {
916            arr.iter()
917                .filter_map(|v| v.as_str().map(|s| s.to_string()))
918                .collect::<Vec<_>>()
919        })
920        .filter(|v| !v.is_empty());
921    let health_interval_ns = healthcheck
922        .and_then(|h| h.get("Interval"))
923        .and_then(|v| v.as_u64())
924        .filter(|n| *n > 0);
925    let health_failing_streak = state
926        .get("Health")
927        .and_then(|h| h.get("FailingStreak"))
928        .and_then(|v| v.as_u64())
929        .map(|n| n as u32);
930
931    Ok(ContainerInspect {
932        exit_code,
933        oom_killed,
934        started_at,
935        finished_at,
936        created_at,
937        health,
938        restart_count,
939        command,
940        entrypoint,
941        env_count,
942        mount_count,
943        networks,
944        image_digest,
945        restart_policy,
946        user,
947        privileged,
948        readonly_rootfs,
949        apparmor_profile,
950        seccomp_profile,
951        cap_add,
952        cap_drop,
953        mounts,
954        compose_project,
955        compose_service,
956        pid,
957        stop_signal,
958        stop_timeout,
959        image_version,
960        image_revision,
961        image_source,
962        working_dir,
963        hostname,
964        memory_limit,
965        cpu_limit_nanos,
966        pids_limit,
967        log_driver,
968        network_mode,
969        health_test,
970        health_interval_ns,
971        health_failing_streak,
972    })
973}
974
975/// Parse a Docker `Up …` status string into a compact uptime label.
976/// Returns `None` for any non-running state (Exited, Created, Restarting,
977/// Paused without an `Up` prefix, empty). Cells render `<1m` for
978/// sub-minute uptimes, `1m` / `5m` / `12h` / `5w` / `3mo` / `2y` otherwise.
979/// Format follows Docker's `units.HumanDuration`.
980pub fn parse_uptime_from_status(s: &str) -> Option<String> {
981    let body = s.strip_prefix("Up ")?;
982    let body = body.split('(').next()?.trim();
983    if body == "Less than a second" {
984        return Some("<1m".to_string());
985    }
986    if body == "About a minute" {
987        return Some("1m".to_string());
988    }
989    if body == "About an hour" {
990        return Some("1h".to_string());
991    }
992    let mut parts = body.split_whitespace();
993    let count: u64 = parts.next()?.parse().ok()?;
994    let unit = parts.next()?;
995    let suffix = match unit {
996        "second" | "seconds" => return Some("<1m".to_string()),
997        "minute" | "minutes" => "m",
998        "hour" | "hours" => "h",
999        "day" | "days" => "d",
1000        "week" | "weeks" => "w",
1001        "month" | "months" => "mo",
1002        "year" | "years" => "y",
1003        _ => return None,
1004    };
1005    Some(format!("{count}{suffix}"))
1006}
1007
1008/// Synchronously fetch + parse `container inspect`. Validates the
1009/// container ID before issuing the SSH call.
1010pub fn fetch_container_inspect(
1011    ctx: &SshContext<'_>,
1012    runtime: ContainerRuntime,
1013    container_id: &str,
1014) -> Result<ContainerInspect, String> {
1015    validate_container_id(container_id)?;
1016    let command = container_inspect_command(runtime, container_id);
1017    let result = crate::snippet::run_snippet(
1018        ctx.alias,
1019        ctx.config_path,
1020        ctx.env,
1021        &command,
1022        ctx.askpass,
1023        ctx.bw_session,
1024        true,
1025        ctx.has_tunnel,
1026    );
1027    match result {
1028        Ok(r) if r.status.success() => parse_container_inspect(&r.stdout),
1029        Ok(r) => Err(crate::messages::container_command_failed(
1030            r.status.code().unwrap_or(1),
1031        )),
1032        Err(e) => Err(e.to_string()),
1033    }
1034}
1035
1036/// Spawn a background thread to run `container inspect`. Mirrors the
1037/// `spawn_container_listing` pattern so the call site looks identical.
1038pub fn spawn_container_inspect_listing<F>(
1039    ctx: OwnedSshContext,
1040    runtime: ContainerRuntime,
1041    container_id: String,
1042    send: F,
1043) where
1044    F: FnOnce(String, String, Result<ContainerInspect, String>) + Send + 'static,
1045{
1046    std::thread::spawn(move || {
1047        let borrowed = SshContext {
1048            alias: &ctx.alias,
1049            config_path: &ctx.config_path,
1050            askpass: ctx.askpass.as_deref(),
1051            bw_session: ctx.bw_session.as_deref(),
1052            has_tunnel: ctx.has_tunnel,
1053            env: &ctx.env,
1054        };
1055        let result = fetch_container_inspect(&borrowed, runtime, &container_id);
1056        send(ctx.alias, container_id, result);
1057    });
1058}
1059
1060/// Build the `<runtime> logs --tail <n> <id>` command. The
1061/// `--tail` cap is enforced server-side so the SSH stream stays
1062/// bounded even on a noisy container.
1063pub(crate) fn container_logs_command(
1064    runtime: ContainerRuntime,
1065    container_id: &str,
1066    tail: usize,
1067) -> String {
1068    format!("{} logs --tail {} {}", runtime.as_str(), tail, container_id)
1069}
1070
1071/// Synchronously fetch logs and split into lines. Returns the raw
1072/// captured stdout split on `\n` so the renderer does not have to
1073/// re-parse. Empty trailing lines are dropped.
1074pub fn fetch_container_logs(
1075    ctx: &SshContext<'_>,
1076    runtime: ContainerRuntime,
1077    container_id: &str,
1078    tail: usize,
1079) -> Result<Vec<String>, String> {
1080    validate_container_id(container_id)?;
1081    let command = container_logs_command(runtime, container_id, tail);
1082    let result = crate::snippet::run_snippet(
1083        ctx.alias,
1084        ctx.config_path,
1085        ctx.env,
1086        &command,
1087        ctx.askpass,
1088        ctx.bw_session,
1089        true,
1090        ctx.has_tunnel,
1091    );
1092    match result {
1093        Ok(r) if r.status.success() => Ok(parse_log_output(&r.stdout, &r.stderr)),
1094        Ok(r) => Err(crate::messages::container_command_failed(
1095            r.status.code().unwrap_or(1),
1096        )),
1097        Err(e) => Err(e.to_string()),
1098    }
1099}
1100
1101/// Merge stdout (app logs) and stderr (errors) into a single chronological
1102/// stream. Many container runtimes split levels across the two streams;
1103/// re-interleaving them is closer to what `docker logs` shows on a TTY.
1104/// Trailing blank lines are stripped from each stream before merging so a
1105/// stdout block that ends in a newline does not introduce a phantom empty
1106/// row between the two streams.
1107pub(crate) fn parse_log_output(stdout: &str, stderr: &str) -> Vec<String> {
1108    let mut lines: Vec<String> = stdout.lines().map(|s| s.to_string()).collect();
1109    while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1110        lines.pop();
1111    }
1112    for s in stderr.lines() {
1113        lines.push(s.to_string());
1114    }
1115    while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1116        lines.pop();
1117    }
1118    lines
1119}
1120
1121/// Spawn a background thread to run `container logs`. Same shape as
1122/// `spawn_container_inspect_listing`. In demo mode the SSH call is
1123/// short-circuited with a deterministic synthetic log stream so the
1124/// logs viewer (and its `/` search) is exercisable without a remote.
1125pub fn spawn_container_logs_fetch<F>(
1126    ctx: OwnedSshContext,
1127    runtime: ContainerRuntime,
1128    container_id: String,
1129    container_name: String,
1130    tail: usize,
1131    send: F,
1132) where
1133    F: FnOnce(String, String, String, Result<Vec<String>, String>) + Send + 'static,
1134{
1135    if crate::demo_flag::is_demo() {
1136        let lines = demo_log_lines(&container_name, tail);
1137        log::debug!(
1138            "[purple] container_logs_fetch: demo short-circuit alias={} id={} lines={}",
1139            ctx.alias,
1140            container_id,
1141            lines.len()
1142        );
1143        send(ctx.alias, container_id, container_name, Ok(lines));
1144        return;
1145    }
1146    std::thread::spawn(move || {
1147        let borrowed = SshContext {
1148            alias: &ctx.alias,
1149            config_path: &ctx.config_path,
1150            askpass: ctx.askpass.as_deref(),
1151            bw_session: ctx.bw_session.as_deref(),
1152            has_tunnel: ctx.has_tunnel,
1153            env: &ctx.env,
1154        };
1155        let result = fetch_container_logs(&borrowed, runtime, &container_id, tail);
1156        send(ctx.alias, container_id, container_name, result);
1157    });
1158}
1159
1160/// Generate a deterministic stream of fake log lines for demo mode.
1161/// Mixes INFO / WARN / ERROR / DEBUG with realistic-looking content
1162/// (HTTP requests, DB pings, retries, timeouts) so the user can
1163/// usefully press `/` and find matches under `--demo`. Anchored to
1164/// `demo_flag::now_secs()` so timestamps stay stable across renders.
1165pub(crate) fn demo_log_lines(container_name: &str, tail: usize) -> Vec<String> {
1166    use std::time::{Duration, UNIX_EPOCH};
1167    // Cheap hash to fan out per-container variation without bringing
1168    // `rand` into the binary.
1169    let seed: u32 = container_name
1170        .bytes()
1171        .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32));
1172
1173    // Templates rotate every line. Index 0 is the freshest log line.
1174    let templates: &[&str] = &[
1175        "INFO  [{}] handled GET /api/v1/health 200 in 14ms",
1176        "INFO  [{}] handled POST /api/v1/orders 201 in 38ms (user_id={user})",
1177        "DEBUG [{}] cache hit key=session:{user} ttl=3600",
1178        "INFO  [{}] handled GET /api/v1/users/{user} 200 in 11ms",
1179        "WARN  [{}] slow query detected duration=812ms statement=SELECT FROM orders",
1180        "INFO  [{}] connection pool size=12 idle=8 in_use=4",
1181        "DEBUG [{}] flushing metrics batch size=64",
1182        "INFO  [{}] handled GET /api/v1/inventory 200 in 22ms",
1183        "ERROR [{}] upstream timeout after 5000ms target=payments retry=1",
1184        "WARN  [{}] retrying request attempt=2 backoff=250ms",
1185        "INFO  [{}] handled POST /api/v1/login 200 in 31ms",
1186        "DEBUG [{}] gc cycle reclaimed=42MB took=18ms",
1187        "INFO  [{}] heartbeat ok rss=128MB cpu=4%",
1188        "ERROR [{}] failed to acquire lock resource=cache_warmer waiter=3",
1189        "INFO  [{}] handled DELETE /api/v1/sessions/{user} 204 in 9ms",
1190        "WARN  [{}] disk usage at 78% mount=/data threshold=80%",
1191        "INFO  [{}] handled GET /api/v1/search?q=widget 200 in 47ms",
1192        "DEBUG [{}] websocket ping rtt=12ms",
1193    ];
1194
1195    // Always use `demo_flag::now_secs()` even outside demo mode: the
1196    // helper's OnceLock caches the first wallclock value, so repeated
1197    // calls within a process return the same instant. Branching on
1198    // `is_demo()` would let tests cross a second boundary and flake.
1199    let now = crate::demo_flag::now_secs();
1200
1201    // Map each line to a timestamp working backwards from now. One log
1202    // every 3 seconds keeps the time range realistic for a 200-line tail.
1203    let mut lines = Vec::with_capacity(tail);
1204    for i in 0..tail {
1205        let template = templates[(i + seed as usize) % templates.len()];
1206        let user = 1000 + ((seed as usize + i * 7) % 50);
1207        let secs_back = (i as u64) * 3;
1208        let line_time = UNIX_EPOCH + Duration::from_secs(now.saturating_sub(secs_back));
1209        let ts = format_demo_timestamp(line_time);
1210        let body = template
1211            .replace("{}", container_name)
1212            .replace("{user}", &user.to_string());
1213        lines.push(format!("{} {}", ts, body));
1214    }
1215    // Render flush-top with the newest line at the bottom of the
1216    // viewport, matching real `docker logs --tail` output.
1217    lines.reverse();
1218    lines
1219}
1220
1221fn format_demo_timestamp(t: std::time::SystemTime) -> String {
1222    use std::time::UNIX_EPOCH;
1223    let secs = t
1224        .duration_since(UNIX_EPOCH)
1225        .map(|d| d.as_secs())
1226        .unwrap_or(0);
1227    // Fast UTC breakdown without dragging in chrono. Good enough for a
1228    // demo timestamp where leap seconds / DST are irrelevant.
1229    let days_since_epoch = (secs / 86_400) as i64;
1230    let seconds_in_day = (secs % 86_400) as u32;
1231    let h = seconds_in_day / 3600;
1232    let m = (seconds_in_day % 3600) / 60;
1233    let s = seconds_in_day % 60;
1234    let (y, mo, d) = civil_from_days(days_since_epoch);
1235    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", y, mo, d, h, m, s)
1236}
1237
1238/// Convert days-since-1970-01-01 to (year, month, day). Howard Hinnant's
1239/// civil_from_days algorithm — proleptic Gregorian, 1970 = day 0.
1240fn civil_from_days(z: i64) -> (i32, u32, u32) {
1241    let z = z + 719_468;
1242    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
1243    let doe = (z - era * 146_097) as u64;
1244    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1245    let y = yoe as i64 + era * 400;
1246    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1247    let mp = (5 * doy + 2) / 153;
1248    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
1249    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1250    let y = if m <= 2 { y + 1 } else { y };
1251    (y as i32, m, d)
1252}
1253
1254// ---------------------------------------------------------------------------
1255// JSON lines cache
1256// ---------------------------------------------------------------------------
1257
1258/// A cached container listing for a single host. `engine_version` is the
1259/// daemon's `Server.Version` captured during the last refresh, surfaced in
1260/// the host detail panel; `None` means the version sub-call did not return
1261/// or the cache was written by an older purple build.
1262#[derive(Debug, Clone)]
1263pub struct ContainerCacheEntry {
1264    pub timestamp: u64,
1265    pub runtime: ContainerRuntime,
1266    pub engine_version: Option<String>,
1267    pub containers: Vec<ContainerInfo>,
1268}
1269
1270/// Serde helper for a single JSON line in the cache file. `engine_version`
1271/// uses `serde(default)` so cache files written before this field existed
1272/// still deserialize cleanly.
1273#[derive(Serialize, Deserialize)]
1274struct CacheLine {
1275    alias: String,
1276    timestamp: u64,
1277    runtime: ContainerRuntime,
1278    #[serde(default, skip_serializing_if = "Option::is_none")]
1279    engine_version: Option<String>,
1280    containers: Vec<ContainerInfo>,
1281}
1282
1283fn cache_path(paths: Option<&crate::runtime::env::Paths>) -> Option<std::path::PathBuf> {
1284    paths.map(crate::runtime::env::Paths::container_cache)
1285}
1286
1287/// Load container cache from `~/.purple/container_cache.jsonl`.
1288/// Malformed lines are silently ignored. Duplicate aliases: last-write-wins.
1289pub fn load_container_cache(
1290    paths: Option<&crate::runtime::env::Paths>,
1291) -> HashMap<String, ContainerCacheEntry> {
1292    let mut map = HashMap::new();
1293    let Some(path) = cache_path(paths) else {
1294        return map;
1295    };
1296    let Ok(content) = std::fs::read_to_string(&path) else {
1297        return map;
1298    };
1299    for line in content.lines() {
1300        let trimmed = line.trim();
1301        if trimmed.is_empty() {
1302            continue;
1303        }
1304        if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1305            map.insert(
1306                entry.alias,
1307                ContainerCacheEntry {
1308                    timestamp: entry.timestamp,
1309                    runtime: entry.runtime,
1310                    engine_version: entry.engine_version,
1311                    containers: entry.containers,
1312                },
1313            );
1314        }
1315    }
1316    map
1317}
1318
1319/// Parse container cache from JSONL content string (for demo/test use).
1320pub fn parse_container_cache_content(content: &str) -> HashMap<String, ContainerCacheEntry> {
1321    let mut map = HashMap::new();
1322    for line in content.lines() {
1323        let trimmed = line.trim();
1324        if trimmed.is_empty() {
1325            continue;
1326        }
1327        if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1328            map.insert(
1329                entry.alias,
1330                ContainerCacheEntry {
1331                    timestamp: entry.timestamp,
1332                    runtime: entry.runtime,
1333                    engine_version: entry.engine_version,
1334                    containers: entry.containers,
1335                },
1336            );
1337        }
1338    }
1339    map
1340}
1341
1342/// Save container cache to `~/.purple/container_cache.jsonl` via atomic write.
1343pub fn save_container_cache(
1344    paths: Option<&crate::runtime::env::Paths>,
1345    cache: &HashMap<String, ContainerCacheEntry>,
1346) {
1347    if crate::demo_flag::is_demo() {
1348        return;
1349    }
1350    let Some(path) = cache_path(paths) else {
1351        return;
1352    };
1353    let mut lines = Vec::with_capacity(cache.len());
1354    for (alias, entry) in cache {
1355        let line = CacheLine {
1356            alias: alias.clone(),
1357            timestamp: entry.timestamp,
1358            runtime: entry.runtime,
1359            engine_version: entry.engine_version.clone(),
1360            containers: entry.containers.clone(),
1361        };
1362        if let Ok(s) = serde_json::to_string(&line) {
1363            lines.push(s);
1364        }
1365    }
1366    let content = lines.join("\n");
1367    log::debug!(
1368        "[purple] save_container_cache: {} host entries, {} bytes -> {}",
1369        cache.len(),
1370        content.len(),
1371        path.display()
1372    );
1373    if let Err(e) = crate::fs_util::atomic_write(&path, content.as_bytes()) {
1374        log::warn!(
1375            "[config] Failed to write container cache {}: {e}",
1376            path.display()
1377        );
1378    }
1379}
1380
1381// ---------------------------------------------------------------------------
1382// String truncation
1383// ---------------------------------------------------------------------------
1384
1385/// Truncate a string to at most `max` characters. Appends ".." if truncated.
1386pub fn truncate_str(s: &str, max: usize) -> String {
1387    let count = s.chars().count();
1388    if count <= max {
1389        s.to_string()
1390    } else {
1391        let cut = max.saturating_sub(2);
1392        let end = s.char_indices().nth(cut).map(|(i, _)| i).unwrap_or(s.len());
1393        format!("{}..", &s[..end])
1394    }
1395}
1396
1397// ---------------------------------------------------------------------------
1398// Relative time
1399// ---------------------------------------------------------------------------
1400
1401/// Format a duration in seconds as a compact label (`12s`, `5m`,
1402/// `2h`, `3d`). Used for the in-border staleness badge where width
1403/// is precious and the surrounding label (`synced`) already says
1404/// "ago" without the suffix.
1405pub fn format_uptime_short(seconds: u64) -> String {
1406    if seconds < 60 {
1407        format!("{seconds}s")
1408    } else if seconds < 3600 {
1409        format!("{}m", seconds / 60)
1410    } else if seconds < 86400 {
1411        format!("{}h", seconds / 3600)
1412    } else {
1413        format!("{}d", seconds / 86400)
1414    }
1415}
1416
1417/// Format a Unix timestamp as a human-readable relative time string.
1418/// Honours `demo_flag::now_secs()` when demo mode is active so visual
1419/// regression goldens stay byte-stable across long-running test
1420/// processes (same pattern as `history::format_time_ago`).
1421pub fn format_relative_time(timestamp: u64) -> String {
1422    let now = if crate::demo_flag::is_demo() {
1423        crate::demo_flag::now_secs()
1424    } else {
1425        SystemTime::now()
1426            .duration_since(UNIX_EPOCH)
1427            .unwrap_or_default()
1428            .as_secs()
1429    };
1430    let diff = now.saturating_sub(timestamp);
1431    if diff < 60 {
1432        "just now".to_string()
1433    } else if diff < 3600 {
1434        format!("{}m ago", diff / 60)
1435    } else if diff < 86400 {
1436        format!("{}h ago", diff / 3600)
1437    } else {
1438        format!("{}d ago", diff / 86400)
1439    }
1440}
1441
1442// ---------------------------------------------------------------------------
1443// Tests
1444// ---------------------------------------------------------------------------
1445
1446#[cfg(test)]
1447#[path = "containers_tests.rs"]
1448mod tests;