krab-agent 0.2.3

Lightweight kubelet for a real Kubernetes control plane (krab agent)
Documentation
use crate::client::Client;
use krab_controllers::util::{now_micro, now_rfc, s};
use krab_runtime::Runtime;
use krab_runtime::host::{HostInfo, disk_free_percent, host_info, meminfo, threads_used_percent};
use serde_json::{Value, json};
use std::io;
use std::time::Duration;

pub const LEASE_NS: &str = "kube-node-lease";
pub const VERSION: &str = "v1.34.0-krab";
const MERGE: &str = "application/strategic-merge-patch+json";
const HEARTBEAT: Duration = Duration::from_secs(10);
const STATUS_EVERY: u32 = 30;
pub(crate) const MEM_AVAILABLE_MIN_KIB: u64 = 100 * 1024;
const DISK_FREE_MIN_PERCENT: u64 = 10;
const PID_USED_MAX_PERCENT: u64 = 90;

#[derive(Clone, Copy, Default, PartialEq, Eq)]
struct Pressure {
    memory: bool,
    disk: bool,
    pid: bool,
}

fn pressure_from(mem_avail_kib: u64, disk_free: Option<u64>, pid_used: Option<u64>) -> Pressure {
    Pressure {
        memory: mem_avail_kib < MEM_AVAILABLE_MIN_KIB,
        disk: disk_free.is_some_and(|f| f < DISK_FREE_MIN_PERCENT),
        pid: pid_used.is_some_and(|u| u > PID_USED_MAX_PERCENT),
    }
}

fn pressure() -> Pressure {
    pressure_from(
        meminfo().1,
        ["/var/lib", "/"].iter().find_map(|p| disk_free_percent(p)),
        threads_used_percent(),
    )
}

fn pressure_cond(
    kind: &str,
    on: bool,
    now: &str,
    since: &str,
    good: (&str, &str),
    bad: (&str, &str),
) -> Value {
    let (reason, msg) = if on { bad } else { good };
    json!({"type": kind, "status": if on { "True" } else { "False" }, "lastHeartbeatTime": now, "lastTransitionTime": since, "reason": reason, "message": msg})
}

fn conditions(ready: bool, since: &str, p: Pressure) -> Value {
    let now = now_rfc();
    let (st, reason, msg) = if ready {
        ("True", "KubeletReady", "krab agent is posting ready status")
    } else {
        (
            "False",
            "KubeletNotReady",
            "container runtime is unreachable",
        )
    };
    json!([
        {"type": "Ready", "status": st, "lastHeartbeatTime": now, "lastTransitionTime": since, "reason": reason, "message": msg},
        pressure_cond("MemoryPressure", p.memory, &now, since, ("KubeletHasSufficientMemory", "kubelet has sufficient memory available"), ("KubeletHasInsufficientMemory", "kubelet has insufficient memory available")),
        pressure_cond("DiskPressure", p.disk, &now, since, ("KubeletHasNoDiskPressure", "kubelet has no disk pressure"), ("KubeletHasDiskPressure", "kubelet has disk pressure")),
        pressure_cond("PIDPressure", p.pid, &now, since, ("KubeletHasSufficientPID", "kubelet has sufficient PID available"), ("KubeletHasInsufficientPID", "kubelet has insufficient PID available"))
    ])
}

fn status(
    host: &HostInfo,
    node: &str,
    (ip, kport): (&str, u16),
    runtime: &str,
    ready: bool,
    since: &str,
    p: Pressure,
) -> Value {
    let mem = format!("{}Ki", host.mem_total_kib);
    let alloc = format!(
        "{}Ki",
        host.mem_total_kib.saturating_sub(MEM_AVAILABLE_MIN_KIB)
    );
    json!({
        "capacity": {"cpu": host.cpus.to_string(), "memory": mem, "pods": "110"},
        "allocatable": {"cpu": host.cpus.to_string(), "memory": alloc, "pods": "110"},
        "conditions": conditions(ready, since, p),
        "addresses": [{"type": "InternalIP", "address": ip}, {"type": "Hostname", "address": node}],
        "daemonEndpoints": {"kubeletEndpoint": {"Port": if kport == 0 { 10250 } else { kport }}},
        "nodeInfo": {
            "machineID": host.machine_id,
            "systemUUID": host.machine_id,
            "bootID": host.boot_id,
            "kernelVersion": host.kernel,
            "osImage": host.os_image,
            "containerRuntimeVersion": runtime,
            "kubeletVersion": VERSION,
            "kubeProxyVersion": VERSION,
            "operatingSystem": "linux",
            "architecture": host.arch
        }
    })
}

fn node_path(node: &str) -> String {
    format!("/api/v1/nodes/{node}")
}

fn lease_path(node: &str) -> String {
    format!("/apis/coordination.k8s.io/v1/namespaces/{LEASE_NS}/leases/{node}")
}

fn bad(what: &str, code: u16, body: &Value) -> io::Error {
    io::Error::other(format!("{what}: HTTP {code} {}", s(body, "/message")))
}

pub fn runtime_version(name: &str) -> String {
    format!("krab-{name}://{}", env!("CARGO_PKG_VERSION"))
}

pub async fn register(
    c: &Client,
    node: &str,
    ip: &str,
    kport: u16,
    runtime: &str,
) -> io::Result<Value> {
    let host = host_info();
    let now = now_rfc();
    let st = status(&host, node, (ip, kport), runtime, true, &now, pressure());
    let (code, existing) = c.get(&node_path(node)).await?;
    if code == 404 {
        let body = json!({
            "apiVersion": "v1",
            "kind": "Node",
            "metadata": {"name": node, "labels": {
                "kubernetes.io/hostname": node,
                "kubernetes.io/os": "linux",
                "kubernetes.io/arch": host.arch,
                "krab.io/agent": "true"
            }},
            "spec": {},
            "status": st
        });
        let (code, created) = c.post("/api/v1/nodes", &body).await?;
        if code != 201 && code != 200 && code != 409 {
            return Err(bad("create node", code, &created));
        }
    } else if code != 200 {
        return Err(bad("get node", code, &existing));
    }
    let (code, out) = c
        .patch(
            &format!("{}/status", node_path(node)),
            MERGE,
            &json!({"status": st}),
        )
        .await?;
    if code != 200 {
        return Err(bad("patch node status", code, &out));
    }
    Ok(out)
}

async fn renew_lease(c: &Client, node: &str, uid: &str) -> io::Result<()> {
    let renew = now_micro();
    let (code, out) = c
        .patch(
            &lease_path(node),
            "application/merge-patch+json",
            &json!({"spec": {"holderIdentity": node, "leaseDurationSeconds": 40, "renewTime": renew}}),
        )
        .await?;
    match code {
        200 => Ok(()),
        404 => {
            let body = json!({
                "apiVersion": "coordination.k8s.io/v1",
                "kind": "Lease",
                "metadata": {"name": node, "namespace": LEASE_NS,
                    "ownerReferences": [{"apiVersion": "v1", "kind": "Node", "name": node, "uid": uid}]},
                "spec": {"holderIdentity": node, "leaseDurationSeconds": 40, "renewTime": renew}
            });
            let (code, out) = c
                .post(
                    &format!("/apis/coordination.k8s.io/v1/namespaces/{LEASE_NS}/leases"),
                    &body,
                )
                .await?;
            if matches!(code, 200 | 201 | 409) {
                Ok(())
            } else {
                Err(bad("create lease", code, &out))
            }
        }
        _ => Err(bad("renew lease", code, &out)),
    }
}

pub async fn run<R: Runtime>(
    c: &Client,
    node: &str,
    ip: &str,
    kport: u16,
    rt: &R,
    mut node_obj: Value,
) {
    let host = host_info();
    let runtime = runtime_version(rt.name());
    let mut since = now_rfc();
    let mut last_ready = true;
    let mut last_pressure = Pressure::default();
    let mut tick = tokio::time::interval(HEARTBEAT);
    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    let mut n = 0u32;
    loop {
        tick.tick().await;
        let ready = tokio::time::timeout(Duration::from_secs(8), rt.list())
            .await
            .is_ok_and(|r| r.is_ok());
        let uid = s(&node_obj, "/metadata/uid").to_string();
        if let Err(e) = renew_lease(c, node, &uid).await {
            eprintln!("krab-agent: {e}");
        }
        n += 1;
        let pr = pressure();
        if ready != last_ready || pr != last_pressure || n >= STATUS_EVERY {
            if ready != last_ready || pr != last_pressure {
                since = now_rfc();
            }
            let st = status(&host, node, (ip, kport), &runtime, ready, &since, pr);
            match c
                .patch(
                    &format!("{}/status", node_path(node)),
                    MERGE,
                    &json!({"status": st}),
                )
                .await
            {
                Ok((200, out)) => {
                    node_obj = out;
                    last_ready = ready;
                    last_pressure = pr;
                    n = 0;
                }
                Ok((404, _)) => {
                    if let Ok(out) = register(c, node, ip, kport, &runtime).await {
                        node_obj = out;
                        last_ready = ready;
                        last_pressure = pr;
                        n = 0;
                    }
                }
                Ok((code, out)) => eprintln!("krab-agent: {}", bad("node status", code, &out)),
                Err(e) => eprintln!("krab-agent: node status: {e}"),
            }
        }
    }
}

#[cfg(test)]
mod pressure_tests {
    use super::*;

    #[test]
    fn thresholds_flip_exactly_at_the_limits() {
        let ok = pressure_from(
            MEM_AVAILABLE_MIN_KIB,
            Some(DISK_FREE_MIN_PERCENT),
            Some(PID_USED_MAX_PERCENT),
        );
        assert!(ok == Pressure::default());
        let p = pressure_from(
            MEM_AVAILABLE_MIN_KIB - 1,
            Some(DISK_FREE_MIN_PERCENT - 1),
            Some(PID_USED_MAX_PERCENT + 1),
        );
        assert!(p.memory && p.disk && p.pid);
        assert!(
            pressure_from(0, None, None)
                == Pressure {
                    memory: true,
                    disk: false,
                    pid: false
                }
        );
    }

    #[test]
    fn conditions_report_pressure_with_reasons() {
        let c = conditions(
            true,
            "t",
            Pressure {
                memory: true,
                disk: false,
                pid: false,
            },
        );
        let mem = c
            .as_array()
            .unwrap()
            .iter()
            .find(|x| x["type"] == "MemoryPressure")
            .unwrap();
        assert_eq!(mem["status"], "True");
        assert_eq!(mem["reason"], "KubeletHasInsufficientMemory");
        let disk = c
            .as_array()
            .unwrap()
            .iter()
            .find(|x| x["type"] == "DiskPressure")
            .unwrap();
        assert_eq!(disk["status"], "False");
    }
}