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 crate::connection::auth_refused(stderr)
483 && !crate::security_key::sign_failures(stderr).is_empty()
484 {
485 log::debug!("[external] Security key did not sign; returning the PIN hint");
488 crate::messages::CONTAINER_SECURITY_KEY_PIN.to_string()
489 } else if lower.contains("permission denied") || lower.contains("got permission denied") {
490 crate::messages::CONTAINER_PERMISSION_DENIED.to_string()
491 } else if lower.contains("cannot connect to the docker daemon")
492 || lower.contains("cannot connect to podman")
493 {
494 crate::messages::CONTAINER_DAEMON_NOT_RUNNING.to_string()
495 } else if lower.contains("connection refused") {
496 crate::messages::CONTAINER_CONNECTION_REFUSED.to_string()
497 } else if lower.contains("no route to host") || lower.contains("network is unreachable") {
498 crate::messages::CONTAINER_HOST_UNREACHABLE.to_string()
499 } else {
500 crate::messages::container_command_failed(code.unwrap_or(1))
501 }
502}
503
504pub fn fetch_containers(
507 ctx: &SshContext<'_>,
508 cached_runtime: Option<ContainerRuntime>,
509) -> Result<ContainerListing, ContainerError> {
510 let command = container_list_command(cached_runtime);
511 let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
512 let alias = ctx.alias;
513 match result {
514 Ok(r) if r.status.success() => {
515 parse_container_output(&r.stdout, cached_runtime).map_err(|e| {
516 error!("[external] Container list parse failed: alias={alias}: {e}");
517 ContainerError {
518 runtime: cached_runtime,
519 message: e,
520 }
521 })
522 }
523 Ok(r) => {
524 let stderr = r.stderr.trim().to_string();
525 let msg = friendly_container_error(&stderr, r.status.code());
526 log::log!(
530 crate::connection::remote_exit_log_level(r.status.code().unwrap_or(-1)),
531 "[external] Container fetch failed: alias={alias}: {msg}"
532 );
533 Err(ContainerError {
534 runtime: cached_runtime,
535 message: msg,
536 })
537 }
538 Err(e) => {
539 error!("[external] Container fetch failed: alias={alias}: {e}");
540 Err(ContainerError {
541 runtime: cached_runtime,
542 message: e.to_string(),
543 })
544 }
545 }
546}
547
548pub fn spawn_container_listing<F>(
551 ctx: OwnedSshContext,
552 cached_runtime: Option<ContainerRuntime>,
553 send: F,
554) where
555 F: FnOnce(String, Result<ContainerListing, ContainerError>) + Send + 'static,
556{
557 std::thread::spawn(move || {
558 let result = fetch_containers(&ctx.borrow(), cached_runtime);
559 send(ctx.alias, result);
560 });
561}
562
563pub fn spawn_container_action<F>(
566 ctx: OwnedSshContext,
567 runtime: ContainerRuntime,
568 action: ContainerAction,
569 container_id: String,
570 send: F,
571) where
572 F: FnOnce(String, ContainerAction, Result<(), String>) + Send + 'static,
573{
574 std::thread::spawn(move || {
575 if let Err(e) = validate_container_id(&container_id) {
576 log::debug!(
577 "[purple] container action {} blocked on alias={}: invalid container_id: {}",
578 action.as_str(),
579 ctx.alias,
580 e
581 );
582 send(ctx.alias, action, Err(e));
583 return;
584 }
585 let alias = &ctx.alias;
586 info!(
587 "[external] Container action: {} container={container_id} alias={alias}",
588 action.as_str()
589 );
590 let command = container_action_command(runtime, action, &container_id);
591 let result = crate::snippet::run_snippet_ctx(&ctx.borrow(), &command, true);
592 match result {
593 Ok(r) if r.status.success() => send(ctx.alias, action, Ok(())),
594 Ok(r) => {
595 let err = friendly_container_error(r.stderr.trim(), r.status.code());
596 log::log!(
600 crate::connection::remote_exit_log_level(r.status.code().unwrap_or(-1)),
601 "[external] Container {} failed: alias={alias} container={container_id}: {err}",
602 action.as_str()
603 );
604 send(ctx.alias, action, Err(err));
605 }
606 Err(e) => {
607 error!(
608 "[external] Container {} failed: alias={alias} container={container_id}: {e}",
609 action.as_str()
610 );
611 send(ctx.alias, action, Err(e.to_string()));
612 }
613 }
614 });
615}
616
617#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
625pub struct ContainerInspect {
626 pub exit_code: i32,
627 pub oom_killed: bool,
628 pub started_at: String,
629 pub finished_at: String,
630 pub created_at: String,
631 pub health: Option<String>,
634 pub restart_count: u32,
635 pub command: Option<Vec<String>>,
636 pub entrypoint: Option<Vec<String>>,
637 pub env_count: usize,
638 pub mount_count: usize,
639 pub networks: Vec<NetworkInfo>,
640 pub image_digest: Option<String>,
642 pub restart_policy: Option<String>,
643 pub user: Option<String>,
644 pub privileged: bool,
645 pub readonly_rootfs: bool,
646 pub apparmor_profile: Option<String>,
647 pub seccomp_profile: Option<String>,
648 pub cap_add: Vec<String>,
649 pub cap_drop: Vec<String>,
650 pub mounts: Vec<MountInfo>,
651 pub compose_project: Option<String>,
652 pub compose_service: Option<String>,
653 pub pid: Option<u32>,
655 pub stop_signal: Option<String>,
656 pub stop_timeout: Option<u32>,
657 pub image_version: Option<String>,
659 pub image_revision: Option<String>,
660 pub image_source: Option<String>,
661 pub working_dir: Option<String>,
662 pub hostname: Option<String>,
663 pub memory_limit: Option<u64>,
665 pub cpu_limit_nanos: Option<u64>,
666 pub pids_limit: Option<i64>,
667 pub log_driver: Option<String>,
668 pub network_mode: Option<String>,
670 pub health_test: Option<Vec<String>>,
672 pub health_interval_ns: Option<u64>,
673 pub health_failing_streak: Option<u32>,
674}
675
676#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
677pub struct NetworkInfo {
678 pub name: String,
679 pub ip_address: String,
680}
681
682#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
683pub struct MountInfo {
684 pub source: String,
685 pub destination: String,
686 pub read_only: bool,
687}
688
689pub(crate) fn container_inspect_command(runtime: ContainerRuntime, container_id: &str) -> String {
695 format!("{} inspect {}", runtime.as_str(), container_id)
696}
697
698pub fn exit_code_meaning(code: i32) -> Option<&'static str> {
704 match code {
705 1 => Some("application error"),
706 125 => Some("docker run failed"),
707 126 => Some("command not executable"),
708 127 => Some("command not found"),
709 130 => Some("interrupted (SIGINT)"),
710 137 => Some("killed (SIGKILL / OOM)"),
711 139 => Some("segfault (SIGSEGV)"),
712 143 => Some("terminated (SIGTERM)"),
713 _ => None,
714 }
715}
716
717pub fn parse_container_inspect(output: &str) -> Result<ContainerInspect, String> {
722 let trimmed = output.trim();
723 if trimmed.is_empty() {
724 return Err(crate::messages::CONTAINER_INSPECT_EMPTY.to_string());
725 }
726 let value: serde_json::Value = serde_json::from_str(trimmed)
727 .map_err(|e| crate::messages::container_inspect_parse_failed(&e.to_string()))?;
728 let entry = value
729 .as_array()
730 .and_then(|a| a.first())
731 .ok_or_else(|| crate::messages::CONTAINER_INSPECT_EMPTY.to_string())?;
732
733 let state = &entry["State"];
734 let config = &entry["Config"];
735 let network_settings = &entry["NetworkSettings"];
736
737 let exit_code = state["ExitCode"].as_i64().unwrap_or(0) as i32;
738 let oom_killed = state["OOMKilled"]
743 .as_bool()
744 .or_else(|| state["OomKilled"].as_bool())
745 .unwrap_or(false);
746 let started_at = state["StartedAt"].as_str().unwrap_or("").to_string();
747 let finished_at = state["FinishedAt"].as_str().unwrap_or("").to_string();
748 let health = state
749 .get("Health")
750 .and_then(|h| h.get("Status"))
751 .and_then(|s| s.as_str())
752 .map(|s| s.to_string());
753 let restart_count = entry["RestartCount"].as_u64().unwrap_or(0) as u32;
754
755 let command = config["Cmd"].as_array().map(|arr| {
756 arr.iter()
757 .filter_map(|v| v.as_str().map(|s| s.to_string()))
758 .collect()
759 });
760 let entrypoint = config["Entrypoint"].as_array().map(|arr| {
761 arr.iter()
762 .filter_map(|v| v.as_str().map(|s| s.to_string()))
763 .collect()
764 });
765 let env_count = config["Env"].as_array().map(|arr| arr.len()).unwrap_or(0);
766 let mount_count = entry["Mounts"].as_array().map(|arr| arr.len()).unwrap_or(0);
767
768 let networks = network_settings
769 .get("Networks")
770 .and_then(|n| n.as_object())
771 .map(|map| {
772 map.iter()
773 .map(|(name, cfg)| NetworkInfo {
774 name: name.clone(),
775 ip_address: cfg
776 .get("IPAddress")
777 .and_then(|v| v.as_str())
778 .unwrap_or("")
779 .to_string(),
780 })
781 .collect::<Vec<_>>()
782 })
783 .unwrap_or_default();
784
785 let host_config = &entry["HostConfig"];
786
787 let image_digest = entry["Image"]
788 .as_str()
789 .filter(|s| !s.is_empty())
790 .map(|s| s.to_string());
791 let restart_policy = host_config
792 .get("RestartPolicy")
793 .and_then(|p| p.get("Name"))
794 .and_then(|s| s.as_str())
795 .filter(|s| !s.is_empty() && *s != "no")
796 .map(|s| s.to_string());
797 let user = config["User"]
798 .as_str()
799 .filter(|s| !s.is_empty())
800 .map(|s| s.to_string());
801 let privileged = host_config["Privileged"].as_bool().unwrap_or(false);
802 let readonly_rootfs = host_config["ReadonlyRootfs"].as_bool().unwrap_or(false);
803 let apparmor_profile = host_config["AppArmorProfile"]
804 .as_str()
805 .or_else(|| entry["AppArmorProfile"].as_str())
806 .filter(|s| !s.is_empty())
807 .map(|s| s.to_string());
808 let seccomp_profile = host_config["SecurityOpt"].as_array().and_then(|arr| {
809 arr.iter()
810 .filter_map(|v| v.as_str())
811 .find_map(|s| s.strip_prefix("seccomp=").map(|v| v.to_string()))
812 });
813 let cap_add = host_config["CapAdd"]
814 .as_array()
815 .map(|arr| {
816 arr.iter()
817 .filter_map(|v| v.as_str().map(|s| s.to_string()))
818 .collect()
819 })
820 .unwrap_or_default();
821 let cap_drop = host_config["CapDrop"]
822 .as_array()
823 .map(|arr| {
824 arr.iter()
825 .filter_map(|v| v.as_str().map(|s| s.to_string()))
826 .collect()
827 })
828 .unwrap_or_default();
829 let mounts = entry["Mounts"]
830 .as_array()
831 .map(|arr| {
832 arr.iter()
833 .map(|m| MountInfo {
834 source: m["Source"].as_str().unwrap_or("").to_string(),
835 destination: m["Destination"].as_str().unwrap_or("").to_string(),
836 read_only: !m["RW"].as_bool().unwrap_or(true),
837 })
838 .collect()
839 })
840 .unwrap_or_default();
841 let labels = config.get("Labels").and_then(|l| l.as_object());
842 let label = |key: &str| {
843 labels
844 .and_then(|l| l.get(key))
845 .and_then(|v| v.as_str())
846 .filter(|s| !s.is_empty())
847 .map(|s| s.to_string())
848 };
849 let compose_project = label("com.docker.compose.project");
850 let compose_service = label("com.docker.compose.service");
851 let image_version = label("org.opencontainers.image.version");
852 let image_revision = label("org.opencontainers.image.revision");
853 let image_source = label("org.opencontainers.image.source");
854
855 let created_at = entry["Created"].as_str().unwrap_or("").to_string();
856 let pid = state["Pid"].as_u64().filter(|n| *n > 0).map(|n| n as u32);
859 let hostname = config["Hostname"]
860 .as_str()
861 .filter(|s| !s.is_empty())
862 .map(|s| s.to_string());
863 let working_dir = config["WorkingDir"]
864 .as_str()
865 .filter(|s| !s.is_empty())
866 .map(|s| s.to_string());
867 let stop_signal = config["StopSignal"]
868 .as_str()
869 .filter(|s| !s.is_empty())
870 .map(|s| s.to_string());
871 let stop_timeout = config["StopTimeout"].as_u64().map(|n| n as u32);
872
873 let network_mode = host_config["NetworkMode"]
874 .as_str()
875 .filter(|s| !s.is_empty() && *s != "default")
876 .map(|s| s.to_string());
877 let memory_limit = host_config["Memory"].as_u64().filter(|n| *n > 0);
879 let cpu_limit_nanos = host_config["NanoCpus"].as_u64().filter(|n| *n > 0);
880 let pids_limit = host_config["PidsLimit"].as_i64().filter(|n| *n > 0);
882 let log_driver = host_config
886 .get("LogConfig")
887 .and_then(|l| l.get("Type"))
888 .and_then(|v| v.as_str())
889 .filter(|s| !s.is_empty())
890 .map(|s| s.to_string());
891
892 let healthcheck = config.get("Healthcheck");
893 let health_test = healthcheck
894 .and_then(|h| h.get("Test"))
895 .and_then(|t| t.as_array())
896 .map(|arr| {
897 arr.iter()
898 .filter_map(|v| v.as_str().map(|s| s.to_string()))
899 .collect::<Vec<_>>()
900 })
901 .filter(|v| !v.is_empty());
902 let health_interval_ns = healthcheck
903 .and_then(|h| h.get("Interval"))
904 .and_then(|v| v.as_u64())
905 .filter(|n| *n > 0);
906 let health_failing_streak = state
907 .get("Health")
908 .and_then(|h| h.get("FailingStreak"))
909 .and_then(|v| v.as_u64())
910 .map(|n| n as u32);
911
912 Ok(ContainerInspect {
913 exit_code,
914 oom_killed,
915 started_at,
916 finished_at,
917 created_at,
918 health,
919 restart_count,
920 command,
921 entrypoint,
922 env_count,
923 mount_count,
924 networks,
925 image_digest,
926 restart_policy,
927 user,
928 privileged,
929 readonly_rootfs,
930 apparmor_profile,
931 seccomp_profile,
932 cap_add,
933 cap_drop,
934 mounts,
935 compose_project,
936 compose_service,
937 pid,
938 stop_signal,
939 stop_timeout,
940 image_version,
941 image_revision,
942 image_source,
943 working_dir,
944 hostname,
945 memory_limit,
946 cpu_limit_nanos,
947 pids_limit,
948 log_driver,
949 network_mode,
950 health_test,
951 health_interval_ns,
952 health_failing_streak,
953 })
954}
955
956pub fn parse_uptime_from_status(s: &str) -> Option<String> {
962 let body = s.strip_prefix("Up ")?;
963 let body = body.split('(').next()?.trim();
964 if body == "Less than a second" {
965 return Some("<1m".to_string());
966 }
967 if body == "About a minute" {
968 return Some("1m".to_string());
969 }
970 if body == "About an hour" {
971 return Some("1h".to_string());
972 }
973 let mut parts = body.split_whitespace();
974 let count: u64 = parts.next()?.parse().ok()?;
975 let unit = parts.next()?;
976 let suffix = match unit {
977 "second" | "seconds" => return Some("<1m".to_string()),
978 "minute" | "minutes" => "m",
979 "hour" | "hours" => "h",
980 "day" | "days" => "d",
981 "week" | "weeks" => "w",
982 "month" | "months" => "mo",
983 "year" | "years" => "y",
984 _ => return None,
985 };
986 Some(format!("{count}{suffix}"))
987}
988
989pub fn fetch_container_inspect(
992 ctx: &SshContext<'_>,
993 runtime: ContainerRuntime,
994 container_id: &str,
995) -> Result<ContainerInspect, String> {
996 validate_container_id(container_id)?;
997 let command = container_inspect_command(runtime, container_id);
998 let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
999 match result {
1000 Ok(r) if r.status.success() => parse_container_inspect(&r.stdout),
1001 Ok(r) => Err(crate::messages::container_command_failed(
1002 r.status.code().unwrap_or(1),
1003 )),
1004 Err(e) => Err(e.to_string()),
1005 }
1006}
1007
1008pub fn spawn_container_inspect_listing<F>(
1011 ctx: OwnedSshContext,
1012 runtime: ContainerRuntime,
1013 container_id: String,
1014 send: F,
1015) where
1016 F: FnOnce(String, String, Result<ContainerInspect, String>) + Send + 'static,
1017{
1018 std::thread::spawn(move || {
1019 let result = fetch_container_inspect(&ctx.borrow(), runtime, &container_id);
1020 send(ctx.alias, container_id, result);
1021 });
1022}
1023
1024pub(crate) fn container_logs_command(
1028 runtime: ContainerRuntime,
1029 container_id: &str,
1030 tail: usize,
1031) -> String {
1032 format!("{} logs --tail {} {}", runtime.as_str(), tail, container_id)
1033}
1034
1035pub fn fetch_container_logs(
1039 ctx: &SshContext<'_>,
1040 runtime: ContainerRuntime,
1041 container_id: &str,
1042 tail: usize,
1043) -> Result<Vec<String>, String> {
1044 validate_container_id(container_id)?;
1045 let command = container_logs_command(runtime, container_id, tail);
1046 let result = crate::snippet::run_snippet_ctx(ctx, &command, true);
1047 match result {
1048 Ok(r) if r.status.success() => Ok(parse_log_output(&r.stdout, &r.stderr)),
1049 Ok(r) => Err(crate::messages::container_command_failed(
1050 r.status.code().unwrap_or(1),
1051 )),
1052 Err(e) => Err(e.to_string()),
1053 }
1054}
1055
1056pub(crate) fn parse_log_output(stdout: &str, stderr: &str) -> Vec<String> {
1063 let mut lines: Vec<String> = stdout.lines().map(|s| s.to_string()).collect();
1064 while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1065 lines.pop();
1066 }
1067 for s in stderr.lines() {
1068 lines.push(s.to_string());
1069 }
1070 while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
1071 lines.pop();
1072 }
1073 lines
1074}
1075
1076pub fn spawn_container_logs_fetch<F>(
1081 ctx: OwnedSshContext,
1082 runtime: ContainerRuntime,
1083 container_id: String,
1084 container_name: String,
1085 tail: usize,
1086 send: F,
1087) where
1088 F: FnOnce(String, String, String, Result<Vec<String>, String>) + Send + 'static,
1089{
1090 if crate::demo_flag::is_demo() {
1091 let lines = demo_log_lines(&container_name, tail);
1092 log::debug!(
1093 "[purple] container_logs_fetch: demo short-circuit alias={} id={} lines={}",
1094 ctx.alias,
1095 container_id,
1096 lines.len()
1097 );
1098 send(ctx.alias, container_id, container_name, Ok(lines));
1099 return;
1100 }
1101 std::thread::spawn(move || {
1102 let result = fetch_container_logs(&ctx.borrow(), runtime, &container_id, tail);
1103 send(ctx.alias, container_id, container_name, result);
1104 });
1105}
1106
1107pub(crate) fn demo_log_lines(container_name: &str, tail: usize) -> Vec<String> {
1113 use std::time::{Duration, UNIX_EPOCH};
1114 let seed: u32 = container_name
1117 .bytes()
1118 .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32));
1119
1120 let templates: &[&str] = &[
1122 "INFO [{}] handled GET /api/v1/health 200 in 14ms",
1123 "INFO [{}] handled POST /api/v1/orders 201 in 38ms (user_id={user})",
1124 "DEBUG [{}] cache hit key=session:{user} ttl=3600",
1125 "INFO [{}] handled GET /api/v1/users/{user} 200 in 11ms",
1126 "WARN [{}] slow query detected duration=812ms statement=SELECT FROM orders",
1127 "INFO [{}] connection pool size=12 idle=8 in_use=4",
1128 "DEBUG [{}] flushing metrics batch size=64",
1129 "INFO [{}] handled GET /api/v1/inventory 200 in 22ms",
1130 "ERROR [{}] upstream timeout after 5000ms target=payments retry=1",
1131 "WARN [{}] retrying request attempt=2 backoff=250ms",
1132 "INFO [{}] handled POST /api/v1/login 200 in 31ms",
1133 "DEBUG [{}] gc cycle reclaimed=42MB took=18ms",
1134 "INFO [{}] heartbeat ok rss=128MB cpu=4%",
1135 "ERROR [{}] failed to acquire lock resource=cache_warmer waiter=3",
1136 "INFO [{}] handled DELETE /api/v1/sessions/{user} 204 in 9ms",
1137 "WARN [{}] disk usage at 78% mount=/data threshold=80%",
1138 "INFO [{}] handled GET /api/v1/search?q=widget 200 in 47ms",
1139 "DEBUG [{}] websocket ping rtt=12ms",
1140 ];
1141
1142 let now = crate::demo_flag::now_secs();
1147
1148 let mut lines = Vec::with_capacity(tail);
1151 for i in 0..tail {
1152 let template = templates[(i + seed as usize) % templates.len()];
1153 let user = 1000 + ((seed as usize + i * 7) % 50);
1154 let secs_back = (i as u64) * 3;
1155 let line_time = UNIX_EPOCH + Duration::from_secs(now.saturating_sub(secs_back));
1156 let ts = format_demo_timestamp(line_time);
1157 let body = template
1158 .replace("{}", container_name)
1159 .replace("{user}", &user.to_string());
1160 lines.push(format!("{} {}", ts, body));
1161 }
1162 lines.reverse();
1165 lines
1166}
1167
1168fn format_demo_timestamp(t: std::time::SystemTime) -> String {
1169 use std::time::UNIX_EPOCH;
1170 let secs = t
1171 .duration_since(UNIX_EPOCH)
1172 .map(|d| d.as_secs())
1173 .unwrap_or(0);
1174 let days_since_epoch = (secs / 86_400) as i64;
1177 let seconds_in_day = (secs % 86_400) as u32;
1178 let h = seconds_in_day / 3600;
1179 let m = (seconds_in_day % 3600) / 60;
1180 let s = seconds_in_day % 60;
1181 let (y, mo, d) = civil_from_days(days_since_epoch);
1182 format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", y, mo, d, h, m, s)
1183}
1184
1185fn civil_from_days(z: i64) -> (i32, u32, u32) {
1188 let z = z + 719_468;
1189 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
1190 let doe = (z - era * 146_097) as u64;
1191 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1192 let y = yoe as i64 + era * 400;
1193 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1194 let mp = (5 * doy + 2) / 153;
1195 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
1196 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1197 let y = if m <= 2 { y + 1 } else { y };
1198 (y as i32, m, d)
1199}
1200
1201#[derive(Debug, Clone)]
1210pub struct ContainerCacheEntry {
1211 pub timestamp: u64,
1212 pub runtime: ContainerRuntime,
1213 pub engine_version: Option<String>,
1214 pub containers: Vec<ContainerInfo>,
1215}
1216
1217#[derive(Serialize, Deserialize)]
1221struct CacheLine {
1222 alias: String,
1223 timestamp: u64,
1224 runtime: ContainerRuntime,
1225 #[serde(default, skip_serializing_if = "Option::is_none")]
1226 engine_version: Option<String>,
1227 containers: Vec<ContainerInfo>,
1228}
1229
1230fn cache_path(paths: Option<&crate::runtime::env::Paths>) -> Option<std::path::PathBuf> {
1231 paths.map(crate::runtime::env::Paths::container_cache)
1232}
1233
1234pub fn load_container_cache(
1237 paths: Option<&crate::runtime::env::Paths>,
1238) -> HashMap<String, ContainerCacheEntry> {
1239 let mut map = HashMap::new();
1240 let Some(path) = cache_path(paths) else {
1241 return map;
1242 };
1243 let Ok(content) = std::fs::read_to_string(&path) else {
1244 return map;
1245 };
1246 for line in content.lines() {
1247 let trimmed = line.trim();
1248 if trimmed.is_empty() {
1249 continue;
1250 }
1251 if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1252 map.insert(
1253 entry.alias,
1254 ContainerCacheEntry {
1255 timestamp: entry.timestamp,
1256 runtime: entry.runtime,
1257 engine_version: entry.engine_version,
1258 containers: entry.containers,
1259 },
1260 );
1261 }
1262 }
1263 map
1264}
1265
1266pub fn parse_container_cache_content(content: &str) -> HashMap<String, ContainerCacheEntry> {
1268 let mut map = HashMap::new();
1269 for line in content.lines() {
1270 let trimmed = line.trim();
1271 if trimmed.is_empty() {
1272 continue;
1273 }
1274 if let Ok(entry) = serde_json::from_str::<CacheLine>(trimmed) {
1275 map.insert(
1276 entry.alias,
1277 ContainerCacheEntry {
1278 timestamp: entry.timestamp,
1279 runtime: entry.runtime,
1280 engine_version: entry.engine_version,
1281 containers: entry.containers,
1282 },
1283 );
1284 }
1285 }
1286 map
1287}
1288
1289pub fn save_container_cache(
1291 paths: Option<&crate::runtime::env::Paths>,
1292 cache: &HashMap<String, ContainerCacheEntry>,
1293) {
1294 if crate::demo_flag::is_demo() {
1295 return;
1296 }
1297 let Some(path) = cache_path(paths) else {
1298 return;
1299 };
1300 let mut lines = Vec::with_capacity(cache.len());
1301 for (alias, entry) in cache {
1302 let line = CacheLine {
1303 alias: alias.clone(),
1304 timestamp: entry.timestamp,
1305 runtime: entry.runtime,
1306 engine_version: entry.engine_version.clone(),
1307 containers: entry.containers.clone(),
1308 };
1309 if let Ok(s) = serde_json::to_string(&line) {
1310 lines.push(s);
1311 }
1312 }
1313 let content = lines.join("\n");
1314 log::debug!(
1315 "[purple] save_container_cache: {} host entries, {} bytes -> {}",
1316 cache.len(),
1317 content.len(),
1318 path.display()
1319 );
1320 if let Err(e) = crate::fs_util::atomic_write(&path, content.as_bytes()) {
1321 log::warn!(
1322 "[config] Failed to write container cache {}: {e}",
1323 path.display()
1324 );
1325 }
1326}
1327
1328pub fn truncate_str(s: &str, max: usize) -> String {
1334 let count = s.chars().count();
1335 if count <= max {
1336 s.to_string()
1337 } else {
1338 let cut = max.saturating_sub(2);
1339 let end = s.char_indices().nth(cut).map(|(i, _)| i).unwrap_or(s.len());
1340 format!("{}..", &s[..end])
1341 }
1342}
1343
1344pub fn format_uptime_short(seconds: u64) -> String {
1353 if seconds < 60 {
1354 format!("{seconds}s")
1355 } else if seconds < 3600 {
1356 format!("{}m", seconds / 60)
1357 } else if seconds < 86400 {
1358 format!("{}h", seconds / 3600)
1359 } else {
1360 format!("{}d", seconds / 86400)
1361 }
1362}
1363
1364pub fn format_relative_time(timestamp: u64) -> String {
1369 let now = if crate::demo_flag::is_demo() {
1370 crate::demo_flag::now_secs()
1371 } else {
1372 SystemTime::now()
1373 .duration_since(UNIX_EPOCH)
1374 .unwrap_or_default()
1375 .as_secs()
1376 };
1377 let diff = now.saturating_sub(timestamp);
1378 if diff < 60 {
1379 "just now".to_string()
1380 } else if diff < 3600 {
1381 format!("{}m ago", diff / 60)
1382 } else if diff < 86400 {
1383 format!("{}h ago", diff / 3600)
1384 } else {
1385 format!("{}d ago", diff / 86400)
1386 }
1387}
1388
1389#[cfg(test)]
1394#[path = "containers_tests.rs"]
1395mod tests;