krab-agent 0.2.1

Lightweight kubelet for a real Kubernetes control plane (krab agent)
Documentation
pub mod client;
pub mod evict;
pub mod join;
pub mod kubelet_api;
pub mod mirror;
pub mod node;
pub mod projected;
pub mod push;
pub mod services;
pub mod watcher;
pub mod wg;
pub mod yaml;

use client::Client;
use krab_controllers::kubelet::{self, Config};
use krab_controllers::util::{self, Recorder};
use krab_runtime::Runtime;
use krab_store::MemStore;
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

pub struct WireGuard {
    pub cluster_subnet: krab_runtime::native::net::Subnet,
    pub local_subnet: krab_runtime::native::net::Subnet,
    pub iface: String,
    pub port: u16,
    pub endpoint: Option<String>,
}

pub struct Cluster {
    pub wireguard: Option<WireGuard>,
    pub service_proxy: bool,
    pub dns: Option<(std::net::Ipv4Addr, String)>,
}

pub struct Options {
    pub kubeconfig: PathBuf,
    pub node_name: String,
    pub node_ip: Option<String>,
    pub volume_root: Option<PathBuf>,
    pub network: Option<String>,
    pub allow_host_paths: Vec<PathBuf>,
    pub kubelet_bind: Option<SocketAddr>,
    pub serving_dir: PathBuf,
    pub client_ca: Option<PathBuf>,
    pub cluster: Option<Cluster>,
    pub rotate_dir: Option<PathBuf>,
}

fn detect_ip(server: &str) -> Option<String> {
    let addr = server.to_socket_addrs().ok()?.next()?;
    let sock = UdpSocket::bind(if addr.is_ipv6() {
        "[::]:0"
    } else {
        "0.0.0.0:0"
    })
    .ok()?;
    sock.connect(addr).ok()?;
    Some(sock.local_addr().ok()?.ip().to_string())
}

const IMAGE_GC_LOW: u64 = 15;
const IMAGE_GC_HIGH: u64 = 25;

pub async fn wait_pod_cidr(
    kubeconfig: &std::path::Path,
    node_name: &str,
    node_ip: Option<String>,
    runtime: &str,
) -> Result<String, String> {
    let client = Client::from_kubeconfig(kubeconfig)?;
    let ip = node_ip
        .or_else(|| detect_ip(&client.authority()))
        .ok_or("cannot detect node ip, pass --node-ip")?;
    for _ in 0..60 {
        match node::register(&client, node_name, &ip, 0, &node::runtime_version(runtime)).await {
            Ok(n) => {
                let cidr = n["spec"]["podCIDR"].as_str().unwrap_or("");
                if !cidr.is_empty() {
                    return Ok(cidr.to_string());
                }
            }
            Err(e) => eprintln!("krab-agent: register: {e}"),
        }
        tokio::time::sleep(Duration::from_secs(2)).await;
    }
    Err("node has no spec.podCIDR (kube-controller-manager needs --allocate-node-cidrs)".into())
}

pub async fn run<R: Runtime + Clone>(opts: Options, rt: Arc<R>) -> Result<(), String> {
    let client = Arc::new(Client::from_kubeconfig(&opts.kubeconfig)?);
    let ip = opts
        .node_ip
        .clone()
        .or_else(|| detect_ip(&client.authority()))
        .ok_or("cannot detect node ip, pass --node-ip")?;
    let kport = opts.kubelet_bind.map_or(0, |a| a.port());
    let node_obj = loop {
        match node::register(
            &client,
            &opts.node_name,
            &ip,
            kport,
            &node::runtime_version(rt.name()),
        )
        .await
        {
            Ok(n) => break n,
            Err(e) => {
                eprintln!("krab-agent: register: {e}");
                tokio::time::sleep(Duration::from_secs(3)).await;
            }
        }
    };
    let store = MemStore::new(4 << 20, 1024);
    util::create(
        &store,
        &format!("nodes/{}", opts.node_name),
        node_obj.clone(),
    );
    let mut cfg = Config::new(opts.node_name.clone());
    if let Some(v) = opts.volume_root {
        cfg.volume_root = v;
    }
    if let Some(n) = opts.network {
        cfg.network = n;
    }
    cfg.allow_host_paths = opts.allow_host_paths;
    let rec = Arc::new(Recorder::new("kubelet"));
    let mut tasks = tokio::task::JoinSet::new();
    let proj = projected::Projector::new(client.clone(), cfg.volume_root.clone());
    tasks.spawn(proj.clone().refresh_loop(store.clone()));
    tasks.spawn(mirror::run(
        client.clone(),
        store.clone(),
        proj,
        opts.node_name.clone(),
    ));
    tasks.spawn(push::run(
        client.clone(),
        store.clone(),
        opts.node_name.clone(),
    ));
    tasks.spawn(kubelet::run(store.clone(), rt.clone(), rec, cfg));
    tasks.spawn(evict::run(store.clone(), opts.node_name.clone()));
    if let Some(dir) = opts.rotate_dir.clone() {
        tasks.spawn(join::rotate_loop(
            opts.kubeconfig.clone(),
            opts.node_name.clone(),
            dir,
        ));
    }
    if let Some(cl) = &opts.cluster {
        if let Some(w) = &cl.wireguard {
            let o = wg::Opts {
                cluster_subnet: w.cluster_subnet,
                local_subnet: w.local_subnet,
                iface: w.iface.clone(),
                port: w.port,
                endpoint: w.endpoint.clone(),
                dir: opts.serving_dir.clone(),
                node: opts.node_name.clone(),
                node_ip: ip.clone(),
            };
            let c = client.clone();
            tasks.spawn(async move {
                if let Err(e) = wg::run(c, o).await {
                    eprintln!("krab-agent: {e}");
                }
            });
        }
        tasks.spawn(services::run(
            client.clone(),
            store.clone(),
            services::Opts {
                proxy: cl.service_proxy,
                dns: cl.dns.clone(),
            },
        ));
    }
    if let Some(bind) = opts.kubelet_bind {
        let app = krab_api::App::new(krab_api::Config::default(), (*rt).clone(), store.clone());
        let kopts = kubelet_api::Opts {
            bind,
            serving_dir: opts.serving_dir.clone(),
            client_ca: opts.client_ca.clone(),
            node_name: opts.node_name.clone(),
            node_ip: ip.clone(),
        };
        let (rt, store, client) = ((*rt).clone(), store.clone(), client.clone());
        tasks.spawn(async move {
            if let Err(e) = kubelet_api::run(app, rt, store, client, kopts).await {
                eprintln!("krab-agent: kubelet api: {e}");
            }
        });
    }
    {
        let (c, rt, name) = (client.clone(), rt.clone(), opts.node_name.clone());
        tasks.spawn(async move { node::run(&c, &name, &ip, kport, &*rt, node_obj).await });
    }
    {
        let rt = rt.clone();
        tasks.spawn(async move {
            let mut tick = tokio::time::interval(std::time::Duration::from_secs(300));
            loop {
                tick.tick().await;
                match rt.gc_images(IMAGE_GC_LOW, IMAGE_GC_HIGH).await {
                    Ok(0) => {}
                    Ok(n) => eprintln!("krab-agent: removed {n} unused images"),
                    Err(e) => eprintln!("krab-agent: image gc: {e}"),
                }
            }
        });
    }
    let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
        .map_err(|e| e.to_string())?;
    let res = tokio::select! {
        _ = tokio::signal::ctrl_c() => Ok(()),
        _ = sigterm.recv() => Ok(()),
        done = tasks.join_next() => Err(match done {
            Some(Err(e)) => format!("task failed: {e}"),
            _ => "task exited unexpectedly".to_string(),
        }),
    };
    tasks.abort_all();
    if let Some(cl) = &opts.cluster {
        if let Some(w) = &cl.wireguard {
            wg::teardown(&w.iface).await;
        }
        if cl.service_proxy {
            services::teardown().await;
        }
    }
    rt.shutdown().await;
    res
}