krab-api 0.2.2

Kubernetes-compatible API server for krabkube
Documentation
use crate::util::{rfc3339, uid_from};
use bytes::Bytes;
use krab_runtime::ContainerInfo;
use krab_runtime::host::{HostInfo, sanitize};
use serde_json::{Value, json};

pub const VERSION: &str = "v1.34.0+krab";

pub fn namespace_of(c: &ContainerInfo) -> String {
    c.labels
        .get("io.kubernetes.pod.namespace")
        .or_else(|| c.labels.get("com.docker.compose.project"))
        .map(|s| sanitize(s))
        .unwrap_or_else(|| "default".into())
}

pub fn pod_name_of(c: &ContainerInfo) -> String {
    sanitize(&c.name)
}

fn real_time(s: &str) -> Option<&str> {
    if s.is_empty() || s.starts_with("0001-") {
        None
    } else {
        Some(s)
    }
}

pub fn container_state(c: &ContainerInfo) -> Value {
    match c.state.as_str() {
        "running" | "paused" => json!({"running": {"startedAt": real_time(&c.started_at)}}),
        "created" => json!({"waiting": {"reason": "ContainerCreating"}}),
        "restarting" => {
            json!({"waiting": {"reason": "CrashLoopBackOff", "message": "container is restarting"}})
        }
        _ => {
            let reason = if c.exit_code == 0 {
                "Completed"
            } else {
                "Error"
            };
            json!({"terminated": {"exitCode": c.exit_code, "reason": reason, "startedAt": real_time(&c.started_at), "finishedAt": real_time(&c.finished_at), "containerID": format!("docker://{}", c.id)}})
        }
    }
}

pub fn pod_phase(c: &ContainerInfo) -> &'static str {
    match c.state.as_str() {
        "running" | "paused" | "restarting" => "Running",
        "created" => "Pending",
        _ if c.exit_code == 0 => "Succeeded",
        _ => "Failed",
    }
}

pub fn pod(c: &ContainerInfo, rev: u64, host: &HostInfo, host_ip: &str) -> Bytes {
    let ns = namespace_of(c);
    let name = pod_name_of(c);
    let ready = c.state == "running";
    let created = rfc3339(c.created);
    let ports: Vec<Value> = c
        .ports
        .iter()
        .map(|(p, proto)| json!({"containerPort": p, "protocol": proto.to_uppercase()}))
        .collect();
    let mut conditions =
        vec![json!({"type": "PodScheduled", "status": "True", "lastTransitionTime": created})];
    if ready {
        conditions.push(json!({"type": "Ready", "status": "True", "lastTransitionTime": created}));
        conditions.push(
            json!({"type": "ContainersReady", "status": "True", "lastTransitionTime": created}),
        );
    } else {
        conditions.push(json!({"type": "Ready", "status": "False", "lastTransitionTime": created}));
    }
    let mut labels = serde_json::Map::new();
    for (k, v) in &c.labels {
        if k.len() <= 63 && v.len() <= 63 && !v.is_empty() {
            labels.insert(k.clone(), Value::String(v.clone()));
        }
    }
    let mut status = json!({
        "phase": pod_phase(c),
        "conditions": conditions,
        "hostIP": host_ip,
        "containerStatuses": [{
            "name": name,
            "state": container_state(c),
            "ready": ready,
            "restartCount": c.restart_count,
            "image": c.image,
            "imageID": c.image_id,
            "containerID": format!("docker://{}", c.id),
            "started": ready
        }]
    });
    if !c.ip.is_empty() {
        status["podIP"] = json!(c.ip);
        status["podIPs"] = json!([{"ip": c.ip}]);
    }
    if let Some(t) = real_time(&c.started_at) {
        status["startTime"] = json!(t);
    }
    let o = json!({
        "apiVersion": "v1",
        "kind": "Pod",
        "metadata": {
            "name": name,
            "namespace": ns,
            "uid": uid_from(&c.id),
            "resourceVersion": rev.to_string(),
            "creationTimestamp": created,
            "labels": labels,
            "annotations": {"krab.io/source": "docker", "krab.io/container-id": c.id, "krab.io/tty": c.tty.to_string()}
        },
        "spec": {
            "nodeName": host.hostname,
            "restartPolicy": "Always",
            "containers": [{"name": name, "image": c.image, "ports": ports, "resources": {}, "imagePullPolicy": "IfNotPresent"}]
        },
        "status": status
    });
    Bytes::from(serde_json::to_vec(&o).unwrap())
}

pub fn namespace(name: &str, rev: u64, created: i64, docker: bool) -> Bytes {
    let mut o = json!({
        "apiVersion": "v1",
        "kind": "Namespace",
        "metadata": {
            "name": name,
            "uid": uid_from(&format!("ns{name}")),
            "resourceVersion": rev.to_string(),
            "creationTimestamp": rfc3339(created),
            "labels": {"kubernetes.io/metadata.name": name}
        },
        "spec": {"finalizers": ["kubernetes"]},
        "status": {"phase": "Active"}
    });
    if docker {
        o["metadata"]["annotations"] = json!({"krab.io/source": "docker"});
    }
    Bytes::from(serde_json::to_vec(&o).unwrap())
}

pub fn node(
    host: &HostInfo,
    rev: u64,
    created: i64,
    ready: bool,
    ip: &str,
    runtime_version: &str,
) -> Bytes {
    let mem = format!("{}Ki", host.mem_total_kib);
    let now = rfc3339(crate::util::now_secs());
    let o = json!({
        "apiVersion": "v1",
        "kind": "Node",
        "metadata": {
            "name": host.hostname,
            "uid": uid_from(&format!("node{}", host.machine_id)),
            "resourceVersion": rev.to_string(),
            "creationTimestamp": rfc3339(created),
            "labels": {
                "kubernetes.io/hostname": host.hostname,
                "kubernetes.io/os": "linux",
                "kubernetes.io/arch": host.arch,
                "node-role.kubernetes.io/control-plane": "",
                "node-role.kubernetes.io/worker": ""
            }
        },
        "spec": {},
        "status": {
            "capacity": {"cpu": host.cpus.to_string(), "memory": mem, "pods": "110"},
            "allocatable": {"cpu": host.cpus.to_string(), "memory": mem, "pods": "110"},
            "conditions": [
                {"type": "Ready", "status": if ready {"True"} else {"False"}, "lastHeartbeatTime": now, "lastTransitionTime": now, "reason": if ready {"KubeletReady"} else {"RuntimeUnreachable"}, "message": if ready {"krab is posting ready status"} else {"container runtime is unreachable"}},
                {"type": "MemoryPressure", "status": "False", "lastHeartbeatTime": now, "lastTransitionTime": now, "reason": "KubeletHasSufficientMemory"},
                {"type": "DiskPressure", "status": "False", "lastHeartbeatTime": now, "lastTransitionTime": now, "reason": "KubeletHasNoDiskPressure"},
                {"type": "PIDPressure", "status": "False", "lastHeartbeatTime": now, "lastTransitionTime": now, "reason": "KubeletHasSufficientPID"}
            ],
            "addresses": [{"type": "InternalIP", "address": ip}, {"type": "Hostname", "address": host.hostname}],
            "nodeInfo": {
                "machineID": host.machine_id,
                "systemUUID": host.machine_id,
                "bootID": host.boot_id,
                "kernelVersion": host.kernel,
                "osImage": host.os_image,
                "containerRuntimeVersion": runtime_version,
                "kubeletVersion": VERSION,
                "kubeProxyVersion": VERSION,
                "operatingSystem": "linux",
                "architecture": host.arch
            }
        }
    });
    Bytes::from(serde_json::to_vec(&o).unwrap())
}

#[allow(clippy::too_many_arguments)]
pub fn event(
    rev: u64,
    ns: &str,
    pod: &str,
    pod_uid: &str,
    reason: &str,
    message: &str,
    warning: bool,
    now: i64,
) -> (String, Bytes) {
    let name = format!("{pod}.{rev:x}");
    let ts = rfc3339(now);
    let o = json!({
        "apiVersion": "v1",
        "kind": "Event",
        "metadata": {"name": name, "namespace": ns, "uid": uid_from(&format!("ev{name}")), "resourceVersion": rev.to_string(), "creationTimestamp": ts},
        "involvedObject": {"kind": "Pod", "namespace": ns, "name": pod, "uid": pod_uid, "apiVersion": "v1"},
        "reason": reason,
        "message": message,
        "type": if warning {"Warning"} else {"Normal"},
        "source": {"component": "krab"},
        "firstTimestamp": ts,
        "lastTimestamp": ts,
        "count": 1,
        "reportingComponent": "krab",
        "reportingInstance": "krab"
    });
    (name, Bytes::from(serde_json::to_vec(&o).unwrap()))
}