Skip to main content

krab_controllers/
util.rs

1use bytes::Bytes;
2use krab_store::{Event, MemStore};
3use serde_json::{Map, Value, json};
4use std::collections::{HashMap, VecDeque};
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Mutex, PoisonError};
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8use tokio::sync::broadcast::{self, error::RecvError, error::TryRecvError};
9
10pub const ALPHABET: &[u8] = b"bcdfghjklmnpqrstvwxz2456789";
11const MAX_EVENTS: usize = 256;
12
13pub fn now_secs() -> i64 {
14    SystemTime::now()
15        .duration_since(UNIX_EPOCH)
16        .map(|d| d.as_secs() as i64)
17        .unwrap_or(0)
18}
19
20pub fn rfc3339(secs: i64) -> String {
21    let days = secs.div_euclid(86400);
22    let rem = secs.rem_euclid(86400);
23    let z = days + 719468;
24    let era = z.div_euclid(146097);
25    let doe = z.rem_euclid(146097);
26    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
27    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
28    let mp = (5 * doy + 2) / 153;
29    let d = doy - (153 * mp + 2) / 5 + 1;
30    let m = if mp < 10 { mp + 3 } else { mp - 9 };
31    let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };
32    format!(
33        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
34        y,
35        m,
36        d,
37        rem / 3600,
38        (rem % 3600) / 60,
39        rem % 60
40    )
41}
42
43pub fn parse_rfc3339(s: &str) -> Option<i64> {
44    let b = s.as_bytes();
45    if b.len() < 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' {
46        return None;
47    }
48    let n = |r: std::ops::Range<usize>| s.get(r)?.parse::<i64>().ok();
49    let (y, m, d) = (n(0..4)?, n(5..7)?, n(8..10)?);
50    let (hh, mm, ss) = (n(11..13)?, n(14..16)?, n(17..19)?);
51    let y2 = if m <= 2 { y - 1 } else { y };
52    let era = y2.div_euclid(400);
53    let yoe = y2.rem_euclid(400);
54    let mp = if m > 2 { m - 3 } else { m + 9 };
55    let doy = (153 * mp + 2) / 5 + d - 1;
56    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
57    Some((era * 146097 + doe - 719468) * 86400 + hh * 3600 + mm * 60 + ss)
58}
59
60pub fn now_rfc() -> String {
61    rfc3339(now_secs())
62}
63
64pub fn now_micro() -> String {
65    let d = SystemTime::now()
66        .duration_since(UNIX_EPOCH)
67        .unwrap_or_default();
68    let s = rfc3339(d.as_secs() as i64);
69    format!("{}.{:06}Z", &s[..19], d.subsec_micros())
70}
71
72pub fn rand_u64() -> u64 {
73    static STATE: AtomicU64 = AtomicU64::new(0);
74    let seed = SystemTime::now()
75        .duration_since(UNIX_EPOCH)
76        .map(|d| d.as_nanos() as u64)
77        .unwrap_or(0);
78    let mut z = STATE
79        .fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed)
80        .wrapping_add(seed);
81    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
82    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
83    z ^ (z >> 31)
84}
85
86pub fn rand_suffix(n: usize) -> String {
87    (0..n)
88        .map(|_| ALPHABET[(rand_u64() % ALPHABET.len() as u64) as usize] as char)
89        .collect()
90}
91
92pub fn new_uid() -> String {
93    let a = rand_u64();
94    let b = rand_u64();
95    let h = format!("{a:016x}{b:016x}");
96    format!(
97        "{}-{}-4{}-a{}-{}",
98        &h[0..8],
99        &h[8..12],
100        &h[13..16],
101        &h[17..20],
102        &h[20..32]
103    )
104}
105
106pub fn fnv32a(data: &[u8]) -> u32 {
107    let mut h: u32 = 0x811c_9dc5;
108    for b in data {
109        h ^= *b as u32;
110        h = h.wrapping_mul(0x0100_0193);
111    }
112    h
113}
114
115pub fn safe_encode(s: &str) -> String {
116    s.bytes()
117        .map(|b| ALPHABET[b as usize % ALPHABET.len()] as char)
118        .collect()
119}
120
121pub fn template_hash(template: &Value) -> String {
122    let data = serde_json::to_vec(template).unwrap_or_default();
123    safe_encode(&fnv32a(&data).to_string())
124}
125
126pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
127    let mut out = Vec::with_capacity(s.len() * 3 / 4);
128    let mut acc = 0u32;
129    let mut bits = 0;
130    for c in s.bytes() {
131        let v = match c {
132            b'A'..=b'Z' => c - b'A',
133            b'a'..=b'z' => c - b'a' + 26,
134            b'0'..=b'9' => c - b'0' + 52,
135            b'+' | b'-' => 62,
136            b'/' | b'_' => 63,
137            b'=' | b'\n' | b'\r' | b' ' => continue,
138            _ => return None,
139        } as u32;
140        acc = (acc << 6) | v;
141        bits += 6;
142        if bits >= 8 {
143            bits -= 8;
144            out.push((acc >> bits) as u8);
145            acc &= (1 << bits) - 1;
146        }
147    }
148    Some(out)
149}
150
151pub fn quantity(s: &str) -> Option<f64> {
152    let s = s.trim();
153    let split = s
154        .find(|c: char| c.is_ascii_alphabetic() && c != 'e' && c != 'E')
155        .unwrap_or(s.len());
156    let (num, suf) = s.split_at(split);
157    let n: f64 = num.parse().ok()?;
158    let mul = match suf {
159        "" => 1.0,
160        "n" => 1e-9,
161        "u" => 1e-6,
162        "m" => 1e-3,
163        "k" => 1e3,
164        "M" => 1e6,
165        "G" => 1e9,
166        "T" => 1e12,
167        "P" => 1e15,
168        "E" => 1e18,
169        "Ki" => 1024.0,
170        "Mi" => 1024.0 * 1024.0,
171        "Gi" => 1024.0 * 1024.0 * 1024.0,
172        "Ti" => 1024f64.powi(4),
173        "Pi" => 1024f64.powi(5),
174        "Ei" => 1024f64.powi(6),
175        _ => return None,
176    };
177    Some(n * mul)
178}
179
180pub fn int_or_percent(v: &Value, total: i64, round_up: bool, default: &str) -> i64 {
181    let v = if v.is_null() { &json!(default) } else { v };
182    if let Some(n) = v.as_i64() {
183        return n.max(0);
184    }
185    let s = v.as_str().unwrap_or("0");
186    match s.strip_suffix('%').and_then(|p| p.parse::<f64>().ok()) {
187        Some(p) => {
188            let x = p * total as f64 / 100.0;
189            (if round_up { x.ceil() } else { x.floor() }) as i64
190        }
191        None => s.parse().unwrap_or(0),
192    }
193}
194
195pub fn parse(b: &Bytes) -> Option<Value> {
196    serde_json::from_slice(b).ok()
197}
198
199pub fn get(store: &MemStore, key: &str) -> Option<Value> {
200    store.get(key).as_ref().and_then(parse)
201}
202
203pub fn list(store: &MemStore, prefix: &str) -> Vec<(String, Value)> {
204    store
205        .list(prefix)
206        .items
207        .into_iter()
208        .filter_map(|(k, v)| parse(&v).map(|v| (k.to_string(), v)))
209        .collect()
210}
211
212pub fn to_bytes(v: &Value, rev: u64) -> Bytes {
213    let mut v = v.clone();
214    v["metadata"]["resourceVersion"] = json!(rev.to_string());
215    Bytes::from(serde_json::to_vec(&v).unwrap_or_default())
216}
217
218pub fn create(store: &MemStore, key: &str, mut v: Value) -> Option<Value> {
219    if store.get(key).is_some() {
220        return None;
221    }
222    let m = &mut v["metadata"];
223    if m["uid"].as_str().is_none_or(str::is_empty) {
224        m["uid"] = json!(new_uid());
225    }
226    if m["creationTimestamp"].is_null() {
227        m["creationTimestamp"] = json!(now_rfc());
228    }
229    if m["generation"].is_null() && !key.starts_with("pods/") && !key.starts_with("events/") {
230        m["generation"] = json!(1);
231    }
232    let rev = store.put(key, |rev| to_bytes(&v, rev));
233    v["metadata"]["resourceVersion"] = json!(rev.to_string());
234    Some(v)
235}
236
237pub fn fix_object(v: &mut Value, ptr: &str) {
238    if let Some(x) = v.pointer_mut(ptr)
239        && !x.is_null()
240        && !x.is_object()
241    {
242        *x = json!({});
243    }
244}
245
246pub fn update(store: &MemStore, key: &str, mut f: impl FnMut(&mut Value) -> bool) -> Option<Value> {
247    for _ in 0..8 {
248        let cur = store.get(key)?;
249        let mut v = parse(&cur)?;
250        if !v.is_object() {
251            return None;
252        }
253        for p in [
254            "/metadata",
255            "/metadata/labels",
256            "/metadata/annotations",
257            "/spec",
258            "/status",
259        ] {
260            fix_object(&mut v, p);
261        }
262        let spec_before = v["spec"].clone();
263        if !f(&mut v) {
264            return None;
265        }
266        if v["spec"] != spec_before && !key.starts_with("pods/") {
267            let g = v["metadata"]["generation"].as_i64().unwrap_or(1);
268            v["metadata"]["generation"] = json!(g + 1);
269        }
270        if store.get(key).as_ref() != Some(&cur) {
271            continue;
272        }
273        let rev = store.put(key, |rev| to_bytes(&v, rev));
274        v["metadata"]["resourceVersion"] = json!(rev.to_string());
275        return Some(v);
276    }
277    None
278}
279
280pub fn delete(store: &MemStore, key: &str) -> bool {
281    store
282        .delete(key, |rev, old| {
283            parse(old)
284                .map(|v| to_bytes(&v, rev))
285                .unwrap_or_else(|| old.clone())
286        })
287        .is_some()
288}
289
290pub fn delete_pod(store: &MemStore, key: &str) {
291    let Some(pod) = get(store, key) else { return };
292    if pod["spec"]["nodeName"].as_str().is_none_or(str::is_empty) {
293        delete(store, key);
294        return;
295    }
296    update(store, key, |p| {
297        if !p["metadata"]["deletionTimestamp"].is_null() {
298            return false;
299        }
300        let grace = p["spec"]["terminationGracePeriodSeconds"]
301            .as_i64()
302            .unwrap_or(30);
303        p["metadata"]["deletionTimestamp"] = json!(rfc3339(now_secs() + grace));
304        p["metadata"]["deletionGracePeriodSeconds"] = json!(grace);
305        true
306    });
307}
308
309pub fn s<'a>(v: &'a Value, ptr: &str) -> &'a str {
310    v.pointer(ptr).and_then(Value::as_str).unwrap_or("")
311}
312
313pub fn name(v: &Value) -> &str {
314    s(v, "/metadata/name")
315}
316
317pub fn ns(v: &Value) -> &str {
318    s(v, "/metadata/namespace")
319}
320
321pub fn uid(v: &Value) -> &str {
322    s(v, "/metadata/uid")
323}
324
325pub fn terminating(v: &Value) -> bool {
326    !v["metadata"]["deletionTimestamp"].is_null()
327}
328
329pub fn created(v: &Value) -> i64 {
330    parse_rfc3339(s(v, "/metadata/creationTimestamp")).unwrap_or(0)
331}
332
333pub fn controller_uid(v: &Value) -> Option<&str> {
334    v["metadata"]["ownerReferences"]
335        .as_array()?
336        .iter()
337        .find(|r| r["controller"].as_bool() == Some(true))
338        .and_then(|r| r["uid"].as_str())
339}
340
341pub fn controller_kind(v: &Value) -> Option<&str> {
342    v["metadata"]["ownerReferences"]
343        .as_array()?
344        .iter()
345        .find(|r| r["controller"].as_bool() == Some(true))
346        .and_then(|r| r["kind"].as_str())
347}
348
349pub fn owner_ref(api: &str, kind: &str, owner: &Value) -> Value {
350    json!({
351        "apiVersion": api,
352        "kind": kind,
353        "name": name(owner),
354        "uid": uid(owner),
355        "controller": true,
356        "blockOwnerDeletion": true
357    })
358}
359
360pub fn map_matches(sel: &Value, labels: &Value) -> bool {
361    match sel.as_object() {
362        None => true,
363        Some(m) => m
364            .iter()
365            .all(|(k, v)| labels.get(k).and_then(Value::as_str) == v.as_str()),
366    }
367}
368
369pub fn selector_matches(sel: &Value, labels: &Value) -> bool {
370    if !map_matches(&sel["matchLabels"], labels) {
371        return false;
372    }
373    let Some(exprs) = sel["matchExpressions"].as_array() else {
374        return true;
375    };
376    exprs.iter().all(|e| {
377        let val = labels.get(s(e, "/key")).and_then(Value::as_str);
378        let vals: Vec<&str> = e["values"]
379            .as_array()
380            .map(|a| a.iter().filter_map(Value::as_str).collect())
381            .unwrap_or_default();
382        match s(e, "/operator") {
383            "In" => val.is_some_and(|v| vals.contains(&v)),
384            "NotIn" => val.is_none_or(|v| !vals.contains(&v)),
385            "Exists" => val.is_some(),
386            "DoesNotExist" => val.is_none(),
387            _ => false,
388        }
389    })
390}
391
392pub fn pod_active(p: &Value) -> bool {
393    !terminating(p) && !matches!(s(p, "/status/phase"), "Succeeded" | "Failed")
394}
395
396pub fn condition<'a>(v: &'a Value, ty: &str) -> Option<&'a Value> {
397    v["status"]["conditions"]
398        .as_array()?
399        .iter()
400        .find(|c| c["type"].as_str() == Some(ty))
401}
402
403pub fn pod_ready(p: &Value) -> bool {
404    condition(p, "Ready").and_then(|c| c["status"].as_str()) == Some("True")
405}
406
407pub fn pod_available(p: &Value, min_ready: i64, now: i64) -> bool {
408    if !pod_ready(p) {
409        return false;
410    }
411    if min_ready <= 0 {
412        return true;
413    }
414    let since = condition(p, "Ready")
415        .and_then(|c| c["lastTransitionTime"].as_str())
416        .and_then(parse_rfc3339)
417        .unwrap_or(now);
418    since + min_ready <= now
419}
420
421pub fn set_condition(v: &mut Value, ty: &str, status: bool, reason: &str, msg: &str) -> bool {
422    let st = if status { "True" } else { "False" };
423    if !v["status"].is_object() {
424        v["status"] = json!({});
425    }
426    if !v["status"]["conditions"].is_array() {
427        v["status"]["conditions"] = json!([]);
428    }
429    let conds = v["status"]["conditions"].as_array_mut().unwrap();
430    let now = now_rfc();
431    if let Some(c) = conds.iter_mut().find(|c| c["type"].as_str() == Some(ty)) {
432        if c["status"].as_str() == Some(st)
433            && c["reason"].as_str().unwrap_or("") == reason
434            && c["message"].as_str().unwrap_or("") == msg
435        {
436            return false;
437        }
438        if c["status"].as_str() != Some(st) {
439            c["lastTransitionTime"] = json!(now);
440        }
441        c["status"] = json!(st);
442        set_opt(c, "reason", reason);
443        set_opt(c, "message", msg);
444        if c.get("lastUpdateTime").is_some() {
445            c["lastUpdateTime"] = json!(now);
446        }
447        return true;
448    }
449    let mut c = json!({"type": ty, "status": st, "lastTransitionTime": now});
450    set_opt(&mut c, "reason", reason);
451    set_opt(&mut c, "message", msg);
452    conds.push(c);
453    true
454}
455
456fn set_opt(c: &mut Value, k: &str, v: &str) {
457    match c.as_object_mut() {
458        Some(o) if v.is_empty() => {
459            o.remove(k);
460        }
461        Some(o) => {
462            o.insert(k.into(), json!(v));
463        }
464        None => {}
465    }
466}
467
468pub fn subscribe(store: &MemStore) -> broadcast::Receiver<Event> {
469    match store.watch("\u{10FFFF}", Some(store.rev())) {
470        Ok(w) => w.rx,
471        Err(_) => store.watch("\u{10FFFF}", None).ok().map(|w| w.rx).unwrap(),
472    }
473}
474
475pub async fn wait_event(rx: &mut broadcast::Receiver<Event>, prefixes: &[&str]) -> bool {
476    loop {
477        match rx.recv().await {
478            Ok(e) if prefixes.iter().any(|p| e.key.starts_with(p)) => return true,
479            Ok(_) => {}
480            Err(RecvError::Lagged(_)) => return true,
481            Err(RecvError::Closed) => return false,
482        }
483    }
484}
485
486pub fn drain(rx: &mut broadcast::Receiver<Event>) {
487    loop {
488        match rx.try_recv() {
489            Ok(_) | Err(TryRecvError::Lagged(_)) => {}
490            Err(_) => return,
491        }
492    }
493}
494
495pub async fn level_loop(
496    store: &MemStore,
497    prefixes: &[&str],
498    resync: Duration,
499    mut f: impl FnMut(),
500) {
501    let mut rx = subscribe(store);
502    let mut tick = tokio::time::interval(resync);
503    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
504    loop {
505        drain(&mut rx);
506        f();
507        tokio::select! {
508            _ = tick.tick() => {}
509            ok = wait_event(&mut rx, prefixes) => if !ok { return },
510        }
511        tokio::time::sleep(Duration::from_millis(20)).await;
512    }
513}
514
515struct RecState {
516    keys: VecDeque<String>,
517    index: HashMap<String, String>,
518}
519
520pub struct Recorder {
521    component: &'static str,
522    state: Mutex<RecState>,
523}
524
525impl Default for Recorder {
526    fn default() -> Self {
527        Self::new("krab")
528    }
529}
530
531impl Recorder {
532    pub fn new(component: &'static str) -> Self {
533        Self {
534            component,
535            state: Mutex::new(RecState {
536                keys: VecDeque::new(),
537                index: HashMap::new(),
538            }),
539        }
540    }
541
542    pub fn event(&self, store: &MemStore, obj: &Value, reason: &str, msg: &str, warn: bool) {
543        let namespace = match ns(obj) {
544            "" => "default",
545            n => n,
546        };
547        let ident = format!("{}|{reason}|{msg}", uid(obj));
548        let now = now_rfc();
549        let mut st = self.state.lock().unwrap_or_else(PoisonError::into_inner);
550        if let Some(key) = st.index.get(&ident).cloned() {
551            let bumped = update(store, &key, |e| {
552                let c = e["count"].as_i64().unwrap_or(1);
553                e["count"] = json!(c + 1);
554                e["lastTimestamp"] = json!(now);
555                true
556            });
557            if bumped.is_some() {
558                return;
559            }
560            st.index.remove(&ident);
561        }
562        let ev_name = format!("{}.{:016x}", name(obj), rand_u64());
563        let key = format!("events/{namespace}/{ev_name}");
564        let mut involved = Map::new();
565        for (k, p) in [
566            ("apiVersion", "/apiVersion"),
567            ("kind", "/kind"),
568            ("name", "/metadata/name"),
569            ("namespace", "/metadata/namespace"),
570            ("uid", "/metadata/uid"),
571            ("resourceVersion", "/metadata/resourceVersion"),
572        ] {
573            let v = s(obj, p);
574            if !v.is_empty() {
575                involved.insert(k.into(), json!(v));
576            }
577        }
578        let ev = json!({
579            "apiVersion": "v1",
580            "kind": "Event",
581            "metadata": {"name": ev_name, "namespace": namespace, "uid": new_uid(), "creationTimestamp": now},
582            "involvedObject": involved,
583            "reason": reason,
584            "message": msg,
585            "type": if warn { "Warning" } else { "Normal" },
586            "source": {"component": self.component},
587            "firstTimestamp": now,
588            "lastTimestamp": now,
589            "count": 1,
590            "reportingComponent": self.component,
591            "reportingInstance": self.component
592        });
593        create(store, &key, ev);
594        st.keys.push_back(key.clone());
595        st.index.insert(ident, key);
596        while st.keys.len() > MAX_EVENTS {
597            if let Some(old) = st.keys.pop_front() {
598                delete(store, &old);
599                st.index.retain(|_, k| k != &old);
600            }
601        }
602    }
603}
604
605#[cfg(test)]
606mod tests {
607    use super::*;
608
609    #[test]
610    fn update_survives_garbage_shapes() {
611        let st = MemStore::new(1 << 20, 16);
612        st.put("replicasets/d/r", |_| {
613            Bytes::from_static(br#"{"metadata":{"name":"r","annotations":"x","labels":[1]},"spec":"x","status":"x"}"#)
614        });
615        let v = update(&st, "replicasets/d/r", |r| {
616            r["status"]["replicas"] = json!(1);
617            r["spec"]["replicas"] = json!(1);
618            r["metadata"]["annotations"]["a"] = json!("b");
619            r["metadata"]["labels"]["l"] = json!("v");
620            true
621        })
622        .unwrap();
623        assert_eq!(v["status"]["replicas"], 1);
624        assert_eq!(v["metadata"]["annotations"]["a"], "b");
625        st.put("leases/n/x", |_| Bytes::from_static(b"[1]"));
626        assert!(update(&st, "leases/n/x", |_| true).is_none());
627    }
628
629    #[test]
630    fn helpers() {
631        assert_eq!(parse_rfc3339(&rfc3339(1_795_000_000)), Some(1_795_000_000));
632        assert_eq!(base64_decode("aGVsbG8=").unwrap(), b"hello");
633        assert_eq!(quantity("128Mi"), Some(134217728.0));
634        assert_eq!(quantity("500m"), Some(0.5));
635        assert_eq!(quantity("1e3"), Some(1000.0));
636        assert_eq!(int_or_percent(&Value::Null, 4, true, "25%"), 1);
637        assert_eq!(int_or_percent(&json!("50%"), 3, false, "25%"), 1);
638        assert_eq!(new_uid().len(), 36);
639        let sel = json!({"matchLabels": {"a": "1"}, "matchExpressions": [{"key": "b", "operator": "In", "values": ["x"]}]});
640        assert!(selector_matches(&sel, &json!({"a": "1", "b": "x"})));
641        assert!(!selector_matches(&sel, &json!({"a": "1"})));
642    }
643
644    #[test]
645    fn update_bumps_generation_and_rv() {
646        let st = MemStore::new(1 << 20, 16);
647        create(
648            &st,
649            "deployments/d/x",
650            json!({"metadata": {"name": "x"}, "spec": {"replicas": 1}}),
651        );
652        let v = update(&st, "deployments/d/x", |v| {
653            v["spec"]["replicas"] = json!(2);
654            true
655        })
656        .unwrap();
657        assert_eq!(v["metadata"]["generation"], 2);
658        assert_eq!(
659            get(&st, "deployments/d/x").unwrap()["metadata"]["resourceVersion"],
660            json!(st.rev().to_string())
661        );
662        assert!(update(&st, "deployments/d/x", |_| false).is_none());
663    }
664}