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 host_aliases: Vec<(String, String)>,
128 pub sysctls: Vec<(String, String)>,
129 pub extra_gids: Vec<u32>,
130 pub user: Option<String>,
131 pub tty: bool,
132 pub stdin: bool,
133 pub allow_privilege_escalation: bool,
134 pub read_only_root: bool,
135 pub seccomp: Option<String>,
136}
137
138pub const MANAGED_LABEL: &str = "krab.io/managed";
139pub const NAME_PREFIX: &str = "krab_";
140
141pub const POD_IP_TOKEN: &str = "\u{1}krab-pod-ip\u{1}";
142
143pub fn container_name(ns: &str, pod: &str, container: &str) -> String {
144 format!("{NAME_PREFIX}{ns}_{pod}_{container}")
145}
146
147pub fn is_managed(info: &ContainerInfo) -> bool {
148 info.name.trim_start_matches('/').starts_with(NAME_PREFIX)
149 && info.labels.get(MANAGED_LABEL).map(String::as_str) == Some("true")
150}
151
152fn unsupported() -> io::Error {
153 io::Error::new(io::ErrorKind::Unsupported, "runtime operation unsupported")
154}
155
156pub(crate) fn seccomp_supported(
157 runtime: &str,
158 requested: Option<&str>,
159 supported: &[&str],
160) -> io::Result<()> {
161 if let Some(t) = requested.filter(|t| !supported.contains(t)) {
162 return Err(io::Error::new(
163 io::ErrorKind::InvalidInput,
164 format!("seccompProfile type {t:?} is not supported by {runtime}"),
165 ));
166 }
167 Ok(())
168}
169
170pub trait Runtime: Send + Sync + 'static {
171 fn name(&self) -> &str;
172 fn list(&self) -> impl Future<Output = io::Result<Vec<ContainerInfo>>> + Send;
173 fn inspect(&self, info: &mut ContainerInfo) -> impl Future<Output = io::Result<()>> + Send;
174 fn logs(
175 &self,
176 info: &ContainerInfo,
177 opts: &LogOpts,
178 ) -> impl Future<Output = io::Result<mpsc::Receiver<Bytes>>> + Send;
179 fn pull_image(&self, _image: &str) -> impl Future<Output = io::Result<()>> + Send {
180 async { Err(unsupported()) }
181 }
182 fn create_container(
183 &self,
184 _spec: &ContainerSpec,
185 ) -> impl Future<Output = io::Result<String>> + Send {
186 async { Err(unsupported()) }
187 }
188 fn start(&self, _id: &str) -> impl Future<Output = io::Result<()>> + Send {
189 async { Err(unsupported()) }
190 }
191 fn stop(&self, _id: &str, _timeout_secs: u64) -> impl Future<Output = io::Result<()>> + Send {
192 async { Err(unsupported()) }
193 }
194 fn remove(&self, _id: &str, _force: bool) -> impl Future<Output = io::Result<()>> + Send {
195 async { Err(unsupported()) }
196 }
197 fn gc_images(
198 &self,
199 _low_free_percent: u64,
200 _high_free_percent: u64,
201 ) -> impl Future<Output = io::Result<usize>> + Send {
202 async { Ok(0) }
203 }
204 fn ensure_network(&self, _name: &str) -> impl Future<Output = io::Result<()>> + Send {
205 async { Err(unsupported()) }
206 }
207 fn remove_network(&self, _name: &str) -> impl Future<Output = io::Result<()>> + Send {
208 async { Err(unsupported()) }
209 }
210 fn connect_network(
211 &self,
212 _container: &str,
213 _network: &str,
214 _aliases: &[String],
215 ) -> impl Future<Output = io::Result<()>> + Send {
216 async { Err(unsupported()) }
217 }
218 fn disconnect_network(
219 &self,
220 _container: &str,
221 _network: &str,
222 ) -> impl Future<Output = io::Result<()>> + Send {
223 async { Err(unsupported()) }
224 }
225 fn remove_volume(&self, _name: &str) -> impl Future<Output = io::Result<()>> + Send {
226 async { Err(unsupported()) }
227 }
228 fn exec_run(
229 &self,
230 _id: &str,
231 _cmd: &[String],
232 ) -> impl Future<Output = io::Result<(i64, Vec<u8>)>> + Send {
233 async { Err(unsupported()) }
234 }
235 fn exec_stream(
236 &self,
237 _id: &str,
238 _opts: &ExecOpts,
239 ) -> impl Future<Output = io::Result<ExecHandle>> + Send {
240 async { Err(unsupported()) }
241 }
242 fn exec_resize(
243 &self,
244 _exec_id: &str,
245 _width: u32,
246 _height: u32,
247 ) -> impl Future<Output = io::Result<()>> + Send {
248 async { Err(unsupported()) }
249 }
250 fn exec_exit_code(&self, _exec_id: &str) -> impl Future<Output = io::Result<i64>> + Send {
251 async { Err(unsupported()) }
252 }
253 fn shutdown(&self) -> impl Future<Output = ()> + Send {
254 async {}
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 const NATIVE: &[&str] = &["Unconfined"];
263 const DOCKER: &[&str] = &["RuntimeDefault"];
264
265 #[test]
266 fn seccomp_rejects_unsupported_modes() {
267 assert!(seccomp_supported("the native runtime", None, NATIVE).is_ok());
268 assert!(seccomp_supported("the native runtime", Some("Unconfined"), NATIVE).is_ok());
269 for t in ["RuntimeDefault", "Localhost", "runtimeDefault", ""] {
270 let e = seccomp_supported("the native runtime", Some(t), NATIVE).unwrap_err();
271 assert_eq!(e.kind(), io::ErrorKind::InvalidInput);
272 assert!(e.to_string().contains(t));
273 }
274 assert!(seccomp_supported("docker", Some("RuntimeDefault"), DOCKER).is_ok());
275 assert!(seccomp_supported("docker", Some("Localhost"), DOCKER).is_err());
276 }
277}