Skip to main content

krab_agent/
node.rs

1use crate::client::Client;
2use krab_controllers::util::{now_micro, now_rfc, s};
3use krab_runtime::Runtime;
4use krab_runtime::host::{HostInfo, disk_free_percent, host_info, meminfo, threads_used_percent};
5use serde_json::{Value, json};
6use std::io;
7use std::time::Duration;
8
9pub const LEASE_NS: &str = "kube-node-lease";
10pub const VERSION: &str = "v1.34.0-krab";
11const MERGE: &str = "application/strategic-merge-patch+json";
12const HEARTBEAT: Duration = Duration::from_secs(10);
13const STATUS_EVERY: u32 = 30;
14pub(crate) const MEM_AVAILABLE_MIN_KIB: u64 = 100 * 1024;
15const DISK_FREE_MIN_PERCENT: u64 = 10;
16const PID_USED_MAX_PERCENT: u64 = 90;
17
18#[derive(Clone, Copy, Default, PartialEq, Eq)]
19struct Pressure {
20    memory: bool,
21    disk: bool,
22    pid: bool,
23}
24
25fn pressure_from(mem_avail_kib: u64, disk_free: Option<u64>, pid_used: Option<u64>) -> Pressure {
26    Pressure {
27        memory: mem_avail_kib < MEM_AVAILABLE_MIN_KIB,
28        disk: disk_free.is_some_and(|f| f < DISK_FREE_MIN_PERCENT),
29        pid: pid_used.is_some_and(|u| u > PID_USED_MAX_PERCENT),
30    }
31}
32
33fn pressure() -> Pressure {
34    pressure_from(
35        meminfo().1,
36        ["/var/lib", "/"].iter().find_map(|p| disk_free_percent(p)),
37        threads_used_percent(),
38    )
39}
40
41fn pressure_cond(
42    kind: &str,
43    on: bool,
44    now: &str,
45    since: &str,
46    good: (&str, &str),
47    bad: (&str, &str),
48) -> Value {
49    let (reason, msg) = if on { bad } else { good };
50    json!({"type": kind, "status": if on { "True" } else { "False" }, "lastHeartbeatTime": now, "lastTransitionTime": since, "reason": reason, "message": msg})
51}
52
53fn conditions(ready: bool, since: &str, p: Pressure) -> Value {
54    let now = now_rfc();
55    let (st, reason, msg) = if ready {
56        ("True", "KubeletReady", "krab agent is posting ready status")
57    } else {
58        (
59            "False",
60            "KubeletNotReady",
61            "container runtime is unreachable",
62        )
63    };
64    json!([
65        {"type": "Ready", "status": st, "lastHeartbeatTime": now, "lastTransitionTime": since, "reason": reason, "message": msg},
66        pressure_cond("MemoryPressure", p.memory, &now, since, ("KubeletHasSufficientMemory", "kubelet has sufficient memory available"), ("KubeletHasInsufficientMemory", "kubelet has insufficient memory available")),
67        pressure_cond("DiskPressure", p.disk, &now, since, ("KubeletHasNoDiskPressure", "kubelet has no disk pressure"), ("KubeletHasDiskPressure", "kubelet has disk pressure")),
68        pressure_cond("PIDPressure", p.pid, &now, since, ("KubeletHasSufficientPID", "kubelet has sufficient PID available"), ("KubeletHasInsufficientPID", "kubelet has insufficient PID available"))
69    ])
70}
71
72fn status(
73    host: &HostInfo,
74    node: &str,
75    (ip, kport): (&str, u16),
76    runtime: &str,
77    ready: bool,
78    since: &str,
79    p: Pressure,
80) -> Value {
81    let mem = format!("{}Ki", host.mem_total_kib);
82    let alloc = format!(
83        "{}Ki",
84        host.mem_total_kib.saturating_sub(MEM_AVAILABLE_MIN_KIB)
85    );
86    json!({
87        "capacity": {"cpu": host.cpus.to_string(), "memory": mem, "pods": "110"},
88        "allocatable": {"cpu": host.cpus.to_string(), "memory": alloc, "pods": "110"},
89        "conditions": conditions(ready, since, p),
90        "addresses": [{"type": "InternalIP", "address": ip}, {"type": "Hostname", "address": node}],
91        "daemonEndpoints": {"kubeletEndpoint": {"Port": if kport == 0 { 10250 } else { kport }}},
92        "nodeInfo": {
93            "machineID": host.machine_id,
94            "systemUUID": host.machine_id,
95            "bootID": host.boot_id,
96            "kernelVersion": host.kernel,
97            "osImage": host.os_image,
98            "containerRuntimeVersion": runtime,
99            "kubeletVersion": VERSION,
100            "kubeProxyVersion": VERSION,
101            "operatingSystem": "linux",
102            "architecture": host.arch
103        }
104    })
105}
106
107fn node_path(node: &str) -> String {
108    format!("/api/v1/nodes/{node}")
109}
110
111fn lease_path(node: &str) -> String {
112    format!("/apis/coordination.k8s.io/v1/namespaces/{LEASE_NS}/leases/{node}")
113}
114
115fn bad(what: &str, code: u16, body: &Value) -> io::Error {
116    io::Error::other(format!("{what}: HTTP {code} {}", s(body, "/message")))
117}
118
119pub fn runtime_version(name: &str) -> String {
120    format!("krab-{name}://{}", env!("CARGO_PKG_VERSION"))
121}
122
123pub async fn register(
124    c: &Client,
125    node: &str,
126    ip: &str,
127    kport: u16,
128    runtime: &str,
129) -> io::Result<Value> {
130    let host = host_info();
131    let now = now_rfc();
132    let st = status(&host, node, (ip, kport), runtime, true, &now, pressure());
133    let (code, existing) = c.get(&node_path(node)).await?;
134    if code == 404 {
135        let body = json!({
136            "apiVersion": "v1",
137            "kind": "Node",
138            "metadata": {"name": node, "labels": {
139                "kubernetes.io/hostname": node,
140                "kubernetes.io/os": "linux",
141                "kubernetes.io/arch": host.arch,
142                "krab.io/agent": "true"
143            }},
144            "spec": {},
145            "status": st
146        });
147        let (code, created) = c.post("/api/v1/nodes", &body).await?;
148        if code != 201 && code != 200 && code != 409 {
149            return Err(bad("create node", code, &created));
150        }
151    } else if code != 200 {
152        return Err(bad("get node", code, &existing));
153    }
154    let (code, out) = c
155        .patch(
156            &format!("{}/status", node_path(node)),
157            MERGE,
158            &json!({"status": st}),
159        )
160        .await?;
161    if code != 200 {
162        return Err(bad("patch node status", code, &out));
163    }
164    Ok(out)
165}
166
167async fn renew_lease(c: &Client, node: &str, uid: &str) -> io::Result<()> {
168    let renew = now_micro();
169    let (code, out) = c
170        .patch(
171            &lease_path(node),
172            "application/merge-patch+json",
173            &json!({"spec": {"holderIdentity": node, "leaseDurationSeconds": 40, "renewTime": renew}}),
174        )
175        .await?;
176    match code {
177        200 => Ok(()),
178        404 => {
179            let body = json!({
180                "apiVersion": "coordination.k8s.io/v1",
181                "kind": "Lease",
182                "metadata": {"name": node, "namespace": LEASE_NS,
183                    "ownerReferences": [{"apiVersion": "v1", "kind": "Node", "name": node, "uid": uid}]},
184                "spec": {"holderIdentity": node, "leaseDurationSeconds": 40, "renewTime": renew}
185            });
186            let (code, out) = c
187                .post(
188                    &format!("/apis/coordination.k8s.io/v1/namespaces/{LEASE_NS}/leases"),
189                    &body,
190                )
191                .await?;
192            if matches!(code, 200 | 201 | 409) {
193                Ok(())
194            } else {
195                Err(bad("create lease", code, &out))
196            }
197        }
198        _ => Err(bad("renew lease", code, &out)),
199    }
200}
201
202pub async fn run<R: Runtime>(
203    c: &Client,
204    node: &str,
205    ip: &str,
206    kport: u16,
207    rt: &R,
208    mut node_obj: Value,
209) {
210    let host = host_info();
211    let runtime = runtime_version(rt.name());
212    let mut since = now_rfc();
213    let mut last_ready = true;
214    let mut last_pressure = Pressure::default();
215    let mut tick = tokio::time::interval(HEARTBEAT);
216    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
217    let mut n = 0u32;
218    loop {
219        tick.tick().await;
220        let ready = tokio::time::timeout(Duration::from_secs(8), rt.list())
221            .await
222            .is_ok_and(|r| r.is_ok());
223        let uid = s(&node_obj, "/metadata/uid").to_string();
224        if let Err(e) = renew_lease(c, node, &uid).await {
225            eprintln!("krab-agent: {e}");
226        }
227        n += 1;
228        let pr = pressure();
229        if ready != last_ready || pr != last_pressure || n >= STATUS_EVERY {
230            if ready != last_ready || pr != last_pressure {
231                since = now_rfc();
232            }
233            let st = status(&host, node, (ip, kport), &runtime, ready, &since, pr);
234            match c
235                .patch(
236                    &format!("{}/status", node_path(node)),
237                    MERGE,
238                    &json!({"status": st}),
239                )
240                .await
241            {
242                Ok((200, out)) => {
243                    node_obj = out;
244                    last_ready = ready;
245                    last_pressure = pr;
246                    n = 0;
247                }
248                Ok((404, _)) => {
249                    if let Ok(out) = register(c, node, ip, kport, &runtime).await {
250                        node_obj = out;
251                        last_ready = ready;
252                        last_pressure = pr;
253                        n = 0;
254                    }
255                }
256                Ok((code, out)) => eprintln!("krab-agent: {}", bad("node status", code, &out)),
257                Err(e) => eprintln!("krab-agent: node status: {e}"),
258            }
259        }
260    }
261}
262
263#[cfg(test)]
264mod pressure_tests {
265    use super::*;
266
267    #[test]
268    fn thresholds_flip_exactly_at_the_limits() {
269        let ok = pressure_from(
270            MEM_AVAILABLE_MIN_KIB,
271            Some(DISK_FREE_MIN_PERCENT),
272            Some(PID_USED_MAX_PERCENT),
273        );
274        assert!(ok == Pressure::default());
275        let p = pressure_from(
276            MEM_AVAILABLE_MIN_KIB - 1,
277            Some(DISK_FREE_MIN_PERCENT - 1),
278            Some(PID_USED_MAX_PERCENT + 1),
279        );
280        assert!(p.memory && p.disk && p.pid);
281        assert!(
282            pressure_from(0, None, None)
283                == Pressure {
284                    memory: true,
285                    disk: false,
286                    pid: false
287                }
288        );
289    }
290
291    #[test]
292    fn conditions_report_pressure_with_reasons() {
293        let c = conditions(
294            true,
295            "t",
296            Pressure {
297                memory: true,
298                disk: false,
299                pid: false,
300            },
301        );
302        let mem = c
303            .as_array()
304            .unwrap()
305            .iter()
306            .find(|x| x["type"] == "MemoryPressure")
307            .unwrap();
308        assert_eq!(mem["status"], "True");
309        assert_eq!(mem["reason"], "KubeletHasInsufficientMemory");
310        let disk = c
311            .as_array()
312            .unwrap()
313            .iter()
314            .find(|x| x["type"] == "DiskPressure")
315            .unwrap();
316        assert_eq!(disk["status"], "False");
317    }
318}