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() -> Pressure {
26 Pressure {
27 memory: meminfo().1 < MEM_AVAILABLE_MIN_KIB,
28 disk: ["/var/lib", "/"]
29 .iter()
30 .find_map(|p| disk_free_percent(p))
31 .is_some_and(|f| f < DISK_FREE_MIN_PERCENT),
32 pid: threads_used_percent().is_some_and(|u| u > PID_USED_MAX_PERCENT),
33 }
34}
35
36fn pressure_cond(
37 kind: &str,
38 on: bool,
39 now: &str,
40 since: &str,
41 good: (&str, &str),
42 bad: (&str, &str),
43) -> Value {
44 let (reason, msg) = if on { bad } else { good };
45 json!({"type": kind, "status": if on { "True" } else { "False" }, "lastHeartbeatTime": now, "lastTransitionTime": since, "reason": reason, "message": msg})
46}
47
48fn conditions(ready: bool, since: &str, p: Pressure) -> Value {
49 let now = now_rfc();
50 let (st, reason, msg) = if ready {
51 ("True", "KubeletReady", "krab agent is posting ready status")
52 } else {
53 (
54 "False",
55 "KubeletNotReady",
56 "container runtime is unreachable",
57 )
58 };
59 json!([
60 {"type": "Ready", "status": st, "lastHeartbeatTime": now, "lastTransitionTime": since, "reason": reason, "message": msg},
61 pressure_cond("MemoryPressure", p.memory, &now, since, ("KubeletHasSufficientMemory", "kubelet has sufficient memory available"), ("KubeletHasInsufficientMemory", "kubelet has insufficient memory available")),
62 pressure_cond("DiskPressure", p.disk, &now, since, ("KubeletHasNoDiskPressure", "kubelet has no disk pressure"), ("KubeletHasDiskPressure", "kubelet has disk pressure")),
63 pressure_cond("PIDPressure", p.pid, &now, since, ("KubeletHasSufficientPID", "kubelet has sufficient PID available"), ("KubeletHasInsufficientPID", "kubelet has insufficient PID available"))
64 ])
65}
66
67fn status(
68 host: &HostInfo,
69 node: &str,
70 (ip, kport): (&str, u16),
71 runtime: &str,
72 ready: bool,
73 since: &str,
74 p: Pressure,
75) -> Value {
76 let mem = format!("{}Ki", host.mem_total_kib);
77 let alloc = format!(
78 "{}Ki",
79 host.mem_total_kib.saturating_sub(MEM_AVAILABLE_MIN_KIB)
80 );
81 json!({
82 "capacity": {"cpu": host.cpus.to_string(), "memory": mem, "pods": "110"},
83 "allocatable": {"cpu": host.cpus.to_string(), "memory": alloc, "pods": "110"},
84 "conditions": conditions(ready, since, p),
85 "addresses": [{"type": "InternalIP", "address": ip}, {"type": "Hostname", "address": node}],
86 "daemonEndpoints": {"kubeletEndpoint": {"Port": if kport == 0 { 10250 } else { kport }}},
87 "nodeInfo": {
88 "machineID": host.machine_id,
89 "systemUUID": host.machine_id,
90 "bootID": host.boot_id,
91 "kernelVersion": host.kernel,
92 "osImage": host.os_image,
93 "containerRuntimeVersion": runtime,
94 "kubeletVersion": VERSION,
95 "kubeProxyVersion": VERSION,
96 "operatingSystem": "linux",
97 "architecture": host.arch
98 }
99 })
100}
101
102fn node_path(node: &str) -> String {
103 format!("/api/v1/nodes/{node}")
104}
105
106fn lease_path(node: &str) -> String {
107 format!("/apis/coordination.k8s.io/v1/namespaces/{LEASE_NS}/leases/{node}")
108}
109
110fn bad(what: &str, code: u16, body: &Value) -> io::Error {
111 io::Error::other(format!("{what}: HTTP {code} {}", s(body, "/message")))
112}
113
114pub fn runtime_version(name: &str) -> String {
115 format!("krab-{name}://{}", env!("CARGO_PKG_VERSION"))
116}
117
118pub async fn register(
119 c: &Client,
120 node: &str,
121 ip: &str,
122 kport: u16,
123 runtime: &str,
124) -> io::Result<Value> {
125 let host = host_info();
126 let now = now_rfc();
127 let st = status(&host, node, (ip, kport), runtime, true, &now, pressure());
128 let (code, existing) = c.get(&node_path(node)).await?;
129 if code == 404 {
130 let body = json!({
131 "apiVersion": "v1",
132 "kind": "Node",
133 "metadata": {"name": node, "labels": {
134 "kubernetes.io/hostname": node,
135 "kubernetes.io/os": "linux",
136 "kubernetes.io/arch": host.arch,
137 "krab.io/agent": "true"
138 }},
139 "spec": {},
140 "status": st
141 });
142 let (code, created) = c.post("/api/v1/nodes", &body).await?;
143 if code != 201 && code != 200 && code != 409 {
144 return Err(bad("create node", code, &created));
145 }
146 } else if code != 200 {
147 return Err(bad("get node", code, &existing));
148 }
149 let (code, out) = c
150 .patch(
151 &format!("{}/status", node_path(node)),
152 MERGE,
153 &json!({"status": st}),
154 )
155 .await?;
156 if code != 200 {
157 return Err(bad("patch node status", code, &out));
158 }
159 Ok(out)
160}
161
162async fn renew_lease(c: &Client, node: &str, uid: &str) -> io::Result<()> {
163 let renew = now_micro();
164 let (code, out) = c
165 .patch(
166 &lease_path(node),
167 "application/merge-patch+json",
168 &json!({"spec": {"holderIdentity": node, "leaseDurationSeconds": 40, "renewTime": renew}}),
169 )
170 .await?;
171 match code {
172 200 => Ok(()),
173 404 => {
174 let body = json!({
175 "apiVersion": "coordination.k8s.io/v1",
176 "kind": "Lease",
177 "metadata": {"name": node, "namespace": LEASE_NS,
178 "ownerReferences": [{"apiVersion": "v1", "kind": "Node", "name": node, "uid": uid}]},
179 "spec": {"holderIdentity": node, "leaseDurationSeconds": 40, "renewTime": renew}
180 });
181 let (code, out) = c
182 .post(
183 &format!("/apis/coordination.k8s.io/v1/namespaces/{LEASE_NS}/leases"),
184 &body,
185 )
186 .await?;
187 if matches!(code, 200 | 201 | 409) {
188 Ok(())
189 } else {
190 Err(bad("create lease", code, &out))
191 }
192 }
193 _ => Err(bad("renew lease", code, &out)),
194 }
195}
196
197pub async fn run<R: Runtime>(
198 c: &Client,
199 node: &str,
200 ip: &str,
201 kport: u16,
202 rt: &R,
203 mut node_obj: Value,
204) {
205 let host = host_info();
206 let runtime = runtime_version(rt.name());
207 let mut since = now_rfc();
208 let mut last_ready = true;
209 let mut last_pressure = Pressure::default();
210 let mut tick = tokio::time::interval(HEARTBEAT);
211 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
212 let mut n = 0u32;
213 loop {
214 tick.tick().await;
215 let ready = tokio::time::timeout(Duration::from_secs(8), rt.list())
216 .await
217 .is_ok_and(|r| r.is_ok());
218 let uid = s(&node_obj, "/metadata/uid").to_string();
219 if let Err(e) = renew_lease(c, node, &uid).await {
220 eprintln!("krab-agent: {e}");
221 }
222 n += 1;
223 let pr = pressure();
224 if ready != last_ready || pr != last_pressure || n >= STATUS_EVERY {
225 if ready != last_ready || pr != last_pressure {
226 since = now_rfc();
227 }
228 let st = status(&host, node, (ip, kport), &runtime, ready, &since, pr);
229 match c
230 .patch(
231 &format!("{}/status", node_path(node)),
232 MERGE,
233 &json!({"status": st}),
234 )
235 .await
236 {
237 Ok((200, out)) => {
238 node_obj = out;
239 last_ready = ready;
240 last_pressure = pr;
241 n = 0;
242 }
243 Ok((404, _)) => {
244 if let Ok(out) = register(c, node, ip, kport, &runtime).await {
245 node_obj = out;
246 last_ready = ready;
247 last_pressure = pr;
248 n = 0;
249 }
250 }
251 Ok((code, out)) => eprintln!("krab-agent: {}", bad("node status", code, &out)),
252 Err(e) => eprintln!("krab-agent: node status: {e}"),
253 }
254 }
255 }
256}