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#[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 #[serde(
37 rename = "Ports",
38 deserialize_with = "deserialize_ports_field",
39 default
40 )]
41 pub ports: String,
42}
43
44fn 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
66fn 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 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 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
162fn 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#[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#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
204pub enum ContainerRuntime {
205 Docker,
206 Podman,
207}
208
209impl ContainerRuntime {
210 pub fn as_str(&self) -> &'static str {
212 match self {
213 ContainerRuntime::Docker => "docker",
214 ContainerRuntime::Podman => "podman",
215 }
216 }
217}
218
219#[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#[derive(Copy, Clone, Debug, PartialEq)]
243pub enum ContainerAction {
244 Start,
245 Stop,
246 Restart,
247}
248
249impl ContainerAction {
250 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
260pub 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
269pub 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
288pub 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#[derive(Debug, Clone, PartialEq)]
334pub struct ContainerListing {
335 pub runtime: ContainerRuntime,
336 pub engine_version: Option<String>,
337 pub containers: Vec<ContainerInfo>,
338}
339
340pub 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 let mut engine_version: Option<String> = None;
373 let mut after_engine = false;
374 let mut containers: Vec<ContainerInfo> = Vec::new();
375 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 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
426fn 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#[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
463fn 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
497pub 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_ctx(ctx, &command, true);
505 let alias = ctx.alias;
506 match result {
507 Ok(r) if r.status.success() => {
508 parse_container_output(&r.stdout, cached_runtime).map_err(|e| {
509 error!("[external] Container list parse failed: alias={alias}: {e}");
510 ContainerError {
511 runtime: cached_runtime,
512 message: e,
513 }
514 })
515 }
516 Ok(r) => {
517 let stderr = r.stderr.trim().to_string();
518 let msg = friendly_container_error(&stderr, r.status.code());
519 log::log!(
523 crate::connection::remote_exit_log_level(r.status.code().unwrap_or(-1)),
524 "[external] Container fetch failed: alias={alias}: {msg}"
525 );
526 Err(ContainerError {
527 runtime: cached_runtime,
528 message: msg,
529 })
530 }
531 Err(e) => {
532 error!("[external] Container fetch failed: alias={alias}: {e}");
533 Err(ContainerError {
534 runtime: cached_runtime,
535 message: e.to_string(),
536 })
537 }
538 }
539}
540
541pub fn spawn_container_listing<F>(
544 ctx: OwnedSshContext,
545 cached_runtime: Option<ContainerRuntime>,
546 send: F,
547) where
548 F: FnOnce(String, Result<ContainerListing, ContainerError>) + Send + 'static,
549{
550 std::thread::spawn(move || {
551 let result = fetch_containers(&ctx.borrow(), cached_runtime);
552 send(ctx.alias, result);
553 });
554}
555
556pub fn spawn_container_action<F>(
559 ctx: OwnedSshContext,
560 runtime: ContainerRuntime,
561 action: ContainerAction,
562 container_id: String,
563 send: F,
564) where
565 F: FnOnce(String, ContainerAction, Result<(), String>) + Send + 'static,
566{
567 std::thread::spawn(move || {
568 if let Err(e) = validate_container_id(&container_id) {
569 log::debug!(
570 "[purple] container action {} blocked on alias={}: invalid container_id: {}",
571 action.as_str(),
572 ctx.alias,
573 e
574 );
575 send(ctx.alias, action, Err(e));
576 return;
577 }
578 let alias = &ctx.alias;
579 info!(
580 "[external] Container action: {} container={container_id} alias={alias}",
581 action.as_str()
582 );
583 let command = container_action_command(runtime, action, &container_id);
584 let result = crate::snippet::run_snippet_ctx(&ctx.borrow(), &command, true);
585 match result {
586 Ok(r) if r.status.success() => send(ctx.alias, action, Ok(())),
587 Ok(r) => {
588 let err = friendly_container_error(r.stderr.trim(), r.status.code());
589 log::log!(
593 crate::connection::remote_exit_log_level(r.status.code().unwrap_or(-1)),
594 "[external] Container {} failed: alias={alias} container={container_id}: {err}",
595 action.as_str()
596 );
597 send(ctx.alias, action, Err(err));
598 }
599 Err(e) => {
600 error!(
601 "[external] Container {} failed: alias={alias} container={container_id}: {e}",
602 action.as_str()
603 );
604 send(ctx.alias, action, Err(e.to_string()));
605 }
606 }
607 });
608}
609
610#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
618pub struct ContainerInspect {
619 pub exit_code: i32,
620 pub oom_killed: bool,
621 pub started_at: String,
622 pub finished_at: String,
623 pub created_at: String,
624 pub health: Option<String>,
627 pub restart_count: u32,
628 pub command: Option<Vec<String>>,
629 pub entrypoint: Option<Vec<String>>,
630 pub env_count: usize,
631 pub mount_count: usize,
632 pub networks: Vec<NetworkInfo>,
633 pub image_digest: Option<String>,
635 pub restart_policy: Option<String>,
636 pub user: Option<String>,
637 pub privileged: bool,
638 pub readonly_rootfs: bool,
639 pub apparmor_profile: Option<String>,
640 pub seccomp_profile: Option<String>,
641 pub cap_add: Vec<String>,
642 pub cap_drop: Vec<String>,
643 pub mounts: Vec<MountInfo>,
644 pub compose_project: Option<String>,
645 pub compose_service: Option<String>,
646 pub pid: Option<u32>,
648 pub stop_signal: Option<String>,
649 pub stop_timeout: Option<u32>,
650 pub image_version: Option<String>,
652 pub image_revision: Option<String>,
653 pub image_source: Option<String>,
654 pub working_dir: Option<String>,
655 pub hostname: Option<String>,
656 pub memory_limit: Option<u64>,
658 pub cpu_limit_nanos: Option<u64>,
659 pub pids_limit: Option<i64>,
660 pub log_driver: Option<String>,
661 pub network_mode: Option<String>,
663 pub health_test: Option<Vec<String>>,
665 pub health_interval_ns: Option<u64>,
666 pub health_failing_streak: Option<u32>,
667}
668
669#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
670pub struct NetworkInfo {
671 pub name: String,
672 pub ip_address: String,
673}
674
675#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
676pub struct MountInfo {
677 pub source: String,
678 pub destination: String,
679 pub read_only: bool,
680}
681
682pub(crate) fn container_inspect_command(runtime: ContainerRuntime, container_id: &str) -> String {
688 format!("{} inspect {}", runtime.as_str(), container_id)
689}
690
691pub fn exit_code_meaning(code: i32) -> Option<&'static str> {
697 match code {
698 1 => Some("application error"),
699 125 => Some("docker run failed"),
700 126 => Some("command not executable"),
701 127 => Some("command not found"),
702 130 => Some("interrupted (SIGINT)"),
703 137 => Some("killed (SIGKILL / OOM)"),
704 139 => Some("segfault (SIGSEGV)"),
705 143 => Some("terminated (SIGTERM)"),
706 _ => None,
707 }
708}
709
710pub fn parse_container_inspect(output: &str) -> Result<ContainerInspect, String> {
715 let trimmed = output.trim();
716 if trimmed.is_empty() {
717 return Err(crate::messages::CONTAINER_INSPECT_EMPTY.to_string());
718 }
719 let value: serde_json::Value = serde_json::from_str(trimmed)
720 .map_err(|e| crate::messages::container_inspect_parse_failed(&e.to_string()))?;
721 let entry = value
722 .as_array()
723 .and_then(|a| a.first())
724 .ok_or_else(|| crate::messages::CONTAINER_INSPECT_EMPTY.to_string())?;
725
726 let state = &entry["State"];
727 let config = &entry["Config"];
728 let network_settings = &entry["NetworkSettings"];
729
730 let exit_code = state["ExitCode"].as_i64().unwrap_or(0) as i32;
731 let oom_killed = state["OOMKilled"]
736 .as_bool()
737 .or_else(|| state["OomKilled"].as_bool())
738 .unwrap_or(false);
739 let started_at = state["StartedAt"].as_str().unwrap_or("").to_string();
740 let finished_at = state["FinishedAt"].as_str().unwrap_or("").to_string();
741 let health = state
742 .get("Health")
743 .and_then(|h| h.get("Status"))
744 .and_then(|s| s.as_str())
745 .map(|s| s.to_string());
746 let restart_count = entry["RestartCount"].as_u64().unwrap_or(0) as u32;
747
748 let command = config["Cmd"].as_array().map(|arr| {
749 arr.iter()
750 .filter_map(|v| v.as_str().map(|s| s.to_string()))
751 .collect()
752 });
753 let entrypoint = config["Entrypoint"].as_array().map(|arr| {
754 arr.iter()
755 .filter_map(|v| v.as_str().map(|s| s.to_string()))
756 .collect()
757 });
758 let env_count = config["Env"].as_array().map(|arr| arr.len()).unwrap_or(0);
759 let mount_count = entry["Mounts"].as_array().map(|arr| arr.len()).unwrap_or(0);
760
761 let networks = network_settings
762 .get("Networks")
763 .and_then(|n| n.as_object())
764 .map(|map| {
765 map.iter()
766 .map(|(name, cfg)| NetworkInfo {
767 name: name.clone(),
768 ip_address: cfg
769 .get("IPAddress")
770 .and_then(|v| v.as_str())
771 .unwrap_or("")
772 .to_string(),
773 })
774 .collect::<Vec<_>>()
775 })
776 .unwrap_or_default();
777
778 let host_config = &entry["HostConfig"];
779
780 let image_digest = entry["Image"]
781 .as_str()
782 .filter(|s| !s.is_empty())
783 .map(|s| s.to_string());
784 let restart_policy = host_config
785 .get("RestartPolicy")
786 .and_then(|p| p.get("Name"))
787 .and_then(|s| s.as_str())
788 .filter(|s| !s.is_empty() && *s != "no")
789 .map(|s| s.to_string());
790 let user = config["User"]
791 .as_str()
792 .filter(|s| !s.is_empty())
793 .map(|s| s.to_string());
794 let privileged = host_config["Privileged"].as_bool().unwrap_or(false);
795 let readonly_rootfs = host_config["ReadonlyRootfs"].as_bool().unwrap_or(false);
796 let apparmor_profile = host_config["AppArmorProfile"]
797 .as_str()
798 .or_else(|| entry["AppArmorProfile"].as_str())
799 .filter(|s| !s.is_empty())
800 .map(|s| s.to_string());
801 let seccomp_profile = host_config["SecurityOpt"].as_array().and_then(|arr| {
802 arr.iter()
803 .filter_map(|v| v.as_str())
804 .find_map(|s| s.strip_prefix("seccomp=").map(|v| v.to_string()))
805 });
806 let cap_add = host_config["CapAdd"]
807 .as_array()
808 .map(|arr| {
809 arr.iter()
810 .filter_map(|v| v.as_str().map(|s| s.to_string()))
811 .collect()
812 })
813 .unwrap_or_default();
814 let cap_drop = host_config["CapDrop"]
815 .as_array()
816 .map(|arr| {
817 arr.iter()
818 .filter_map(|v| v.as_str().map(|s| s.to_string()))
819 .collect()
820 })
821 .unwrap_or_default();
822 let mounts = entry["Mounts"]
823 .as_array()
824 .map(|arr| {
825 arr.iter()
826 .map(|m| MountInfo {
827 source: m["Source"].as_str().unwrap_or("").to_string(),
828 destination: m["Destination"].as_str().unwrap_or("").to_string(),
829 read_only: !m["RW"].as_bool().unwrap_or(true),
830 })
831 .collect()
832 })
833 .unwrap_or_default();
834 let labels = config.get("Labels").and_then(|l| l.as_object());
835 let label = |key: &str| {
836 labels
837 .and_then(|l| l.get(key))
838 .and_then(|v| v.as_str())
839 .filter(|s| !s.is_empty())
840 .map(|s| s.to_string())
841 };
842 let compose_project = label("com.docker.compose.project");
843 let compose_service = label("com.docker.compose.service");
844 let image_version = label("org.opencontainers.image.version");
845 let image_revision = label("org.opencontainers.image.revision");
846 let image_source = label("org.opencontainers.image.source");
847
848 let created_at = entry["Created"].as_str().unwrap_or("").to_string();
849 let pid = state["Pid"].as_u64().filter(|n| *n > 0).map(|n| n as u32);
852 let hostname = config["Hostname"]
853 .as_str()
854 .filter(|s| !s.is_empty())
855 .map(|s| s.to_string());
856 let working_dir = config["WorkingDir"]
857 .as_str()
858 .filter(|s| !s.is_empty())
859 .map(|s| s.to_string());
860 let stop_signal = config["StopSignal"]
861 .as_str()
862 .filter(|s| !s.is_empty())
863 .map(|s| s.to_string());
864 let stop_timeout = config["StopTimeout"].as_u64().map(|n| n as u32);
865
866 let network_mode = host_config["NetworkMode"]
867 .as_str()
868 .filter(|s| !s.is_empty() && *s != "default")
869 .map(|s| s.to_string());
870 let memory_limit = host_config["Memory"].as_u64().filter(|n| *n > 0);
872 let cpu_limit_nanos = host_config["NanoCpus"].as_u64().filter(|n| *n > 0);
873 let pids_limit = host_config["PidsLimit"].as_i64().filter(|n| *n > 0);
875 let log_driver = host_config
879 .get("LogConfig")
880 .and_then(|l| l.get("Type"))
881 .and_then(|v| v.as_str())
882 .filter(|s| !s.is_empty())
883 .map(|s| s.to_string());
884
885 let healthcheck = config.get("Healthcheck");
886 let health_test = healthcheck
887 .and_then(|h| h.get("Test"))
888 .and_then(|t| t.as_array())
889 .map(|arr| {
890 arr.iter()
891 .filter_map(|v| v.as_str().map(|s| s.to_string()))
892 .collect::<Vec<_>>()
893 })
894 .filter(|v| !v.is_empty());
895 let health_interval_ns = healthcheck
896 .and_then(|h| h.get("Interval"))
897 .and_then(|v| v.as_u64())
898 .filter(|n| *n > 0);
899 let health_failing_streak = state
900 .get("Health")
901 .and_then(|h| h.get("FailingStreak"))
902 .and_then(|v| v.as_u64())
903 .map(|n| n as u32);
904
905 Ok(ContainerInspect {
906 exit_code,
907 oom_killed,
908 started_at,
909 finished_at,
910 created_at,
911 health,
912 restart_count,
913 command,
914 entrypoint,
915 env_count,
916 mount_count,
917 networks,
918 image_digest,
919 restart_policy,
920 user,
921 privileged,
922 readonly_rootfs,
923 apparmor_profile,
924 seccomp_profile,
925 cap_add,
926 cap_drop,
927 mounts,
928 compose_project,
929 compose_service,
930 pid,
931 stop_signal,
932 stop_timeout,
933 image_version,
934 image_revision,
935 image_source,
936 working_dir,
937 hostname,
938 memory_limit,
939 cpu_limit_nanos,
940 pids_limit,
941 log_driver,
942 network_mode,
943 health_test,
944 health_interval_ns,
945 health_failing_streak,
946 })
947}
948
949pub fn parse_uptime_from_status(s: &str) -> Option<String> {
955 let body = s.strip_prefix("Up ")?;
956 let body = body.split('(').next()?.trim();
957 if body == "Less than a second" {
958 return Some("<1m".to_string());
959 }
960 if body == "About a minute" {
961 return Some("1m".to_string());
962 }
963 if body == "About an hour" {
964 return Some("1h".to_string());
965 }
966 let mut parts = body.split_whitespace();
967 let count: u64 = parts.next()?.parse().ok()?;
968 let unit = parts.next()?;
969 let suffix = match unit {
970 "second" | "seconds" => return Some("<1m".to_string()),
971 "minute" | "minutes" => "m",
972 "hour" | "hours" => "h",
973 "day" | "days" => "d",
974 "week" | "weeks" => "w",
975 "month" | "months" => "mo",
976 "year" | "years" => "y",
977 _ => return None,
978 };
979 Some(format!("{count}{suffix}"))
980}
981
982pub fn fetch_container_inspect(
985 ctx: &SshContext<'_>,
986 runtime: ContainerRuntime,
987 container_id: &str,
988) -> Result<ContainerInspect, String> {
989 validate_container_id(container_id)?;
990 let command = container_inspect_command(runtime, container_id);
991 let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
992 match result {
993 Ok(r) if r.status.success() => parse_container_inspect(&r.stdout),
994 Ok(r) => Err(crate::messages::container_command_failed(
995 r.status.code().unwrap_or(1),
996 )),
997 Err(e) => Err(e.to_string()),
998 }
999}
1000
1001pub fn spawn_container_inspect_listing<F>(
1004 ctx: OwnedSshContext,
1005 runtime: ContainerRuntime,
1006 container_id: String,
1007 send: F,
1008) where
1009 F: FnOnce(String, String, Result<ContainerInspect, String>) + Send + 'static,
1010{
1011 std::thread::spawn(move || {
1012 let result = fetch_container_inspect(&ctx.borrow(), runtime, &container_id);
1013 send(ctx.alias, container_id, result);
1014 });
1015}
1016
1017pub(crate) fn container_logs_command(
1021 runtime: ContainerRuntime,
1022 container_id: &str,
1023 tail: usize,
1024) -> String {
1025 format!("{} logs --tail {} {}", runtime.as_str(), tail, container_id)
1026}
1027
1028pub fn fetch_container_logs(
1032 ctx: &SshContext<'_>,
1033 runtime: ContainerRuntime,
1034 container_id: &str,
1035 tail: usize,
1036) -> Result<Vec<String>, String> {
1037 validate_container_id(container_id)?;
1038 let command = container_logs_command(runtime, container_id, tail);
1039 let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
1040 match result {
1041 Ok(r) if r.status.success() => Ok(parse_log_output(&r.stdout, &r.stderr)),
1042 Ok(r) => Err(crate::messages::container_command_failed(
1043 r.status.code().unwrap_or(1),
1044 )),
1045 Err(e) => Err(e.to_string()),
1046 }
1047}
1048
1049pub(crate) fn parse_log_output(stdout: &str, stderr: &str) -> Vec<String> {
1056 let mut lines: Vec<String> = stdout.lines().map(|s| s.to_string()).collect();
1057 while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1058 lines.pop();
1059 }
1060 for s in stderr.lines() {
1061 lines.push(s.to_string());
1062 }
1063 while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1064 lines.pop();
1065 }
1066 lines
1067}
1068
1069pub fn spawn_container_logs_fetch<F>(
1074 ctx: OwnedSshContext,
1075 runtime: ContainerRuntime,
1076 container_id: String,
1077 container_name: String,
1078 tail: usize,
1079 send: F,
1080) where
1081 F: FnOnce(String, String, String, Result<Vec<String>, String>) + Send + 'static,
1082{
1083 if crate::demo_flag::is_demo() {
1084 let lines = demo_log_lines(&container_name, tail);
1085 log::debug!(
1086 "[purple] container_logs_fetch: demo short-circuit alias={} id={} lines={}",
1087 ctx.alias,
1088 container_id,
1089 lines.len()
1090 );
1091 send(ctx.alias, container_id, container_name, Ok(lines));
1092 return;
1093 }
1094 std::thread::spawn(move || {
1095 let result = fetch_container_logs(&ctx.borrow(), runtime, &container_id, tail);
1096 send(ctx.alias, container_id, container_name, result);
1097 });
1098}
1099
1100pub(crate) fn demo_log_lines(container_name: &str, tail: usize) -> Vec<String> {
1106 use std::time::{Duration, UNIX_EPOCH};
1107 let seed: u32 = container_name
1110 .bytes()
1111 .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32));
1112
1113 let templates: &[&str] = &[
1115 "INFO [{}] handled GET /api/v1/health 200 in 14ms",
1116 "INFO [{}] handled POST /api/v1/orders 201 in 38ms (user_id={user})",
1117 "DEBUG [{}] cache hit key=session:{user} ttl=3600",
1118 "INFO [{}] handled GET /api/v1/users/{user} 200 in 11ms",
1119 "WARN [{}] slow query detected duration=812ms statement=SELECT FROM orders",
1120 "INFO [{}] connection pool size=12 idle=8 in_use=4",
1121 "DEBUG [{}] flushing metrics batch size=64",
1122 "INFO [{}] handled GET /api/v1/inventory 200 in 22ms",
1123 "ERROR [{}] upstream timeout after 5000ms target=payments retry=1",
1124 "WARN [{}] retrying request attempt=2 backoff=250ms",
1125 "INFO [{}] handled POST /api/v1/login 200 in 31ms",
1126 "DEBUG [{}] gc cycle reclaimed=42MB took=18ms",
1127 "INFO [{}] heartbeat ok rss=128MB cpu=4%",
1128 "ERROR [{}] failed to acquire lock resource=cache_warmer waiter=3",
1129 "INFO [{}] handled DELETE /api/v1/sessions/{user} 204 in 9ms",
1130 "WARN [{}] disk usage at 78% mount=/data threshold=80%",
1131 "INFO [{}] handled GET /api/v1/search?q=widget 200 in 47ms",
1132 "DEBUG [{}] websocket ping rtt=12ms",
1133 ];
1134
1135 let now = crate::demo_flag::now_secs();
1140
1141 let mut lines = Vec::with_capacity(tail);
1144 for i in 0..tail {
1145 let template = templates[(i + seed as usize) % templates.len()];
1146 let user = 1000 + ((seed as usize + i * 7) % 50);
1147 let secs_back = (i as u64) * 3;
1148 let line_time = UNIX_EPOCH + Duration::from_secs(now.saturating_sub(secs_back));
1149 let ts = format_demo_timestamp(line_time);
1150 let body = template
1151 .replace("{}", container_name)
1152 .replace("{user}", &user.to_string());
1153 lines.push(format!("{} {}", ts, body));
1154 }
1155 lines.reverse();
1158 lines
1159}
1160
1161fn format_demo_timestamp(t: std::time::SystemTime) -> String {
1162 use std::time::UNIX_EPOCH;
1163 let secs = t
1164 .duration_since(UNIX_EPOCH)
1165 .map(|d| d.as_secs())
1166 .unwrap_or(0);
1167 let days_since_epoch = (secs / 86_400) as i64;
1170 let seconds_in_day = (secs % 86_400) as u32;
1171 let h = seconds_in_day / 3600;
1172 let m = (seconds_in_day % 3600) / 60;
1173 let s = seconds_in_day % 60;
1174 let (y, mo, d) = civil_from_days(days_since_epoch);
1175 format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", y, mo, d, h, m, s)
1176}
1177
1178fn civil_from_days(z: i64) -> (i32, u32, u32) {
1181 let z = z + 719_468;
1182 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
1183 let doe = (z - era * 146_097) as u64;
1184 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1185 let y = yoe as i64 + era * 400;
1186 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1187 let mp = (5 * doy + 2) / 153;
1188 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
1189 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1190 let y = if m <= 2 { y + 1 } else { y };
1191 (y as i32, m, d)
1192}
1193
1194#[derive(Debug, Clone)]
1203pub struct ContainerCacheEntry {
1204 pub timestamp: u64,
1205 pub runtime: ContainerRuntime,
1206 pub engine_version: Option<String>,
1207 pub containers: Vec<ContainerInfo>,
1208}
1209
1210#[derive(Serialize, Deserialize)]
1214struct CacheLine {
1215 alias: String,
1216 timestamp: u64,
1217 runtime: ContainerRuntime,
1218 #[serde(default, skip_serializing_if = "Option::is_none")]
1219 engine_version: Option<String>,
1220 containers: Vec<ContainerInfo>,
1221}
1222
1223fn cache_path(paths: Option<&crate::runtime::env::Paths>) -> Option<std::path::PathBuf> {
1224 paths.map(crate::runtime::env::Paths::container_cache)
1225}
1226
1227pub fn load_container_cache(
1230 paths: Option<&crate::runtime::env::Paths>,
1231) -> HashMap<String, ContainerCacheEntry> {
1232 let mut map = HashMap::new();
1233 let Some(path) = cache_path(paths) else {
1234 return map;
1235 };
1236 let Ok(content) = std::fs::read_to_string(&path) else {
1237 return map;
1238 };
1239 for line in content.lines() {
1240 let trimmed = line.trim();
1241 if trimmed.is_empty() {
1242 continue;
1243 }
1244 if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1245 map.insert(
1246 entry.alias,
1247 ContainerCacheEntry {
1248 timestamp: entry.timestamp,
1249 runtime: entry.runtime,
1250 engine_version: entry.engine_version,
1251 containers: entry.containers,
1252 },
1253 );
1254 }
1255 }
1256 map
1257}
1258
1259pub fn parse_container_cache_content(content: &str) -> HashMap<String, ContainerCacheEntry> {
1261 let mut map = HashMap::new();
1262 for line in content.lines() {
1263 let trimmed = line.trim();
1264 if trimmed.is_empty() {
1265 continue;
1266 }
1267 if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1268 map.insert(
1269 entry.alias,
1270 ContainerCacheEntry {
1271 timestamp: entry.timestamp,
1272 runtime: entry.runtime,
1273 engine_version: entry.engine_version,
1274 containers: entry.containers,
1275 },
1276 );
1277 }
1278 }
1279 map
1280}
1281
1282pub fn save_container_cache(
1284 paths: Option<&crate::runtime::env::Paths>,
1285 cache: &HashMap<String, ContainerCacheEntry>,
1286) {
1287 if crate::demo_flag::is_demo() {
1288 return;
1289 }
1290 let Some(path) = cache_path(paths) else {
1291 return;
1292 };
1293 let mut lines = Vec::with_capacity(cache.len());
1294 for (alias, entry) in cache {
1295 let line = CacheLine {
1296 alias: alias.clone(),
1297 timestamp: entry.timestamp,
1298 runtime: entry.runtime,
1299 engine_version: entry.engine_version.clone(),
1300 containers: entry.containers.clone(),
1301 };
1302 if let Ok(s) = serde_json::to_string(&line) {
1303 lines.push(s);
1304 }
1305 }
1306 let content = lines.join("\n");
1307 log::debug!(
1308 "[purple] save_container_cache: {} host entries, {} bytes -> {}",
1309 cache.len(),
1310 content.len(),
1311 path.display()
1312 );
1313 if let Err(e) = crate::fs_util::atomic_write(&path, content.as_bytes()) {
1314 log::warn!(
1315 "[config] Failed to write container cache {}: {e}",
1316 path.display()
1317 );
1318 }
1319}
1320
1321pub fn truncate_str(s: &str, max: usize) -> String {
1327 let count = s.chars().count();
1328 if count <= max {
1329 s.to_string()
1330 } else {
1331 let cut = max.saturating_sub(2);
1332 let end = s.char_indices().nth(cut).map(|(i, _)| i).unwrap_or(s.len());
1333 format!("{}..", &s[..end])
1334 }
1335}
1336
1337pub fn format_uptime_short(seconds: u64) -> String {
1346 if seconds < 60 {
1347 format!("{seconds}s")
1348 } else if seconds < 3600 {
1349 format!("{}m", seconds / 60)
1350 } else if seconds < 86400 {
1351 format!("{}h", seconds / 3600)
1352 } else {
1353 format!("{}d", seconds / 86400)
1354 }
1355}
1356
1357pub fn format_relative_time(timestamp: u64) -> String {
1362 let now = if crate::demo_flag::is_demo() {
1363 crate::demo_flag::now_secs()
1364 } else {
1365 SystemTime::now()
1366 .duration_since(UNIX_EPOCH)
1367 .unwrap_or_default()
1368 .as_secs()
1369 };
1370 let diff = now.saturating_sub(timestamp);
1371 if diff < 60 {
1372 "just now".to_string()
1373 } else if diff < 3600 {
1374 format!("{}m ago", diff / 60)
1375 } else if diff < 86400 {
1376 format!("{}h ago", diff / 3600)
1377 } else {
1378 format!("{}d ago", diff / 86400)
1379 }
1380}
1381
1382#[cfg(test)]
1387#[path = "containers_tests.rs"]
1388mod tests;