krab-runtime 0.1.0

Container runtime abstraction and Docker backend for krabkube
Documentation
pub mod cgroup;
pub mod docker;
pub mod host;
pub mod policy;

use bytes::Bytes;
use std::collections::BTreeMap;
use std::future::Future;
use std::io;
use tokio::sync::mpsc;

#[derive(Clone, Debug, Default, PartialEq)]
pub struct ContainerInfo {
    pub id: String,
    pub name: String,
    pub image: String,
    pub image_id: String,
    pub state: String,
    pub created: i64,
    pub labels: BTreeMap<String, String>,
    pub ports: Vec<(u16, String)>,
    pub ip: String,
    pub started_at: String,
    pub finished_at: String,
    pub exit_code: i64,
    pub restart_count: u64,
    pub tty: bool,
    pub pid: i64,
}

#[derive(Clone, Debug, Default)]
pub struct LogOpts {
    pub tail: Option<usize>,
    pub follow: bool,
    pub timestamps: bool,
    pub since_seconds: Option<u64>,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RestartPolicy {
    #[default]
    Always,
    OnFailure,
    Never,
}

impl RestartPolicy {
    pub fn parse(s: &str) -> Self {
        match s {
            "OnFailure" => RestartPolicy::OnFailure,
            "Never" => RestartPolicy::Never,
            _ => RestartPolicy::Always,
        }
    }

    pub fn docker_name(self) -> &'static str {
        match self {
            RestartPolicy::Always => "unless-stopped",
            RestartPolicy::OnFailure => "on-failure",
            RestartPolicy::Never => "no",
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct ExecOpts {
    pub cmd: Vec<String>,
    pub tty: bool,
    pub stdin: bool,
}

pub struct ExecHandle {
    pub exec_id: String,
    pub stdout: mpsc::Receiver<Bytes>,
    pub stderr: mpsc::Receiver<Bytes>,
    pub stdin: Option<Box<dyn tokio::io::AsyncWrite + Unpin + Send>>,
    pub hold: Option<Box<dyn tokio::io::AsyncWrite + Unpin + Send>>,
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct PortSpec {
    pub container_port: u16,
    pub protocol: String,
    pub host_port: Option<u16>,
    pub host_ip: Option<String>,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Mount {
    Bind {
        src: String,
        dst: String,
        read_only: bool,
    },
    Volume {
        name: String,
        dst: String,
        read_only: bool,
    },
    Tmpfs {
        dst: String,
    },
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct ContainerSpec {
    pub name: String,
    pub image: String,
    pub command: Vec<String>,
    pub args: Vec<String>,
    pub env: Vec<String>,
    pub working_dir: Option<String>,
    pub ports: Vec<PortSpec>,
    pub labels: BTreeMap<String, String>,
    pub restart: RestartPolicy,
    pub memory_bytes: Option<i64>,
    pub nano_cpus: Option<i64>,
    pub mounts: Vec<Mount>,
    pub hostname: Option<String>,
    pub dns_search: Vec<String>,
    pub dns_options: Vec<String>,
    pub network: Option<String>,
    pub aliases: Vec<String>,
    pub user: Option<String>,
    pub tty: bool,
    pub stdin: bool,
    pub allow_privilege_escalation: bool,
    pub read_only_root: bool,
}

pub const MANAGED_LABEL: &str = "krab.io/managed";
pub const NAME_PREFIX: &str = "krab_";

pub fn container_name(ns: &str, pod: &str, container: &str) -> String {
    format!("{NAME_PREFIX}{ns}_{pod}_{container}")
}

pub fn is_managed(info: &ContainerInfo) -> bool {
    info.name.trim_start_matches('/').starts_with(NAME_PREFIX)
        && info.labels.get(MANAGED_LABEL).map(String::as_str) == Some("true")
}

fn unsupported() -> io::Error {
    io::Error::new(io::ErrorKind::Unsupported, "runtime operation unsupported")
}

pub trait Runtime: Send + Sync + 'static {
    fn name(&self) -> &str;
    fn list(&self) -> impl Future<Output = io::Result<Vec<ContainerInfo>>> + Send;
    fn inspect(&self, info: &mut ContainerInfo) -> impl Future<Output = io::Result<()>> + Send;
    fn logs(
        &self,
        info: &ContainerInfo,
        opts: &LogOpts,
    ) -> impl Future<Output = io::Result<mpsc::Receiver<Bytes>>> + Send;
    fn pull_image(&self, _image: &str) -> impl Future<Output = io::Result<()>> + Send {
        async { Err(unsupported()) }
    }
    fn create_container(
        &self,
        _spec: &ContainerSpec,
    ) -> impl Future<Output = io::Result<String>> + Send {
        async { Err(unsupported()) }
    }
    fn start(&self, _id: &str) -> impl Future<Output = io::Result<()>> + Send {
        async { Err(unsupported()) }
    }
    fn stop(&self, _id: &str, _timeout_secs: u64) -> impl Future<Output = io::Result<()>> + Send {
        async { Err(unsupported()) }
    }
    fn remove(&self, _id: &str, _force: bool) -> impl Future<Output = io::Result<()>> + Send {
        async { Err(unsupported()) }
    }
    fn ensure_network(&self, _name: &str) -> impl Future<Output = io::Result<()>> + Send {
        async { Err(unsupported()) }
    }
    fn remove_network(&self, _name: &str) -> impl Future<Output = io::Result<()>> + Send {
        async { Err(unsupported()) }
    }
    fn connect_network(
        &self,
        _container: &str,
        _network: &str,
        _aliases: &[String],
    ) -> impl Future<Output = io::Result<()>> + Send {
        async { Err(unsupported()) }
    }
    fn disconnect_network(
        &self,
        _container: &str,
        _network: &str,
    ) -> impl Future<Output = io::Result<()>> + Send {
        async { Err(unsupported()) }
    }
    fn remove_volume(&self, _name: &str) -> impl Future<Output = io::Result<()>> + Send {
        async { Err(unsupported()) }
    }
    fn exec_run(
        &self,
        _id: &str,
        _cmd: &[String],
    ) -> impl Future<Output = io::Result<(i64, Vec<u8>)>> + Send {
        async { Err(unsupported()) }
    }
    fn exec_stream(
        &self,
        _id: &str,
        _opts: &ExecOpts,
    ) -> impl Future<Output = io::Result<ExecHandle>> + Send {
        async { Err(unsupported()) }
    }
    fn exec_resize(
        &self,
        _exec_id: &str,
        _width: u32,
        _height: u32,
    ) -> impl Future<Output = io::Result<()>> + Send {
        async { Err(unsupported()) }
    }
    fn exec_exit_code(&self, _exec_id: &str) -> impl Future<Output = io::Result<i64>> + Send {
        async { Err(unsupported()) }
    }
}