use crate::client::Client;
use crate::mirror::delete_body;
use krab_controllers::util::{self, name, ns, s, uid};
use krab_store::{EventKind, MemStore};
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::broadcast::error::RecvError;
const MERGE: &str = "application/strategic-merge-patch+json";
const FLUSH: Duration = Duration::from_millis(300);
fn status_patch(pod: &Value, status: &Value) -> Value {
let mut status = status.clone();
if let Some(ips) = status["podIPs"].as_array_mut() {
ips.insert(0, json!({"$patch": "replace"}));
}
json!({"metadata": {"uid": uid(pod)}, "status": status})
}
async fn push_pod(c: &Client, pod: &Value, last: &mut HashMap<String, (Value, String)>) -> bool {
let status = pod["status"].clone();
if s(&status, "/phase").is_empty() || last.get(uid(pod)).is_some_and(|l| l.0 == status) {
return true;
}
let path = format!("/api/v1/namespaces/{}/pods/{}/status", ns(pod), name(pod));
match c.patch(&path, MERGE, &status_patch(pod, &status)).await {
Ok((200, _)) | Ok((404, _)) => {
last.insert(
uid(pod).to_string(),
(status, format!("{}/{}", ns(pod), name(pod))),
);
true
}
Ok((code, out)) => {
eprintln!(
"krab-agent: pod status {}/{}: HTTP {code} {}",
ns(pod),
name(pod),
s(&out, "/message")
);
code < 500 && code != 409 && code != 429 && code != 403
}
Err(e) => {
eprintln!("krab-agent: pod status {}/{}: {e}", ns(pod), name(pod));
false
}
}
}
async fn push_event(c: &Client, ev: &Value, node: &str, posted: &mut HashSet<String>) -> bool {
let namespace = ns(ev);
if posted.contains(&format!("{namespace}/{}", name(ev))) {
let path = format!("/api/v1/namespaces/{namespace}/events/{}", name(ev));
let body = json!({"count": ev["count"], "lastTimestamp": ev["lastTimestamp"]});
return matches!(
c.patch(&path, "application/merge-patch+json", &body).await,
Ok((200, _)) | Ok((404, _))
);
}
let mut body = ev.clone();
if let Some(m) = body["metadata"].as_object_mut() {
m.remove("uid");
m.remove("resourceVersion");
}
body["source"]["host"] = json!(node);
let path = format!("/api/v1/namespaces/{namespace}/events");
match c.post(&path, &body).await {
Ok((200 | 201 | 409, _)) => {
posted.insert(format!("{namespace}/{}", name(ev)));
true
}
Ok((code, out)) => {
eprintln!("krab-agent: event: HTTP {code} {}", s(&out, "/message"));
code < 500 && code != 429 && code != 403
}
Err(_) => false,
}
}
pub async fn run(c: Arc<Client>, store: Arc<MemStore>, node: String) {
let mut rx = util::subscribe(&store);
let mut dirty: HashSet<String> = HashSet::new();
let mut deleted: Vec<Value> = Vec::new();
let mut last: HashMap<String, (Value, String)> = HashMap::new();
let mut posted: HashSet<String> = HashSet::new();
let mut retry: HashSet<String> = HashSet::new();
let mut ticks = 0u32;
let mut tick = tokio::time::interval(FLUSH);
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
tokio::select! {
ev = rx.recv() => match ev {
Ok(e) => {
if e.key.starts_with("pods/") || e.key.starts_with("events/") {
match e.kind {
EventKind::Deleted if e.key.starts_with("pods/") => {
if let Some(p) = util::parse(&e.obj) {
last.remove(uid(&p));
deleted.push(p);
}
dirty.remove(&*e.key);
}
EventKind::Deleted => {}
_ => {
dirty.insert(e.key.to_string());
}
}
}
}
Err(RecvError::Lagged(_)) => {
for p in ["pods/", "events/"] {
dirty.extend(store.list(p).items.into_iter().map(|(k, _)| k.to_string()));
}
let live: HashSet<String> = util::list(&store, "pods/")
.iter()
.map(|(_, p)| uid(p).to_string())
.collect();
last.retain(|u, (_, key)| {
if live.contains(u) {
return true;
}
if let Some((n, p)) = key.split_once('/') {
deleted.push(json!({"metadata": {"uid": u, "namespace": n, "name": p}}));
}
false
});
}
Err(RecvError::Closed) => return,
},
_ = tick.tick() => {
ticks = ticks.wrapping_add(1);
if ticks.is_multiple_of(20) {
dirty.extend(retry.drain());
}
let keys: Vec<String> = dirty.drain().collect();
for k in keys {
let Some(obj) = util::get(&store, &k) else { continue };
let ok = if k.starts_with("pods/") {
push_pod(&c, &obj, &mut last).await
} else {
push_event(&c, &obj, &node, &mut posted).await
};
if !ok {
retry.insert(k);
}
}
for p in std::mem::take(&mut deleted) {
let path = format!("/api/v1/namespaces/{}/pods/{}", ns(&p), name(&p));
match c.delete(&path, &delete_body(uid(&p))).await {
Ok((code, _)) if code < 500 && code != 429 => {}
_ => deleted.push(p),
}
}
if posted.len() > 4096 {
posted.clear();
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pod_ips_are_replaced_not_merged() {
let pod = json!({"metadata": {"uid": "u"}});
let body = status_patch(
&pod,
&json!({"phase": "Running", "podIPs": [{"ip": "10.0.0.2"}]}),
);
assert_eq!(body["status"]["podIPs"][0], json!({"$patch": "replace"}));
assert_eq!(body["status"]["podIPs"][1]["ip"], "10.0.0.2");
}
}