krab-controllers 0.2.3

Scheduler, kubelet and controllers for krabkube
Documentation
use crate::util::s;
use krab_runtime::Runtime;
use serde_json::Value;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::time::timeout;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
    Startup = 0,
    Liveness = 1,
    Readiness = 2,
}

impl Kind {
    pub fn field(self) -> &'static str {
        match self {
            Kind::Startup => "startupProbe",
            Kind::Liveness => "livenessProbe",
            Kind::Readiness => "readinessProbe",
        }
    }

    pub fn title(self) -> &'static str {
        match self {
            Kind::Startup => "Startup",
            Kind::Liveness => "Liveness",
            Kind::Readiness => "Readiness",
        }
    }
}

pub struct Params {
    pub initial_delay: u64,
    pub period: u64,
    pub timeout: u64,
    pub success: u32,
    pub failure: u32,
}

pub fn params(p: &Value) -> Params {
    let n = |k: &str, d: u64| p[k].as_u64().unwrap_or(d);
    Params {
        initial_delay: n("initialDelaySeconds", 0),
        period: n("periodSeconds", 10).max(1),
        timeout: n("timeoutSeconds", 1).max(1),
        success: n("successThreshold", 1).max(1) as u32,
        failure: n("failureThreshold", 3).max(1) as u32,
    }
}

fn resolve_port(c: &Value, port: &Value) -> Option<u16> {
    match port {
        Value::Number(n) => n.as_u64().and_then(|p| u16::try_from(p).ok()),
        Value::String(name) => name.parse().ok().or_else(|| {
            c["ports"].as_array()?.iter().find_map(|p| {
                (p["name"].as_str() == Some(name)).then(|| {
                    p["containerPort"]
                        .as_u64()
                        .and_then(|x| u16::try_from(x).ok())
                })?
            })
        }),
        _ => None,
    }
}

pub async fn run<R: Runtime>(
    rt: &R,
    id: &str,
    c: &Value,
    p: &Value,
    pod_ip: &str,
) -> Result<(), String> {
    let prm = params(p);
    let limit = Duration::from_secs(prm.timeout);
    if let Some(cmd) = p["exec"]["command"].as_array() {
        let cmd: Vec<String> = cmd
            .iter()
            .filter_map(|x| x.as_str().map(str::to_string))
            .collect();
        return match timeout(limit, rt.exec_run(id, &cmd)).await {
            Err(_) => Err(format!("command timed out after {}s", prm.timeout)),
            Ok(Err(e)) => Err(e.to_string()),
            Ok(Ok((0, _))) => Ok(()),
            Ok(Ok((code, out))) => Err(format!(
                "command exited with {code}: {}",
                String::from_utf8_lossy(&out[..out.len().min(256)]).trim()
            )),
        };
    }
    let (section, http) = if p["httpGet"].is_object() {
        (&p["httpGet"], true)
    } else if p["tcpSocket"].is_object() {
        (&p["tcpSocket"], false)
    } else if p["grpc"].is_object() {
        (&p["grpc"], false)
    } else {
        return Ok(());
    };
    let port = resolve_port(c, &section["port"]).ok_or("invalid probe port")?;
    let host = pod_ip;
    let path = match s(section, "/path") {
        "" => "/",
        x => x,
    };
    let headers: Vec<(&str, &str)> = section["httpHeaders"]
        .as_array()
        .into_iter()
        .flatten()
        .map(|h| (s(h, "/name"), s(h, "/value")))
        .collect();
    let crlf = |x: &str| x.contains(['\r', '\n']);
    if http
        && (!path.starts_with('/')
            || crlf(path)
            || headers
                .iter()
                .any(|(k, v)| k.is_empty() || k.contains(':') || crlf(k) || crlf(v)))
    {
        return Err("invalid httpGet probe: path or headers contain forbidden characters".into());
    }
    if host.is_empty() {
        return Err("pod has no IP".into());
    }
    let addr = format!("{host}:{port}");
    let fut = async {
        let mut stream = TcpStream::connect(&addr)
            .await
            .map_err(|e| format!("dial tcp {addr}: {e}"))?;
        if !http || s(section, "/scheme").eq_ignore_ascii_case("https") {
            return Ok(());
        }
        let mut req = format!(
            "GET {path} HTTP/1.1\r\nHost: {addr}\r\nUser-Agent: kube-probe/1.34\r\nAccept: */*\r\nConnection: close\r\n"
        );
        for (k, v) in &headers {
            req.push_str(&format!("{k}: {v}\r\n"));
        }
        req.push_str("\r\n");
        stream
            .write_all(req.as_bytes())
            .await
            .map_err(|e| e.to_string())?;
        let mut buf = [0u8; 64];
        let mut got = 0;
        while got < 12 {
            let n = stream
                .read(&mut buf[got..])
                .await
                .map_err(|e| e.to_string())?;
            if n == 0 {
                break;
            }
            got += n;
        }
        let line = String::from_utf8_lossy(&buf[..got]);
        let code: u16 = line
            .split_whitespace()
            .nth(1)
            .and_then(|c| c.parse().ok())
            .ok_or("malformed HTTP response")?;
        if (200..400).contains(&code) {
            Ok(())
        } else {
            Err(format!("HTTP probe failed with statuscode: {code}"))
        }
    };
    match timeout(limit, fut).await {
        Err(_) => Err(format!("Get \"http://{addr}\": context deadline exceeded")),
        Ok(r) => r,
    }
}