1use anyhow::bail;
2use libc::pid_t;
3use std::fmt::Debug;
4
5use crate::result::Result;
6
7mod cmd;
8mod command;
9mod containerd;
10mod docker;
11mod kubernetes;
12mod lxc;
13mod lxd;
14mod nspawn;
15mod podman;
16mod process_id;
17mod result;
18
19pub trait Container: Debug {
20 fn lookup(&self, id: &str) -> Result<pid_t>;
21 fn check_required_tools(&self) -> Result<()>;
22}
23
24pub const AVAILABLE_CONTAINER_TYPES: &[&str] = &[
25 "process_id",
26 "podman",
27 "docker",
28 "nspawn",
29 "lxc",
30 "lxd",
31 "command",
32 "containerd",
33 "kubernetes",
34];
35
36fn default_order() -> Vec<Box<dyn Container>> {
37 let containers: Vec<Box<dyn Container>> = vec![
38 Box::new(process_id::ProcessId {}),
39 Box::new(podman::Podman {}),
40 Box::new(docker::Docker {}),
41 Box::new(nspawn::Nspawn {}),
42 Box::new(lxc::Lxc {}),
43 Box::new(lxd::Lxd {}),
44 Box::new(containerd::Containerd {}),
45 Box::new(kubernetes::Kubernetes {}),
46 ];
47 containers
48 .into_iter()
49 .filter(|c| c.check_required_tools().is_ok())
50 .collect()
51}
52
53pub fn lookup_container_type(name: &str) -> Option<Box<dyn Container>> {
54 Some(match name {
55 "process_id" => Box::new(process_id::ProcessId {}),
56 "podman" => Box::new(podman::Podman {}),
57 "docker" => Box::new(docker::Docker {}),
58 "nspawn" => Box::new(nspawn::Nspawn {}),
59 "lxc" => Box::new(lxc::Lxc {}),
60 "lxd" => Box::new(lxd::Lxd {}),
61 "containerd" => Box::new(containerd::Containerd {}),
62 "command" => Box::new(command::Command {}),
63 "kubernetes" => Box::new(kubernetes::Kubernetes {}),
64 _ => return None,
65 })
66}
67
68pub fn lookup_container_pid(
69 container_id: &str,
70 container_types: &[Box<dyn Container>],
71) -> Result<pid_t> {
72 for c in container_types {
73 c.check_required_tools()?;
74 }
75 let fallback: Vec<Box<dyn Container>> = default_order();
76 let types = if container_types.is_empty() {
77 fallback.as_slice()
78 } else {
79 container_types
80 };
81
82 let mut message = String::from("failed to find container - tried the following runtimes:");
83 for t in types {
84 match t.lookup(container_id) {
85 Ok(pid) => return Ok(pid),
86 Err(e) => {
87 message += &format!("\n - {:?}: {}", t, e);
88 }
89 };
90 }
91
92 bail!("{}", message)
93}