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(
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 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
550pub 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
573pub 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 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#[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 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 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 pub pid: Option<u32>,
674 pub stop_signal: Option<String>,
675 pub stop_timeout: Option<u32>,
676 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 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 pub network_mode: Option<String>,
689 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
708pub(crate) fn container_inspect_command(runtime: ContainerRuntime, container_id: &str) -> String {
714 format!("{} inspect {}", runtime.as_str(), container_id)
715}
716
717pub 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
736pub 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 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 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 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 let pids_limit = host_config["PidsLimit"].as_i64().filter(|n| *n > 0);
901 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
975pub 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
1008pub 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
1036pub 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
1060pub(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
1071pub 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
1101pub(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
1121pub 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
1160pub(crate) fn demo_log_lines(container_name: &str, tail: usize) -> Vec<String> {
1166 use std::time::{Duration, UNIX_EPOCH};
1167 let seed: u32 = container_name
1170 .bytes()
1171 .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32));
1172
1173 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 let now = crate::demo_flag::now_secs();
1200
1201 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 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 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
1238fn 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#[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#[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
1287pub 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
1319pub 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
1342pub 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
1381pub 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
1397pub 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
1417pub 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#[cfg(test)]
1447#[path = "containers_tests.rs"]
1448mod tests;