Skip to main content

krab_runtime/
lib.rs

1pub mod cgroup;
2pub mod docker;
3pub mod host;
4pub mod native;
5pub mod policy;
6pub mod subpath;
7
8use bytes::Bytes;
9use std::collections::BTreeMap;
10use std::future::Future;
11use std::io;
12use tokio::sync::mpsc;
13
14#[derive(Clone, Debug, Default, PartialEq)]
15pub struct ContainerInfo {
16    pub id: String,
17    pub name: String,
18    pub image: String,
19    pub image_id: String,
20    pub state: String,
21    pub created: i64,
22    pub labels: BTreeMap<String, String>,
23    pub ports: Vec<(u16, String)>,
24    pub ip: String,
25    pub started_at: String,
26    pub finished_at: String,
27    pub exit_code: i64,
28    pub oom_killed: bool,
29    pub restart_count: u64,
30    pub tty: bool,
31    pub pid: i64,
32}
33
34#[derive(Clone, Debug, Default)]
35pub struct LogOpts {
36    pub tail: Option<usize>,
37    pub follow: bool,
38    pub timestamps: bool,
39    pub since_seconds: Option<u64>,
40}
41
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub enum RestartPolicy {
44    #[default]
45    Always,
46    OnFailure,
47    Never,
48}
49
50impl RestartPolicy {
51    pub fn parse(s: &str) -> Self {
52        match s {
53            "OnFailure" => RestartPolicy::OnFailure,
54            "Never" => RestartPolicy::Never,
55            _ => RestartPolicy::Always,
56        }
57    }
58
59    pub fn docker_name(self) -> &'static str {
60        match self {
61            RestartPolicy::Always => "unless-stopped",
62            RestartPolicy::OnFailure => "on-failure",
63            RestartPolicy::Never => "no",
64        }
65    }
66}
67
68#[derive(Clone, Debug, Default)]
69pub struct ExecOpts {
70    pub cmd: Vec<String>,
71    pub tty: bool,
72    pub stdin: bool,
73}
74
75pub struct ExecHandle {
76    pub exec_id: String,
77    pub stdout: mpsc::Receiver<Bytes>,
78    pub stderr: mpsc::Receiver<Bytes>,
79    pub stdin: Option<Box<dyn tokio::io::AsyncWrite + Unpin + Send>>,
80    pub hold: Option<Box<dyn tokio::io::AsyncWrite + Unpin + Send>>,
81}
82
83#[derive(Clone, Debug, Default, PartialEq)]
84pub struct PortSpec {
85    pub container_port: u16,
86    pub protocol: String,
87    pub host_port: Option<u16>,
88    pub host_ip: Option<String>,
89}
90
91#[derive(Clone, Debug, PartialEq)]
92pub enum Mount {
93    Bind {
94        src: String,
95        dst: String,
96        read_only: bool,
97    },
98    Volume {
99        name: String,
100        dst: String,
101        read_only: bool,
102    },
103    Tmpfs {
104        dst: String,
105    },
106}
107
108#[derive(Clone, Debug, Default, PartialEq)]
109pub struct ContainerSpec {
110    pub name: String,
111    pub image: String,
112    pub command: Vec<String>,
113    pub args: Vec<String>,
114    pub env: Vec<String>,
115    pub working_dir: Option<String>,
116    pub ports: Vec<PortSpec>,
117    pub labels: BTreeMap<String, String>,
118    pub restart: RestartPolicy,
119    pub memory_bytes: Option<i64>,
120    pub nano_cpus: Option<i64>,
121    pub mounts: Vec<Mount>,
122    pub hostname: Option<String>,
123    pub dns_search: Vec<String>,
124    pub dns_options: Vec<String>,
125    pub network: Option<String>,
126    pub aliases: Vec<String>,
127    pub user: Option<String>,
128    pub tty: bool,
129    pub stdin: bool,
130    pub allow_privilege_escalation: bool,
131    pub read_only_root: bool,
132    pub seccomp: Option<String>,
133}
134
135pub const MANAGED_LABEL: &str = "krab.io/managed";
136pub const NAME_PREFIX: &str = "krab_";
137
138pub const POD_IP_TOKEN: &str = "\u{1}krab-pod-ip\u{1}";
139
140pub fn container_name(ns: &str, pod: &str, container: &str) -> String {
141    format!("{NAME_PREFIX}{ns}_{pod}_{container}")
142}
143
144pub fn is_managed(info: &ContainerInfo) -> bool {
145    info.name.trim_start_matches('/').starts_with(NAME_PREFIX)
146        && info.labels.get(MANAGED_LABEL).map(String::as_str) == Some("true")
147}
148
149fn unsupported() -> io::Error {
150    io::Error::new(io::ErrorKind::Unsupported, "runtime operation unsupported")
151}
152
153pub(crate) fn seccomp_supported(
154    runtime: &str,
155    requested: Option<&str>,
156    supported: &[&str],
157) -> io::Result<()> {
158    if let Some(t) = requested.filter(|t| !supported.contains(t)) {
159        return Err(io::Error::new(
160            io::ErrorKind::InvalidInput,
161            format!("seccompProfile type {t:?} is not supported by {runtime}"),
162        ));
163    }
164    Ok(())
165}
166
167pub trait Runtime: Send + Sync + 'static {
168    fn name(&self) -> &str;
169    fn list(&self) -> impl Future<Output = io::Result<Vec<ContainerInfo>>> + Send;
170    fn inspect(&self, info: &mut ContainerInfo) -> impl Future<Output = io::Result<()>> + Send;
171    fn logs(
172        &self,
173        info: &ContainerInfo,
174        opts: &LogOpts,
175    ) -> impl Future<Output = io::Result<mpsc::Receiver<Bytes>>> + Send;
176    fn pull_image(&self, _image: &str) -> impl Future<Output = io::Result<()>> + Send {
177        async { Err(unsupported()) }
178    }
179    fn create_container(
180        &self,
181        _spec: &ContainerSpec,
182    ) -> impl Future<Output = io::Result<String>> + Send {
183        async { Err(unsupported()) }
184    }
185    fn start(&self, _id: &str) -> impl Future<Output = io::Result<()>> + Send {
186        async { Err(unsupported()) }
187    }
188    fn stop(&self, _id: &str, _timeout_secs: u64) -> impl Future<Output = io::Result<()>> + Send {
189        async { Err(unsupported()) }
190    }
191    fn remove(&self, _id: &str, _force: bool) -> impl Future<Output = io::Result<()>> + Send {
192        async { Err(unsupported()) }
193    }
194    fn gc_images(
195        &self,
196        _low_free_percent: u64,
197        _high_free_percent: u64,
198    ) -> impl Future<Output = io::Result<usize>> + Send {
199        async { Ok(0) }
200    }
201    fn ensure_network(&self, _name: &str) -> impl Future<Output = io::Result<()>> + Send {
202        async { Err(unsupported()) }
203    }
204    fn remove_network(&self, _name: &str) -> impl Future<Output = io::Result<()>> + Send {
205        async { Err(unsupported()) }
206    }
207    fn connect_network(
208        &self,
209        _container: &str,
210        _network: &str,
211        _aliases: &[String],
212    ) -> impl Future<Output = io::Result<()>> + Send {
213        async { Err(unsupported()) }
214    }
215    fn disconnect_network(
216        &self,
217        _container: &str,
218        _network: &str,
219    ) -> impl Future<Output = io::Result<()>> + Send {
220        async { Err(unsupported()) }
221    }
222    fn remove_volume(&self, _name: &str) -> impl Future<Output = io::Result<()>> + Send {
223        async { Err(unsupported()) }
224    }
225    fn exec_run(
226        &self,
227        _id: &str,
228        _cmd: &[String],
229    ) -> impl Future<Output = io::Result<(i64, Vec<u8>)>> + Send {
230        async { Err(unsupported()) }
231    }
232    fn exec_stream(
233        &self,
234        _id: &str,
235        _opts: &ExecOpts,
236    ) -> impl Future<Output = io::Result<ExecHandle>> + Send {
237        async { Err(unsupported()) }
238    }
239    fn exec_resize(
240        &self,
241        _exec_id: &str,
242        _width: u32,
243        _height: u32,
244    ) -> impl Future<Output = io::Result<()>> + Send {
245        async { Err(unsupported()) }
246    }
247    fn exec_exit_code(&self, _exec_id: &str) -> impl Future<Output = io::Result<i64>> + Send {
248        async { Err(unsupported()) }
249    }
250    fn shutdown(&self) -> impl Future<Output = ()> + Send {
251        async {}
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    const NATIVE: &[&str] = &["Unconfined"];
260    const DOCKER: &[&str] = &["RuntimeDefault"];
261
262    #[test]
263    fn seccomp_rejects_unsupported_modes() {
264        assert!(seccomp_supported("the native runtime", None, NATIVE).is_ok());
265        assert!(seccomp_supported("the native runtime", Some("Unconfined"), NATIVE).is_ok());
266        for t in ["RuntimeDefault", "Localhost", "runtimeDefault", ""] {
267            let e = seccomp_supported("the native runtime", Some(t), NATIVE).unwrap_err();
268            assert_eq!(e.kind(), io::ErrorKind::InvalidInput);
269            assert!(e.to_string().contains(t));
270        }
271        assert!(seccomp_supported("docker", Some("RuntimeDefault"), DOCKER).is_ok());
272        assert!(seccomp_supported("docker", Some("Localhost"), DOCKER).is_err());
273    }
274}