Skip to main content

krab_agent/
lib.rs

1pub mod client;
2pub mod evict;
3pub mod join;
4pub mod kubelet_api;
5pub mod mirror;
6pub mod node;
7pub mod projected;
8pub mod push;
9pub mod services;
10pub mod watcher;
11pub mod wg;
12pub mod yaml;
13
14use client::Client;
15use krab_controllers::kubelet::{self, Config};
16use krab_controllers::util::{self, Recorder};
17use krab_runtime::Runtime;
18use krab_store::MemStore;
19use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
20use std::path::PathBuf;
21use std::sync::Arc;
22use std::time::Duration;
23
24pub struct WireGuard {
25    pub cluster_subnet: krab_runtime::native::net::Subnet,
26    pub local_subnet: krab_runtime::native::net::Subnet,
27    pub iface: String,
28    pub port: u16,
29    pub endpoint: Option<String>,
30}
31
32pub struct Cluster {
33    pub wireguard: Option<WireGuard>,
34    pub service_proxy: bool,
35    pub dns: Option<(std::net::Ipv4Addr, String)>,
36}
37
38pub struct Options {
39    pub kubeconfig: PathBuf,
40    pub node_name: String,
41    pub node_ip: Option<String>,
42    pub volume_root: Option<PathBuf>,
43    pub network: Option<String>,
44    pub allow_host_paths: Vec<PathBuf>,
45    pub kubelet_bind: Option<SocketAddr>,
46    pub serving_dir: PathBuf,
47    pub client_ca: Option<PathBuf>,
48    pub cluster: Option<Cluster>,
49    pub rotate_dir: Option<PathBuf>,
50}
51
52fn detect_ip(server: &str) -> Option<String> {
53    let addr = server.to_socket_addrs().ok()?.next()?;
54    let sock = UdpSocket::bind(if addr.is_ipv6() {
55        "[::]:0"
56    } else {
57        "0.0.0.0:0"
58    })
59    .ok()?;
60    sock.connect(addr).ok()?;
61    Some(sock.local_addr().ok()?.ip().to_string())
62}
63
64const IMAGE_GC_LOW: u64 = 15;
65const IMAGE_GC_HIGH: u64 = 25;
66
67pub async fn wait_pod_cidr(
68    kubeconfig: &std::path::Path,
69    node_name: &str,
70    node_ip: Option<String>,
71    runtime: &str,
72) -> Result<String, String> {
73    let client = Client::from_kubeconfig(kubeconfig)?;
74    let ip = node_ip
75        .or_else(|| detect_ip(&client.authority()))
76        .ok_or("cannot detect node ip, pass --node-ip")?;
77    for _ in 0..60 {
78        match node::register(&client, node_name, &ip, 0, &node::runtime_version(runtime)).await {
79            Ok(n) => {
80                let cidr = n["spec"]["podCIDR"].as_str().unwrap_or("");
81                if !cidr.is_empty() {
82                    return Ok(cidr.to_string());
83                }
84            }
85            Err(e) => eprintln!("krab-agent: register: {e}"),
86        }
87        tokio::time::sleep(Duration::from_secs(2)).await;
88    }
89    Err("node has no spec.podCIDR (kube-controller-manager needs --allocate-node-cidrs)".into())
90}
91
92pub async fn run<R: Runtime + Clone>(opts: Options, rt: Arc<R>) -> Result<(), String> {
93    let client = Arc::new(Client::from_kubeconfig(&opts.kubeconfig)?);
94    let ip = opts
95        .node_ip
96        .clone()
97        .or_else(|| detect_ip(&client.authority()))
98        .ok_or("cannot detect node ip, pass --node-ip")?;
99    let kport = opts.kubelet_bind.map_or(0, |a| a.port());
100    let node_obj = loop {
101        match node::register(
102            &client,
103            &opts.node_name,
104            &ip,
105            kport,
106            &node::runtime_version(rt.name()),
107        )
108        .await
109        {
110            Ok(n) => break n,
111            Err(e) => {
112                eprintln!("krab-agent: register: {e}");
113                tokio::time::sleep(Duration::from_secs(3)).await;
114            }
115        }
116    };
117    let store = MemStore::new(64 << 10, 1024);
118    util::create(
119        &store,
120        &format!("nodes/{}", opts.node_name),
121        node_obj.clone(),
122    );
123    let mut cfg = Config::new(opts.node_name.clone());
124    if let Some(v) = opts.volume_root {
125        cfg.volume_root = v;
126    }
127    if let Some(n) = opts.network {
128        cfg.network = n;
129    }
130    cfg.allow_host_paths = opts.allow_host_paths;
131    let rec = Arc::new(Recorder::new("kubelet"));
132    let mut tasks = tokio::task::JoinSet::new();
133    let proj = projected::Projector::new(client.clone(), cfg.volume_root.clone());
134    tasks.spawn(proj.clone().refresh_loop(store.clone()));
135    tasks.spawn(mirror::run(
136        client.clone(),
137        store.clone(),
138        proj,
139        opts.node_name.clone(),
140    ));
141    tasks.spawn(push::run(
142        client.clone(),
143        store.clone(),
144        opts.node_name.clone(),
145    ));
146    tasks.spawn(kubelet::run(store.clone(), rt.clone(), rec, cfg));
147    tasks.spawn(evict::run(store.clone(), opts.node_name.clone()));
148    if let Some(dir) = opts.rotate_dir.clone() {
149        tasks.spawn(join::rotate_loop(
150            opts.kubeconfig.clone(),
151            opts.node_name.clone(),
152            dir,
153        ));
154    }
155    if let Some(cl) = &opts.cluster {
156        if let Some(w) = &cl.wireguard {
157            let o = wg::Opts {
158                cluster_subnet: w.cluster_subnet,
159                local_subnet: w.local_subnet,
160                iface: w.iface.clone(),
161                port: w.port,
162                endpoint: w.endpoint.clone(),
163                dir: opts.serving_dir.clone(),
164                node: opts.node_name.clone(),
165                node_ip: ip.clone(),
166            };
167            let c = client.clone();
168            tasks.spawn(async move {
169                if let Err(e) = wg::run(c, o).await {
170                    eprintln!("krab-agent: {e}");
171                }
172            });
173        }
174        tasks.spawn(services::run(
175            client.clone(),
176            store.clone(),
177            services::Opts {
178                proxy: cl.service_proxy,
179                dns: cl.dns.clone(),
180            },
181        ));
182    }
183    if let Some(bind) = opts.kubelet_bind {
184        let app = krab_api::App::new(krab_api::Config::default(), (*rt).clone(), store.clone());
185        let kopts = kubelet_api::Opts {
186            bind,
187            serving_dir: opts.serving_dir.clone(),
188            client_ca: opts.client_ca.clone(),
189            node_name: opts.node_name.clone(),
190            node_ip: ip.clone(),
191        };
192        let (rt, store, client) = ((*rt).clone(), store.clone(), client.clone());
193        tasks.spawn(async move {
194            if let Err(e) = kubelet_api::run(app, rt, store, client, kopts).await {
195                eprintln!("krab-agent: kubelet api: {e}");
196            }
197        });
198    }
199    {
200        let (c, rt, name) = (client.clone(), rt.clone(), opts.node_name.clone());
201        tasks.spawn(async move { node::run(&c, &name, &ip, kport, &*rt, node_obj).await });
202    }
203    {
204        let rt = rt.clone();
205        tasks.spawn(async move {
206            let mut tick = tokio::time::interval(std::time::Duration::from_secs(300));
207            loop {
208                tick.tick().await;
209                match rt.gc_images(IMAGE_GC_LOW, IMAGE_GC_HIGH).await {
210                    Ok(0) => {}
211                    Ok(n) => eprintln!("krab-agent: removed {n} unused images"),
212                    Err(e) => eprintln!("krab-agent: image gc: {e}"),
213                }
214            }
215        });
216    }
217    let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
218        .map_err(|e| e.to_string())?;
219    let res = tokio::select! {
220        _ = tokio::signal::ctrl_c() => Ok(()),
221        _ = sigterm.recv() => Ok(()),
222        done = tasks.join_next() => Err(match done {
223            Some(Err(e)) => format!("task failed: {e}"),
224            _ => "task exited unexpectedly".to_string(),
225        }),
226    };
227    tasks.abort_all();
228    if let Some(cl) = &opts.cluster {
229        if let Some(w) = &cl.wireguard {
230            wg::teardown(&w.iface).await;
231        }
232        if cl.service_proxy {
233            services::teardown().await;
234        }
235    }
236    rt.shutdown().await;
237    res
238}