use crate::client::Client;
use hyper::body::Incoming;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
use krab_api::kubelet_bridge::{self, Op};
use krab_api::{App, Body};
use krab_controllers::util::{self, s};
use krab_runtime::cgroup::container_usage;
use krab_runtime::host::{cpu_busy_ticks, meminfo};
use krab_runtime::{Runtime, is_managed};
use krab_store::MemStore;
use krab_tls::{Identity, b64, csr, der, identity_from_peer, tls};
use rustls_pki_types::CertificateDer;
use rustls_pki_types::pem::PemObject;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::net::TcpListener;
use tokio_rustls::TlsAcceptor;
const CACHE_TTL: Duration = Duration::from_secs(60);
const CACHE_MAX: usize = 256;
const REVIEWS: usize = 8;
const REVIEW_WAIT: Duration = Duration::from_secs(5);
const CGROUP_ROOT: &str = "/sys/fs/cgroup";
pub struct Opts {
pub bind: SocketAddr,
pub serving_dir: PathBuf,
pub client_ca: Option<PathBuf>,
pub node_name: String,
pub node_ip: String,
}
struct Ctx<R> {
app: Arc<App<R>>,
rt: R,
store: Arc<MemStore>,
client: Arc<Client>,
node: String,
bind: SocketAddr,
cache: Mutex<HashMap<String, (Instant, bool)>>,
tokens: Mutex<HashMap<String, (Instant, Option<Identity>)>>,
reviews: tokio::sync::Semaphore,
}
fn status(code: u16, reason: &str, msg: &str) -> Response<Body> {
let body = json!({"apiVersion": "v1", "kind": "Status", "metadata": {}, "status": "Failure", "message": msg, "reason": reason, "code": code});
Response::builder()
.status(StatusCode::from_u16(code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR))
.header("content-type", "application/json")
.body(Body::full(body.to_string()))
.unwrap()
}
fn reply(ctype: &str, body: String) -> Response<Body> {
Response::builder()
.status(StatusCode::OK)
.header("content-type", ctype)
.body(Body::full(body))
.unwrap()
}
fn subresource(path: &str) -> &'static str {
let first = path.trim_start_matches('/').split('/').next().unwrap_or("");
match first {
"stats" => "stats",
"metrics" => "metrics",
"logs" => "log",
"spec" => "spec",
"checkpoint" => "checkpoint",
_ => "proxy",
}
}
fn verb(m: &Method) -> &'static str {
match *m {
Method::GET | Method::HEAD => "get",
Method::POST => "create",
Method::PUT => "update",
Method::PATCH => "patch",
Method::DELETE => "delete",
_ => "get",
}
}
fn required_verb(path: &str, m: &Method) -> &'static str {
match path.trim_start_matches('/').split('/').next().unwrap_or("") {
"exec" | "attach" | "portForward" | "run" => "create",
_ => verb(m),
}
}
fn bearer(req: &Request<Incoming>) -> Option<String> {
req.headers()
.get("authorization")?
.to_str()
.ok()?
.strip_prefix("Bearer ")
.map(str::to_string)
}
fn bounded<V>(m: &mut HashMap<String, V>) {
if m.len() >= CACHE_MAX {
m.clear();
}
}
impl<R: Runtime + Clone> Ctx<R> {
async fn review_permit(&self) -> Option<tokio::sync::SemaphorePermit<'_>> {
tokio::time::timeout(REVIEW_WAIT, self.reviews.acquire())
.await
.ok()?
.ok()
}
async fn token_identity(&self, token: &str) -> Option<Identity> {
if let Some((t, v)) = self
.tokens
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(token)
&& t.elapsed() < CACHE_TTL
{
return v.clone();
}
let _permit = self.review_permit().await?;
let body = json!({"apiVersion": "authentication.k8s.io/v1", "kind": "TokenReview", "spec": {"token": token}});
let (code, out) = self
.client
.post("/apis/authentication.k8s.io/v1/tokenreviews", &body)
.await
.ok()?;
if !matches!(code, 200 | 201) {
return None;
}
let id = (out["status"]["authenticated"] == true).then(|| Identity {
user: s(&out, "/status/user/username").to_string(),
groups: out["status"]["user"]["groups"]
.as_array()
.into_iter()
.flatten()
.filter_map(|g| g.as_str().map(str::to_string))
.collect(),
});
let mut m = self.tokens.lock().unwrap_or_else(|e| e.into_inner());
bounded(&mut m);
m.insert(token.to_string(), (Instant::now(), id.clone()));
id
}
async fn allowed(&self, id: &Identity, verb: &str, sub: &str) -> bool {
if id.groups.iter().any(|g| g == "system:masters") {
return true;
}
let key = format!("{}|{}|{verb}|{sub}", id.user, id.groups.join(","));
if let Some((t, v)) = self
.cache
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&key)
&& t.elapsed() < CACHE_TTL
{
return *v;
}
let Some(_permit) = self.review_permit().await else {
return false;
};
let body = json!({"apiVersion": "authorization.k8s.io/v1", "kind": "SubjectAccessReview", "spec": {
"user": id.user,
"groups": id.groups,
"resourceAttributes": {"verb": verb, "version": "v1", "resource": "nodes", "subresource": sub, "name": self.node}
}});
let ok = match self
.client
.post("/apis/authorization.k8s.io/v1/subjectaccessreviews", &body)
.await
{
Ok((200 | 201, out)) => out["status"]["allowed"] == true,
_ => return false,
};
let mut m = self.cache.lock().unwrap_or_else(|e| e.into_inner());
bounded(&mut m);
m.insert(key, (Instant::now(), ok));
ok
}
}
async fn handle<R: Runtime + Clone>(
cx: Arc<Ctx<R>>,
req: Request<Incoming>,
peer: Option<Identity>,
) -> Response<Body> {
let path = req.uri().path().trim_end_matches('/').to_string();
if path == "/healthz" {
return reply("text/plain", "ok".into());
}
let id = match peer {
Some(id) => id,
None => match bearer(&req) {
Some(t) => match cx.token_identity(&t).await {
Some(id) => id,
None => return status(401, "Unauthorized", "Unauthorized"),
},
None => return status(401, "Unauthorized", "Unauthorized"),
},
};
let sub = subresource(&path);
let v = required_verb(&path, req.method());
if !cx.allowed(&id, v, sub).await {
return status(
403,
"Forbidden",
&format!("user {} cannot {v} nodes/{sub}", id.user),
);
}
let segs: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect();
match (req.method().clone(), segs.as_slice()) {
(Method::GET, ["containerLogs", n, p, c]) => {
kubelet_bridge::handle(&cx.app, req, n, p, Some(c), Op::Logs).await
}
(Method::GET | Method::POST, [op @ ("exec" | "attach"), n, p, c])
| (Method::GET | Method::POST, [op @ ("exec" | "attach"), n, p, _, c]) => {
let op = if *op == "exec" { Op::Exec } else { Op::Attach };
kubelet_bridge::handle(&cx.app, req, n, p, Some(c), op).await
}
(Method::GET | Method::POST, ["portForward", n, p])
| (Method::GET | Method::POST, ["portForward", n, p, _]) => {
kubelet_bridge::handle(&cx.app, req, n, p, None, Op::PortForward).await
}
(Method::GET, ["metrics", "resource"]) => {
reply("text/plain; version=0.0.4", resource_metrics(&cx).await)
}
(Method::GET, ["configz"]) => reply(
"application/json",
json!({"kubeletconfig": {
"apiVersion": "kubelet.config.k8s.io/v1beta1",
"kind": "KubeletConfiguration",
"address": cx.bind.ip().to_string(),
"port": cx.bind.port(),
"readOnlyPort": 0,
"authentication": {"anonymous": {"enabled": false}, "webhook": {"enabled": true}},
"authorization": {"mode": "Webhook"}
}})
.to_string(),
),
(Method::GET, ["stats", "summary"]) => {
reply("application/json", stats_summary(&cx).await.to_string())
}
(Method::GET, ["pods"]) => {
let items: Vec<Value> = util::list(&cx.store, "pods/")
.into_iter()
.map(|(_, p)| p)
.collect();
reply(
"application/json",
json!({"apiVersion": "v1", "kind": "PodList", "items": items}).to_string(),
)
}
_ => status(404, "NotFound", "page not found"),
}
}
struct Sample {
ns: String,
pod: String,
uid: String,
container: String,
cpu_usec: u64,
mem: u64,
started: i64,
}
async fn samples<R: Runtime + Clone>(cx: &Ctx<R>) -> Vec<Sample> {
let Ok(list) = cx.rt.list().await else {
return Vec::new();
};
let node = Some(&cx.node);
list.into_iter()
.filter(|c| is_managed(c) && c.state == "running" && c.labels.get("krab.io/node") == node)
.filter_map(|c| {
let u = container_usage(CGROUP_ROOT, &c.id)?;
let l = |k: &str| c.labels.get(k).cloned().unwrap_or_default();
Some(Sample {
ns: l("krab.io/namespace"),
pod: l("krab.io/pod"),
uid: l("krab.io/uid"),
container: l("krab.io/container"),
cpu_usec: u.cpu_usec,
mem: u.mem_bytes,
started: util::parse_rfc3339(&c.started_at).unwrap_or(0),
})
})
.collect()
}
fn node_usage() -> (f64, u64) {
let cpu = cpu_busy_ticks().unwrap_or(0) as f64 / 100.0;
let (total, avail) = meminfo();
(cpu, total.saturating_sub(avail) * 1024)
}
fn esc(v: &str) -> String {
v.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
}
async fn resource_metrics<R: Runtime + Clone>(cx: &Ctx<R>) -> String {
let ts = util::now_secs() * 1000;
let (cpu, mem) = node_usage();
let mut out = format!(
"# TYPE node_cpu_usage_seconds_total counter\nnode_cpu_usage_seconds_total {cpu} {ts}\n# TYPE node_memory_working_set_bytes gauge\nnode_memory_working_set_bytes {mem} {ts}\n"
);
let list = samples(cx).await;
let mut pods: HashMap<(String, String), (u64, u64)> = HashMap::new();
out.push_str("# TYPE container_cpu_usage_seconds_total counter\n");
for c in &list {
out.push_str(&format!(
"container_cpu_usage_seconds_total{{container=\"{}\",namespace=\"{}\",pod=\"{}\"}} {} {ts}\n",
esc(&c.container),
esc(&c.ns),
esc(&c.pod),
c.cpu_usec as f64 / 1e6
));
let e = pods.entry((c.ns.clone(), c.pod.clone())).or_default();
e.0 += c.cpu_usec;
e.1 += c.mem;
}
out.push_str("# TYPE container_memory_working_set_bytes gauge\n");
for c in &list {
out.push_str(&format!(
"container_memory_working_set_bytes{{container=\"{}\",namespace=\"{}\",pod=\"{}\"}} {} {ts}\n",
esc(&c.container),
esc(&c.ns),
esc(&c.pod),
c.mem
));
}
out.push_str("# TYPE container_start_time_seconds gauge\n");
for c in &list {
out.push_str(&format!(
"container_start_time_seconds{{container=\"{}\",namespace=\"{}\",pod=\"{}\"}} {}\n",
esc(&c.container),
esc(&c.ns),
esc(&c.pod),
c.started
));
}
out.push_str("# TYPE pod_cpu_usage_seconds_total counter\n");
for ((n, p), (cpu, _)) in &pods {
out.push_str(&format!(
"pod_cpu_usage_seconds_total{{namespace=\"{}\",pod=\"{}\"}} {} {ts}\n",
esc(n),
esc(p),
*cpu as f64 / 1e6
));
}
out.push_str("# TYPE pod_memory_working_set_bytes gauge\n");
for ((n, p), (_, mem)) in &pods {
out.push_str(&format!(
"pod_memory_working_set_bytes{{namespace=\"{}\",pod=\"{}\"}} {mem} {ts}\n",
esc(n),
esc(p)
));
}
out.push_str("# TYPE scrape_error gauge\nscrape_error 0\n");
out
}
async fn stats_summary<R: Runtime + Clone>(cx: &Ctx<R>) -> Value {
let time = util::now_rfc();
let (cpu, mem) = node_usage();
let mut pods: HashMap<(String, String, String), Vec<Value>> = HashMap::new();
for c in samples(cx).await {
pods.entry((c.ns, c.pod, c.uid)).or_default().push(json!({
"name": c.container,
"startTime": util::rfc3339(c.started),
"cpu": {"time": time, "usageCoreNanoSeconds": c.cpu_usec * 1000},
"memory": {"time": time, "workingSetBytes": c.mem, "usageBytes": c.mem}
}));
}
let pods: Vec<Value> = pods
.into_iter()
.map(|((n, p, u), cs)| {
let cpu: u64 = cs
.iter()
.map(|c| c["cpu"]["usageCoreNanoSeconds"].as_u64().unwrap_or(0))
.sum();
let mem: u64 = cs
.iter()
.map(|c| c["memory"]["workingSetBytes"].as_u64().unwrap_or(0))
.sum();
json!({
"podRef": {"name": p, "namespace": n, "uid": u},
"cpu": {"time": time, "usageCoreNanoSeconds": cpu},
"memory": {"time": time, "workingSetBytes": mem, "usageBytes": mem},
"containers": cs
})
})
.collect();
json!({
"node": {
"nodeName": cx.node,
"cpu": {"time": time, "usageCoreNanoSeconds": (cpu * 1e9) as u64},
"memory": {"time": time, "workingSetBytes": mem, "usageBytes": mem}
},
"pods": pods
})
}
async fn client_ca(client: &Client, file: Option<&Path>) -> Option<String> {
if let Some(f) = file {
return std::fs::read_to_string(f).ok();
}
let (code, cm) = client
.get("/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication")
.await
.ok()?;
(code == 200)
.then(|| s(&cm, "/data/client-ca-file").to_string())
.filter(|c| !c.is_empty())
}
pub fn write_private(path: &Path, data: &[u8]) -> std::io::Result<()> {
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let tmp = path.with_extension("tmp");
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(&tmp)?;
f.write_all(data)?;
f.sync_all()?;
std::fs::rename(&tmp, path)
}
async fn serving_cert(
client: Arc<Client>,
dir: PathBuf,
node: String,
sans: Vec<String>,
ca: String,
slot: Arc<Mutex<TlsAcceptor>>,
) {
let (crt, key) = (dir.join("serving.crt"), dir.join("serving.key"));
let install = |cert: &str, key_pem: &str| match tls::acceptor_for(cert, key_pem, &ca) {
Ok(a) => {
*slot.lock().unwrap_or_else(|e| e.into_inner()) = a;
true
}
Err(e) => {
eprintln!("krab-agent: serving certificate: {e}");
false
}
};
'renew: loop {
if let (Ok(c), Ok(k)) = (std::fs::read_to_string(&crt), std::fs::read_to_string(&key))
&& let Some(wait) = CertificateDer::pem_slice_iter(c.as_bytes())
.next()
.and_then(Result::ok)
.and_then(|d| der::validity(d.as_ref()))
.and_then(|(nb, na)| crate::join::rotation_wait(nb, na, util::now_secs()))
&& install(&c, &k)
{
tokio::time::sleep(wait).await;
continue 'renew;
}
loop {
let Ok(req) = csr::serving_request(&node, &sans) else {
return;
};
let name = format!("csr-krab-{node}-{:08x}", util::rand_u64() as u32);
let body = json!({
"apiVersion": "certificates.k8s.io/v1",
"kind": "CertificateSigningRequest",
"metadata": {"name": name},
"spec": {
"request": b64::encode_std(req.csr_pem.as_bytes()),
"signerName": "kubernetes.io/kubelet-serving",
"usages": ["digital signature", "key encipherment", "server auth"]
}
});
match client
.post(
"/apis/certificates.k8s.io/v1/certificatesigningrequests",
&body,
)
.await
{
Ok((200 | 201, _)) => eprintln!(
"krab-agent: waiting for approval of kubelet-serving certificate request {name}"
),
other => {
eprintln!("krab-agent: create certificate request: {other:?}");
tokio::time::sleep(Duration::from_secs(30)).await;
continue;
}
}
let path = format!("/apis/certificates.k8s.io/v1/certificatesigningrequests/{name}");
let mut waited = 0u32;
loop {
tokio::time::sleep(Duration::from_secs(3)).await;
waited += 3;
let Ok((200, csr)) = client.get(&path).await else {
continue;
};
let cert = s(&csr, "/status/certificate");
if !cert.is_empty() {
if let Some(pem) = util::base64_decode(cert)
.and_then(|b| String::from_utf8(b).ok())
.filter(|p| install(p, &req.key_pem))
{
let _ = write_private(&key, req.key_pem.as_bytes());
let _ = write_private(&crt, pem.as_bytes());
eprintln!("krab-agent: kubelet-serving certificate installed");
let _ = client.delete(&path, &json!({})).await;
continue 'renew;
}
break;
}
let failed = csr["status"]["conditions"]
.as_array()
.into_iter()
.flatten()
.any(|c| matches!(s(c, "/type"), "Denied" | "Failed"));
if failed || waited >= 3600 {
break;
}
}
let _ = client.delete(&path, &json!({})).await;
tokio::time::sleep(Duration::from_secs(60)).await;
}
}
}
pub async fn run<R: Runtime + Clone>(
app: Arc<App<R>>,
rt: R,
store: Arc<MemStore>,
client: Arc<Client>,
opts: Opts,
) -> Result<(), String> {
let sans = vec![opts.node_ip.clone(), opts.node_name.clone()];
let (cert, key) =
csr::self_signed_serving(&opts.node_name, &sans).map_err(|e| e.to_string())?;
let ca = match client_ca(&client, opts.client_ca.as_deref()).await {
Some(c) => c,
None => client.ca_pem(),
};
if ca.is_empty() {
eprintln!(
"krab-agent: cluster client CA unavailable, client certificates are not accepted (bearer tokens only)"
);
}
let acceptor = Arc::new(Mutex::new(
tls::acceptor_for(&cert, &key, &ca).map_err(|e| e.to_string())?,
));
tokio::spawn(serving_cert(
client.clone(),
opts.serving_dir.clone(),
opts.node_name.clone(),
sans,
ca,
acceptor.clone(),
));
let listener = TcpListener::bind(opts.bind)
.await
.map_err(|e| format!("bind {}: {e}", opts.bind))?;
let bind = listener.local_addr().map_err(|e| e.to_string())?;
let cx = Arc::new(Ctx {
app,
rt,
store,
client,
node: opts.node_name,
bind,
cache: Mutex::new(HashMap::new()),
tokens: Mutex::new(HashMap::new()),
reviews: tokio::sync::Semaphore::new(REVIEWS),
});
let permits = Arc::new(tokio::sync::Semaphore::new(64));
let per_ip: Arc<Mutex<HashMap<std::net::IpAddr, usize>>> = Arc::new(Mutex::new(HashMap::new()));
loop {
let (stream, addr) = listener.accept().await.map_err(|e| e.to_string())?;
let Ok(permit) = permits.clone().try_acquire_owned() else {
continue;
};
let Some(_slot) = IpSlot::take(&per_ip, addr.ip()) else {
continue;
};
let acceptor = acceptor.lock().unwrap_or_else(|e| e.into_inner()).clone();
let cx = cx.clone();
tokio::spawn(async move {
let (_permit, _slot) = (permit, _slot);
let Ok(Ok(tls)) =
tokio::time::timeout(Duration::from_secs(10), acceptor.accept(stream)).await
else {
return;
};
let peer = identity_from_peer(tls.get_ref().1);
let svc = hyper::service::service_fn(move |req| {
let (cx, peer) = (cx.clone(), peer.clone());
async move { Ok::<_, Infallible>(handle(cx, req, peer).await) }
});
let mut b = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
b.http1()
.timer(TokioTimer::new())
.header_read_timeout(Duration::from_secs(30));
let _ = b
.serve_connection_with_upgrades(TokioIo::new(tls), svc)
.await;
});
}
}
const PER_IP: usize = 16;
struct IpSlot {
map: Arc<Mutex<HashMap<std::net::IpAddr, usize>>>,
ip: std::net::IpAddr,
}
impl IpSlot {
fn take(
map: &Arc<Mutex<HashMap<std::net::IpAddr, usize>>>,
ip: std::net::IpAddr,
) -> Option<Self> {
let mut g = map.lock().unwrap_or_else(|e| e.into_inner());
let n = g.entry(ip).or_insert(0);
if *n >= PER_IP {
return None;
}
*n += 1;
Some(Self {
map: map.clone(),
ip,
})
}
}
impl Drop for IpSlot {
fn drop(&mut self) {
let mut g = self.map.lock().unwrap_or_else(|e| e.into_inner());
if let Some(n) = g.get_mut(&self.ip) {
*n -= 1;
if *n == 0 {
g.remove(&self.ip);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn per_ip_slots_are_limited_and_released() {
let map = Arc::new(Mutex::new(HashMap::new()));
let ip: std::net::IpAddr = "10.0.0.1".parse().unwrap();
let held: Vec<_> = (0..PER_IP)
.map(|_| IpSlot::take(&map, ip).unwrap())
.collect();
assert!(IpSlot::take(&map, ip).is_none());
assert!(IpSlot::take(&map, "10.0.0.2".parse().unwrap()).is_some());
drop(held);
assert!(IpSlot::take(&map, ip).is_some());
}
#[test]
fn streaming_endpoints_always_need_create() {
for p in [
"/exec/d/p/c",
"/attach/d/p/c",
"/portForward/d/p",
"/run/d/p/c",
] {
assert_eq!(required_verb(p, &Method::GET), "create", "{p}");
assert_eq!(required_verb(p, &Method::POST), "create", "{p}");
}
assert_eq!(required_verb("/containerLogs/d/p/c", &Method::GET), "get");
assert_eq!(required_verb("/metrics/resource", &Method::GET), "get");
assert_eq!(required_verb("/pods", &Method::DELETE), "delete");
}
}