mod body;
pub mod crypt;
mod defaults;
mod discovery;
mod gc;
pub mod kubelet_bridge;
mod objects;
pub mod objects_util;
pub mod patch;
mod proto;
pub mod registry;
mod select;
mod spdy;
mod status;
mod stream;
mod sync;
mod table;
mod util;
mod write;
pub use body::Body;
use bytes::Bytes;
use http_body_util::BodyExt;
use hyper::body::Incoming;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
pub use krab_crypt::{CryptError, Keyring};
use krab_runtime::host::{HostInfo, host_info, rss_kib};
use krab_runtime::{ContainerInfo, LogOpts, Runtime, is_managed};
use krab_store::WatchError;
pub use krab_store::{MemStore, Resealed, SyncMode};
use krab_tls::sa::Signer;
use krab_tls::tokens::StaticTokens;
use krab_tls::{Identity, Pki, identity_from_peer};
use registry::ResDef;
use select::Selector;
use serde_json::{Value, json};
use status::ApiError;
use std::collections::HashMap;
use std::convert::Infallible;
use std::io;
use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use util::now_secs;
use write::{Opts, Sub};
const MAX_BODY: usize = 3 << 20;
const MAX_CONNS: usize = 128;
const MAX_CONNS_PER_IP: u32 = 64;
const MAX_WATCH_SECS: u64 = 3600;
const HEADER_TIMEOUT: Duration = Duration::from_secs(30);
pub struct Config {
pub listen: String,
pub token: Option<String>,
pub cgroup_root: String,
pub poll_interval: Duration,
pub watch_log_bytes: usize,
pub bookmark_interval: Duration,
pub allow_host_paths: Arc<Vec<PathBuf>>,
}
impl Default for Config {
fn default() -> Self {
Self {
listen: "127.0.0.1:6443".into(),
token: None,
cgroup_root: "/sys/fs/cgroup".into(),
poll_interval: Duration::from_secs(2),
watch_log_bytes: 512 * 1024,
bookmark_interval: Duration::from_secs(60),
allow_host_paths: Arc::default(),
}
}
}
pub struct Authn {
pub static_tokens: StaticTokens,
pub signer: Option<Signer>,
}
pub struct App<R> {
store: Arc<MemStore>,
rt: R,
host: HostInfo,
node_ip: String,
cfg: Config,
metrics: Mutex<sync::Metrics>,
auth: Option<Authn>,
conns: Mutex<HashMap<IpAddr, u32>>,
}
impl<R: Runtime> App<R> {
pub fn new(cfg: Config, rt: R, store: Arc<MemStore>) -> Arc<Self> {
App::with_auth(cfg, rt, store, None)
}
pub fn with_auth(cfg: Config, rt: R, store: Arc<MemStore>, auth: Option<Authn>) -> Arc<Self> {
let node_ip = std::env::var("KRAB_NODE_IP").unwrap_or_else(|_| "127.0.0.1".into());
sync::ensure_base_namespaces(&store);
Arc::new(App {
store,
rt,
host: host_info(),
node_ip,
cfg,
metrics: Mutex::new(sync::Metrics::default()),
auth,
conns: Mutex::new(HashMap::new()),
})
}
pub fn store(&self) -> Arc<MemStore> {
self.store.clone()
}
}
pub fn new_store(cfg: &Config) -> Arc<MemStore> {
MemStore::new(cfg.watch_log_bytes, 256)
}
#[derive(Default)]
struct Query {
watch: bool,
rv: Option<u64>,
label: Selector,
field: Selector,
label_s: String,
field_s: String,
timeout: u64,
follow: bool,
tail: Option<usize>,
timestamps: bool,
since_seconds: Option<u64>,
limit: Option<usize>,
cont: Option<String>,
bookmarks: bool,
dry: bool,
manager: Option<String>,
force: bool,
propagation: Option<String>,
container: Option<String>,
}
fn hex_val(c: u8) -> Option<u8> {
(c as char).to_digit(16).map(|d| d as u8)
}
fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
match b[i] {
b'%' if i + 2 < b.len() => {
if let (Some(h), Some(l)) = (hex_val(b[i + 1]), hex_val(b[i + 2])) {
out.push(h << 4 | l);
i += 3;
continue;
}
out.push(b'%');
i += 1;
}
b'+' => {
out.push(b' ');
i += 1;
}
c => {
out.push(c);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
fn parse_query(q: Option<&str>) -> Query {
let mut out = Query {
timeout: 1800,
..Default::default()
};
for pair in q.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
let v = percent_decode(v);
match k {
"watch" => out.watch = v == "true" || v == "1",
"resourceVersion" => out.rv = v.parse().ok(),
"labelSelector" => {
out.label = Selector::parse(&v);
out.label_s = v;
}
"fieldSelector" => {
out.field = Selector::parse(&v);
out.field_s = v;
}
"timeoutSeconds" => out.timeout = v.parse().unwrap_or(1800).min(MAX_WATCH_SECS),
"follow" => out.follow = v == "true",
"tailLines" => out.tail = v.parse().ok(),
"timestamps" => out.timestamps = v == "true",
"sinceSeconds" => out.since_seconds = v.parse().ok(),
"limit" => out.limit = v.parse().ok().filter(|n| *n > 0),
"continue" => out.cont = Some(v).filter(|s| !s.is_empty()),
"allowWatchBookmarks" => out.bookmarks = v == "true" || v == "1",
"dryRun" => out.dry = v == "All",
"fieldManager" => out.manager = Some(v),
"force" => out.force = v == "true" || v == "1",
"propagationPolicy" => out.propagation = Some(v),
"container" => out.container = Some(v).filter(|c| !c.is_empty()),
_ => {}
}
}
out
}
impl Query {
fn opts(&self, allow_host: &Arc<Vec<PathBuf>>) -> Opts {
Opts {
dry: self.dry,
manager: self.manager.clone(),
force: self.force,
propagation: self.propagation.clone(),
allow_host: allow_host.clone(),
}
}
}
fn respond(status: StatusCode, ctype: &str, body: impl Into<Bytes>) -> Response<Body> {
Response::builder()
.status(status)
.header("Content-Type", ctype)
.body(Body::full(body))
.unwrap()
}
fn json_ok(v: &Value) -> Response<Body> {
respond(
StatusCode::OK,
"application/json",
serde_json::to_vec(v).unwrap(),
)
}
fn json_code(code: u16, b: Bytes) -> Response<Body> {
respond(
StatusCode::from_u16(code).unwrap_or(StatusCode::OK),
"application/json",
b,
)
}
fn unreadable() -> ApiError {
ApiError::new(500, "InternalError", "stored object could not be decrypted")
}
fn error(e: ApiError) -> Response<Body> {
respond(
StatusCode::from_u16(e.code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
"application/json",
serde_json::to_vec(&e.to_json()).unwrap(),
)
}
fn failure(code: u16, reason: &'static str, message: &str) -> Response<Body> {
error(ApiError::new(code, reason, message))
}
fn not_found_kind(kind: &str, name: &str) -> Response<Body> {
let plural = kind.to_lowercase() + "s";
let mut e = ApiError::new(404, "NotFound", format!("{plural} \"{name}\" not found"));
e.details = json!({"name": name, "kind": plural});
error(e)
}
fn header<'a>(req: &'a Request<Incoming>, name: &str) -> &'a str {
req.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
}
pub async fn run<R: Runtime>(cfg: Config, rt: R) -> io::Result<()> {
let store = new_store(&cfg);
run_with_store(cfg, rt, store).await
}
pub async fn run_with_store<R: Runtime>(
cfg: Config,
rt: R,
store: Arc<MemStore>,
) -> io::Result<()> {
let listener = TcpListener::bind(&cfg.listen).await?;
serve(App::new(cfg, rt, store), listener).await
}
struct ConnSlot<R: Runtime> {
app: Arc<App<R>>,
ip: IpAddr,
}
impl<R: Runtime> Drop for ConnSlot<R> {
fn drop(&mut self) {
let mut m = self
.app
.conns
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(n) = m.get_mut(&self.ip) {
*n -= 1;
if *n == 0 {
m.remove(&self.ip);
}
}
}
}
fn conn_slot<R: Runtime>(app: &Arc<App<R>>, ip: IpAddr) -> Option<ConnSlot<R>> {
let mut m = app.conns.lock().unwrap_or_else(PoisonError::into_inner);
let n = m.entry(ip).or_insert(0);
if *n >= MAX_CONNS_PER_IP {
return None;
}
*n += 1;
Some(ConnSlot {
app: app.clone(),
ip,
})
}
pub async fn serve<R: Runtime>(app: Arc<App<R>>, listener: TcpListener) -> io::Result<()> {
spawn_background(&app);
let permits = Arc::new(tokio::sync::Semaphore::new(MAX_CONNS));
loop {
let (stream, addr) = listener.accept().await?;
let Ok(permit) = permits.clone().try_acquire_owned() else {
continue;
};
let Some(slot) = conn_slot(&app, addr.ip()) else {
continue;
};
let app = app.clone();
tokio::spawn(async move {
let _permit = permit;
let _slot = slot;
serve_conn(app, stream, None).await;
});
}
}
pub async fn serve_tls<R: Runtime>(
app: Arc<App<R>>,
listener: TcpListener,
pki: &Pki,
) -> io::Result<()> {
let acceptor = krab_tls::tls::acceptor(pki).map_err(|e| io::Error::other(e.to_string()))?;
spawn_background(&app);
let permits = Arc::new(tokio::sync::Semaphore::new(MAX_CONNS));
loop {
let (stream, addr) = listener.accept().await?;
let Ok(permit) = permits.clone().try_acquire_owned() else {
continue;
};
let Some(slot) = conn_slot(&app, addr.ip()) else {
continue;
};
let app = app.clone();
let acceptor = acceptor.clone();
tokio::spawn(async move {
let _permit = permit;
let _slot = 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);
serve_conn(app, tls, peer).await;
});
}
}
fn spawn_background<R: Runtime>(app: &Arc<App<R>>) {
tokio::spawn(sync::run(app.clone()));
tokio::spawn(gc::run(app.store.clone()));
}
async fn serve_conn<R, S>(app: Arc<App<R>>, stream: S, peer: Option<Identity>)
where
R: Runtime,
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let svc = hyper::service::service_fn(move |req| {
let app = app.clone();
let peer = peer.clone();
async move { Ok::<_, Infallible>(handle(app, req, peer).await) }
});
let mut b = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
b.http1()
.timer(TokioTimer::new())
.header_read_timeout(HEADER_TIMEOUT);
b.http2()
.timer(TokioTimer::new())
.max_concurrent_streams(64)
.keep_alive_interval(Duration::from_secs(60))
.keep_alive_timeout(Duration::from_secs(20));
let _ = b
.serve_connection_with_upgrades(TokioIo::new(stream), svc)
.await;
}
fn bearer(req: &Request<Incoming>) -> Option<&str> {
req.headers()
.get("authorization")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
}
fn is_admin(id: &Identity) -> bool {
id.groups.iter().any(|g| g == "system:masters")
}
fn public_path(p: &str) -> bool {
matches!(p, "/healthz" | "/livez" | "/readyz" | "/version")
|| p.starts_with("/healthz/")
|| p.starts_with("/livez/")
|| p.starts_with("/readyz/")
}
fn authenticate<R>(app: &App<R>, req: &Request<Incoming>, peer: Option<&Identity>) -> Option<bool> {
if app.auth.is_some()
&& let Some(id) = peer
{
return Some(is_admin(id));
}
if let Some(t) = &app.cfg.token {
return bearer(req)
.is_some_and(|b| krab_tls::tokens::ct_eq(b.as_bytes(), t.as_bytes()))
.then_some(true);
}
if let Some(auth) = &app.auth {
let b = bearer(req)?;
if let Some(id) = auth.static_tokens.authenticate(b) {
return Some(is_admin(&id));
}
if let Some(c) = auth.signer.as_ref().and_then(|s| s.verify(b).ok()) {
return Some(is_admin(&c.identity()));
}
return None;
}
Some(true)
}
const PRIVILEGED_SUBS: [&str; 5] = ["log", "exec", "attach", "portforward", "proxy"];
fn reader_allowed(verb: &str, resource: &str, sub: &str) -> bool {
matches!(verb, "get" | "list" | "watch")
&& resource != "secrets"
&& !PRIVILEGED_SUBS.contains(&sub)
}
fn reader_request_allowed(req: &Request<Incoming>, segs: &[&str]) -> bool {
if req.method() == Method::POST
&& segs
== [
"apis",
"authorization.k8s.io",
"v1",
"selfsubjectaccessreviews",
]
{
return true;
}
(req.method() == Method::GET || req.method() == Method::HEAD)
&& !segs.contains(&"secrets")
&& !segs.last().is_some_and(|s| PRIVILEGED_SUBS.contains(s))
}
fn discovery_response(accept: &str, legacy: bool, fallback: Value) -> Response<Body> {
let mut r = match discovery::aggregated_version(accept) {
Some(v) => respond(
StatusCode::OK,
&discovery::content_type(v),
serde_json::to_vec(&discovery::aggregated(legacy, v)).unwrap(),
),
None => json_ok(&fallback),
};
r.headers_mut()
.insert("Vary", hyper::header::HeaderValue::from_static("Accept"));
r
}
fn opt_json(v: Option<Value>) -> Response<Body> {
match v {
Some(v) => json_ok(&v),
None => error(ApiError::not_found_path()),
}
}
async fn handle<R: Runtime>(
app: Arc<App<R>>,
req: Request<Incoming>,
peer: Option<Identity>,
) -> Response<Body> {
let admin = if public_path(req.uri().path()) {
true
} else {
match authenticate(&app, &req, peer.as_ref()) {
Some(a) => a,
None => return failure(401, "Unauthorized", "Unauthorized"),
}
};
let path = req.uri().path().trim_end_matches('/').to_string();
let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
if !admin && !reader_request_allowed(&req, &segs) {
return failure(
403,
"Forbidden",
"forbidden: only members of system:masters may modify objects, read secrets or use log, exec, attach and portforward",
);
}
let q = parse_query(req.uri().query());
let accept = header(&req, "accept").to_string();
let table = accept.contains("as=Table");
let get = req.method() == Method::GET || req.method() == Method::HEAD;
match segs.as_slice() {
["api", "v1", rest @ ..] if !rest.is_empty() => {
resource(&app, req, "", "v1", rest, &q, table).await
}
["apis", "metrics.k8s.io", "v1beta1", rest @ ..] if !rest.is_empty() => {
if get {
metrics_api(&app, rest, &q)
} else {
error(ApiError::method_not_allowed())
}
}
[
"apis",
"authorization.k8s.io",
"v1",
"selfsubjectaccessreviews",
] => {
if req.method() == Method::POST {
ssar(req, admin).await
} else {
error(ApiError::method_not_allowed())
}
}
["apis", g, v, rest @ ..] if !rest.is_empty() => {
let (g, v) = (g.to_string(), v.to_string());
resource(&app, req, &g, &v, rest, &q, table).await
}
_ if !get => error(ApiError::method_not_allowed()),
[] => json_ok(
&json!({"paths": ["/api", "/api/v1", "/apis", "/healthz", "/livez", "/readyz", "/version", "/metrics", "/openapi/v3"]}),
),
["healthz" | "livez" | "readyz", ..] => respond(StatusCode::OK, "text/plain", "ok"),
["version"] => json_ok(
&json!({"major": "1", "minor": "34", "gitVersion": objects::VERSION, "gitCommit": "krab", "gitTreeState": "clean", "buildDate": "2026-11-30T00:00:00Z", "goVersion": "rust", "compiler": "rustc", "platform": format!("linux/{}", app.host.arch)}),
),
["metrics"] => prometheus(&app),
["openapi", "v3"] => json_ok(&discovery::openapi_index()),
["openapi", "v3", "api", "v1"] => opt_json(discovery::openapi_doc("", "v1")),
["openapi", "v3", "apis", g, v] => opt_json(discovery::openapi_doc(g, v)),
["openapi", "v2"] | ["swagger.json"] => json_ok(
&json!({"swagger": "2.0", "info": {"title": "krab", "version": objects::VERSION}, "paths": {}}),
),
["api"] => discovery_response(
&accept,
true,
json!({"kind": "APIVersions", "versions": ["v1"], "serverAddressByClientCIDRs": [{"clientCIDR": "0.0.0.0/0", "serverAddress": ""}]}),
),
["apis"] => discovery_response(&accept, false, discovery::api_group_list()),
["api", "v1"] => opt_json(discovery::resource_list("", "v1")),
["apis", g] => opt_json(discovery::api_group(g)),
["apis", g, v] => opt_json(discovery::resource_list(g, v)),
_ => error(ApiError::not_found_path()),
}
}
async fn read_body(req: Request<Incoming>) -> Result<Bytes, ApiError> {
match http_body_util::Limited::new(req.into_body(), MAX_BODY)
.collect()
.await
{
Ok(b) => Ok(b.to_bytes()),
Err(e) if e.is::<http_body_util::LengthLimitError>() => Err(ApiError::new(
413,
"RequestEntityTooLarge",
"Request entity too large: limit is 3145728",
)),
Err(_) => Err(ApiError::bad_request("unreadable body")),
}
}
async fn ssar(req: Request<Incoming>, admin: bool) -> Response<Body> {
let bytes = match read_body(req).await {
Ok(b) => b,
Err(e) => return error(e),
};
let mut v: Value = serde_json::from_slice(&bytes)
.ok()
.filter(Value::is_object)
.unwrap_or_else(|| json!({}));
let attr = |k: &str| -> String {
v.pointer(&format!("/spec/resourceAttributes/{k}"))
.or_else(|| v.pointer(&format!("/spec/nonResourceAttributes/{k}")))
.and_then(Value::as_str)
.unwrap_or("")
.to_string()
};
let allowed = admin || reader_allowed(&attr("verb"), &attr("resource"), &attr("subresource"));
let reason = if admin {
"system:masters may perform any action"
} else if allowed {
"authenticated users may read non-secret objects"
} else {
"only system:masters may perform this action"
};
v["apiVersion"] = json!("authorization.k8s.io/v1");
v["kind"] = json!("SelfSubjectAccessReview");
v["status"] = json!({"allowed": allowed, "reason": reason});
respond(
StatusCode::CREATED,
"application/json",
serde_json::to_vec(&v).unwrap(),
)
}
fn parse_body(ctype: &str, b: &[u8]) -> Result<Value, ApiError> {
if ctype.contains("protobuf") {
return proto::decode(b).map_err(ApiError::unsupported_media);
}
if !ctype.is_empty() && !ctype.contains("json") && !ctype.contains("yaml") {
return Err(ApiError::unsupported_media(format!(
"the body of the request was in an unknown format - accepted media types include: application/json, application/yaml, application/vnd.kubernetes.protobuf (got {ctype})"
)));
}
write::parse_json(b)
}
struct Target {
def: &'static ResDef,
ns: Option<String>,
name: Option<String>,
sub: Option<String>,
}
fn target(group: &str, version: &str, rest: &[&str]) -> Result<Target, ApiError> {
let (ns, rest) = if rest.len() >= 3
&& rest[0] == "namespaces"
&& !(rest.len() == 3 && matches!(rest[2], "status" | "finalize"))
{
(Some(rest[1].to_string()), &rest[2..])
} else {
(None, rest)
};
let (plural, name, sub) = match rest {
[p] => (*p, None, None),
[p, n] => (*p, Some(n.to_string()), None),
[p, n, s] => (*p, Some(n.to_string()), Some(s.to_string())),
_ => return Err(ApiError::not_found_path()),
};
let def = registry::find(group, version, plural)
.filter(|d| d.stored)
.ok_or_else(ApiError::not_found_path)?;
if (ns.is_some() && !def.namespaced) || (ns.is_none() && def.namespaced && name.is_some()) {
return Err(ApiError::not_found_path());
}
if sub.as_deref().is_some_and(|s| !def.has_sub(s)) {
return Err(ApiError::not_found_path());
}
Ok(Target { def, ns, name, sub })
}
async fn resource<R: Runtime>(
app: &Arc<App<R>>,
req: Request<Incoming>,
group: &str,
version: &str,
rest: &[&str],
q: &Query,
table: bool,
) -> Response<Body> {
let t = match target(group, version, rest) {
Ok(t) => t,
Err(e) => return error(e),
};
let def = t.def;
let ns = t.ns.as_deref();
let sub = t.sub.as_deref();
let method = req.method().clone();
let ctype = header(&req, "content-type").to_string();
let deny = || error(ApiError::method_not_allowed());
let store = &app.store;
if t.name.is_some()
&& sub.is_some_and(|s| matches!(s, "exec" | "attach" | "portforward"))
&& (method == Method::GET || method == Method::POST)
{
let ns = ns.unwrap_or("default");
let name = t.name.as_deref().unwrap();
if header(&req, "upgrade").is_empty() {
return failure(
400,
"BadRequest",
&format!("{} requires an upgrade request", sub.unwrap()),
);
}
return stream::handle(app.clone(), req, ns, name, sub.unwrap()).await;
}
let out = match (&method, t.name.as_deref(), sub) {
(&Method::GET | &Method::HEAD, None, None) => {
if !def.can(if q.watch { "watch" } else { "list" }) {
return deny();
}
return list_or_watch(app, def, ns, q, table);
}
(&Method::GET | &Method::HEAD, Some(n), None | Some("status")) => {
return get_one(app, def, ns, n, table);
}
(&Method::GET, Some(n), Some("log")) => {
return pod_log(app, ns.unwrap_or(""), n, q).await;
}
(&Method::GET, Some(n), Some("scale")) => match store.get(&def.key(ns, n)) {
Some(b) => {
let v: Value = serde_json::from_slice(&b).unwrap_or(Value::Null);
return json_ok(&write::scale_view(&v));
}
None => Err(status::not_found(def, n)),
},
(&Method::POST, None, None) if def.can("create") => match read_body(req).await {
Ok(b) => parse_body(&ctype, &b)
.and_then(|v| write::create(store, def, ns, v, &q.opts(&app.cfg.allow_host_paths))),
Err(e) => Err(e),
},
(&Method::PUT, Some(n), None | Some("status") | Some("scale")) if def.can("update") => {
match read_body(req).await {
Ok(b) => parse_body(&ctype, &b).and_then(|v| {
write::update(
store,
def,
ns,
n,
Sub::from(sub),
v,
&q.opts(&app.cfg.allow_host_paths),
)
}),
Err(e) => Err(e),
}
}
(&Method::PATCH, Some(n), None | Some("status") | Some("scale")) if def.can("patch") => {
match read_body(req).await {
Ok(b) => write::patch(
store,
def,
ns,
n,
Sub::from(sub),
&ctype,
&b,
&q.opts(&app.cfg.allow_host_paths),
),
Err(e) => Err(e),
}
}
(&Method::DELETE, Some(n), None) if def.can("delete") => match read_body(req).await {
Ok(b) => {
let mut opts = q.opts(&app.cfg.allow_host_paths);
let pre = write::delete_opts(&b, &mut opts);
write::delete(store, def, ns, n, &opts, pre)
}
Err(e) => Err(e),
},
(&Method::DELETE, None, None) if def.can("deletecollection") => {
let mut opts = q.opts(&app.cfg.allow_host_paths);
if let Ok(b) = read_body(req).await {
write::delete_opts(&b, &mut opts);
}
return delete_collection(app, def, ns, q, &opts);
}
_ => return deny(),
};
match out {
Ok((code, b)) => json_code(code, b),
Err(e) => error(e),
}
}
fn get_one<R: Runtime>(
app: &Arc<App<R>>,
def: &ResDef,
ns: Option<&str>,
name: &str,
table: bool,
) -> Response<Body> {
let Some(obj) = app.store.get(&def.key(ns, name)) else {
return error(status::not_found(def, name));
};
if obj.is_empty() {
return error(unreadable());
}
if !table {
return respond(StatusCode::OK, "application/json", obj);
}
let v: Value = serde_json::from_slice(&obj).unwrap_or(Value::Null);
let rv = v
.pointer("/metadata/resourceVersion")
.and_then(Value::as_str)
.unwrap_or("0")
.to_string();
json_ok(&table::table(def.kind, &rv, &[v], true))
}
fn keep(q: &Query, v: &Value) -> bool {
(q.label.is_empty() || q.label.matches_labels(v))
&& (q.field.is_empty() || q.field.matches_fields(v))
}
fn hex_encode(s: &str) -> String {
s.bytes().map(|b| format!("{b:02x}")).collect()
}
fn hex_decode(s: &str) -> Option<String> {
if !s.len().is_multiple_of(2) {
return None;
}
let bytes: Option<Vec<u8>> = (0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
.collect();
String::from_utf8(bytes?).ok()
}
fn delete_collection<R: Runtime>(
app: &Arc<App<R>>,
def: &'static ResDef,
ns: Option<&str>,
q: &Query,
opts: &Opts,
) -> Response<Body> {
let snap = app.store.list(&def.prefix(ns));
let mut items = Vec::new();
for (_, b) in snap.items {
let Ok(v) = serde_json::from_slice::<Value>(&b) else {
continue;
};
if !keep(q, &v) || objects_util::is_docker(&v) {
continue;
}
let name = v
.pointer("/metadata/name")
.and_then(Value::as_str)
.unwrap_or("");
let ons = v.pointer("/metadata/namespace").and_then(Value::as_str);
if let Ok((_, d)) = write::delete(&app.store, def, ons, name, opts, (None, None))
&& let Ok(dv) = serde_json::from_slice::<Value>(&d)
{
items.push(dv);
}
}
json_ok(
&json!({"kind": format!("{}List", def.kind), "apiVersion": def.api_version(), "metadata": {"resourceVersion": app.store.rev().to_string()}, "items": items}),
)
}
fn list_or_watch<R: Runtime>(
app: &Arc<App<R>>,
def: &'static ResDef,
ns: Option<&str>,
q: &Query,
table: bool,
) -> Response<Body> {
let prefix = def.prefix(ns);
if q.watch {
return start_watch(app, def, prefix, q, table);
}
let snap = app.store.list(&prefix);
if snap.items.iter().any(|(_, b)| b.is_empty()) {
return error(unreadable());
}
let after = q.cont.as_deref().and_then(hex_decode);
let filtered = !q.label.is_empty() || !q.field.is_empty();
let limit = q.limit.unwrap_or(usize::MAX);
let mut raw: Vec<&Bytes> = Vec::new();
let mut objs: Vec<Value> = Vec::new();
let mut last: Option<&str> = None;
let mut more = false;
for (k, b) in snap
.items
.iter()
.filter(|(k, _)| after.as_deref().is_none_or(|a| k.as_ref() > a))
{
let parsed = if filtered || table {
match serde_json::from_slice::<Value>(b) {
Ok(v) if keep(q, &v) => Some(v),
_ => continue,
}
} else {
None
};
if raw.len() + objs.len() == limit {
more = true;
break;
}
match parsed {
Some(v) => objs.push(v),
None => raw.push(b),
}
last = Some(k);
}
let cont = if more {
last.map(hex_encode).unwrap_or_default()
} else {
String::new()
};
let list_kind = format!("{}List", def.kind);
let av = def.api_version();
if table {
let mut t = table::table(def.kind, &snap.rev.to_string(), &objs, true);
if !cont.is_empty() {
t["metadata"]["continue"] = json!(cont);
}
return json_ok(&t);
}
let meta = if cont.is_empty() {
json!({"resourceVersion": snap.rev.to_string()})
} else {
json!({"resourceVersion": snap.rev.to_string(), "continue": cont})
};
if !filtered {
let mut out = Vec::with_capacity(raw.iter().map(|b| b.len() + 1).sum::<usize>() + 160);
out.extend_from_slice(
format!(
"{{\"kind\":\"{list_kind}\",\"apiVersion\":\"{av}\",\"metadata\":{meta},\"items\":["
)
.as_bytes(),
);
for (i, b) in raw.iter().enumerate() {
if i > 0 {
out.push(b',');
}
out.extend_from_slice(b);
}
out.extend_from_slice(b"]}");
return respond(StatusCode::OK, "application/json", out);
}
json_ok(&json!({"kind": list_kind, "apiVersion": av, "metadata": meta, "items": objs}))
}
fn start_watch<R: Runtime>(
app: &Arc<App<R>>,
def: &'static ResDef,
prefix: String,
q: &Query,
table: bool,
) -> Response<Body> {
let w = match app.store.watch(&prefix, q.rv) {
Ok(w) => w,
Err(WatchError::Expired { oldest }) => {
let line = format!(
"{{\"type\":\"ERROR\",\"object\":{{\"kind\":\"Status\",\"apiVersion\":\"v1\",\"metadata\":{{}},\"status\":\"Failure\",\"message\":\"too old resource version: {} ({})\",\"reason\":\"Expired\",\"code\":410}}}}\n",
q.rv.unwrap_or(0),
oldest.saturating_sub(1)
);
return respond(StatusCode::OK, "application/json", line);
}
};
let (tx, rx) = mpsc::channel::<Bytes>(16);
let filter_needed = !q.label.is_empty() || !q.field.is_empty() || table;
let timeout = Duration::from_secs(q.timeout.max(1));
let (lbl, fld) = (q.label_s.clone(), q.field_s.clone());
let kind = def.kind;
let av = def.api_version();
let bookmarks = q.bookmarks;
let bm_every = app.cfg.bookmark_interval.max(Duration::from_millis(100));
tokio::spawn(async move {
let q = Query {
label: Selector::parse(&lbl),
field: Selector::parse(&fld),
..Default::default()
};
let mut first = true;
let mut rxb = w.rx;
let last = w.last_rev;
let mut seen = last;
let send = |ev: krab_store::Event, first: bool| -> Option<Bytes> {
if ev.obj.is_empty() {
let mut line =
serde_json::to_vec(&json!({"type": "ERROR", "object": unreadable().to_json()}))
.ok()?;
line.push(b'\n');
return Some(Bytes::from(line));
}
if !filter_needed {
let mut line = Vec::with_capacity(ev.obj.len() + 40);
line.extend_from_slice(
format!("{{\"type\":\"{}\",\"object\":", ev.kind.as_str()).as_bytes(),
);
line.extend_from_slice(&ev.obj);
line.extend_from_slice(b"}\n");
return Some(Bytes::from(line));
}
let v: Value = serde_json::from_slice(&ev.obj).ok()?;
if !keep(&q, &v) {
return None;
}
let obj = if table {
table::table(kind, &ev.rev.to_string(), &[v], first)
} else {
v
};
let mut line =
serde_json::to_vec(&json!({"type": ev.kind.as_str(), "object": obj})).ok()?;
line.push(b'\n');
Some(Bytes::from(line))
};
for ev in w.initial {
if let Some(b) = send(ev, first) {
first = false;
if tx.send(b).await.is_err() {
return;
}
}
}
let deadline = tokio::time::sleep(timeout);
tokio::pin!(deadline);
let mut bm = tokio::time::interval_at(tokio::time::Instant::now() + bm_every, bm_every);
loop {
tokio::select! {
_ = &mut deadline => break,
_ = bm.tick(), if bookmarks => {
let line = format!("{{\"type\":\"BOOKMARK\",\"object\":{{\"kind\":\"{kind}\",\"apiVersion\":\"{av}\",\"metadata\":{{\"resourceVersion\":\"{seen}\"}}}}}}\n");
if tx.send(Bytes::from(line)).await.is_err() {
return;
}
}
got = rxb.recv() => match got {
Ok(ev) => {
if ev.rev <= last {
continue;
}
seen = ev.rev;
if !ev.key.starts_with(&prefix) {
continue;
}
if let Some(b) = send(ev, first) {
first = false;
if tx.send(b).await.is_err() {
return;
}
}
}
Err(_) => break,
}
}
}
});
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/json")
.body(Body::Chan(rx))
.unwrap()
}
async fn pod_log<R: Runtime>(app: &Arc<App<R>>, ns: &str, name: &str, q: &Query) -> Response<Body> {
let Some(obj) = app.store.get(&format!("pods/{ns}/{name}")) else {
return not_found_kind("Pod", name);
};
let v: Value = serde_json::from_slice(&obj).unwrap_or(Value::Null);
let info = match pod_container(app, &v, q.container.as_deref()).await {
Ok((info, _)) => info,
Err(e) => return failure(400, "BadRequest", &e),
};
let opts = LogOpts {
tail: q.tail,
follow: q.follow,
timestamps: q.timestamps,
since_seconds: q.since_seconds,
};
match app.rt.logs(&info, &opts).await {
Ok(rx) => Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "text/plain")
.body(Body::Chan(rx))
.unwrap(),
Err(e) => failure(500, "InternalError", &format!("log stream failed: {e}")),
}
}
fn docker_id_ok(id: &str) -> bool {
(12..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_hexdigit())
}
pub(crate) async fn pod_container<R: Runtime>(
app: &App<R>,
pod: &Value,
want: Option<&str>,
) -> Result<(ContainerInfo, bool), String> {
let name = pod
.pointer("/metadata/name")
.and_then(Value::as_str)
.unwrap_or("");
let not_running = || format!("container for pod \"{name}\" is not running");
if objects_util::is_docker(pod) {
let id = pod
.pointer("/metadata/annotations/krab.io~1container-id")
.and_then(Value::as_str)
.filter(|id| docker_id_ok(id))
.ok_or_else(not_running)?;
let mut info = ContainerInfo {
id: id.to_string(),
..Default::default()
};
app.rt.inspect(&mut info).await.map_err(|_| not_running())?;
if is_managed(&info) || info.id != id {
return Err(not_running());
}
return Ok((info, false));
}
let uid = pod
.pointer("/metadata/uid")
.and_then(Value::as_str)
.unwrap_or("");
let first = pod
.pointer("/spec/containers/0/name")
.and_then(Value::as_str)
.unwrap_or("");
let cname = want.unwrap_or(first);
let list = app.rt.list().await.map_err(|e| e.to_string())?;
let mut info = list
.into_iter()
.find(|c| {
is_managed(c)
&& !uid.is_empty()
&& c.labels.get("krab.io/uid").map(String::as_str) == Some(uid)
&& c.labels.get("krab.io/container").map(String::as_str) == Some(cname)
})
.ok_or_else(not_running)?;
app.rt.inspect(&mut info).await.map_err(|_| not_running())?;
if !is_managed(&info) {
return Err(not_running());
}
Ok((info, true))
}
fn quantity_cpu(n: u64) -> String {
format!("{n}n")
}
fn metrics_api<R: Runtime>(app: &Arc<App<R>>, segs: &[&str], q: &Query) -> Response<Body> {
let m = app.metrics.lock().unwrap_or_else(PoisonError::into_inner);
let window = format!("{}s", m.window_secs.max(10));
let ts = util::rfc3339(now_secs());
let node_item = |_: ()| {
m.node_cpu_nano.map(|cpu| json!({"kind": "NodeMetrics", "apiVersion": "metrics.k8s.io/v1beta1", "metadata": {"name": app.host.hostname, "creationTimestamp": ts, "labels": {"kubernetes.io/hostname": app.host.hostname}}, "timestamp": ts, "window": window, "usage": {"cpu": quantity_cpu(cpu), "memory": format!("{}Ki", m.node_mem_bytes / 1024)}}))
};
let pod_items = |ns: Option<&str>| -> Vec<Value> {
let mut out = Vec::new();
for (key, s) in &m.pods {
let Some(cpu) = s.cpu_nano else { continue };
let mut parts = key.splitn(3, '/');
let (_, pns, pname) = (
parts.next(),
parts.next().unwrap_or(""),
parts.next().unwrap_or(""),
);
if ns.is_some_and(|n| n != pns) {
continue;
}
let item = json!({"kind": "PodMetrics", "apiVersion": "metrics.k8s.io/v1beta1", "metadata": {"name": pname, "namespace": pns, "creationTimestamp": ts}, "timestamp": ts, "window": window, "containers": [{"name": pname, "usage": {"cpu": quantity_cpu(cpu), "memory": format!("{}Ki", s.mem_bytes / 1024)}}]});
if keep(q, &item) {
out.push(item);
}
}
out.sort_by(|a, b| {
a["metadata"]["name"]
.as_str()
.cmp(&b["metadata"]["name"].as_str())
});
out
};
let list = |kind: &str, items: Vec<Value>| json!({"kind": kind, "apiVersion": "metrics.k8s.io/v1beta1", "metadata": {}, "items": items});
match segs {
["nodes"] => json_ok(&list(
"NodeMetricsList",
node_item(()).into_iter().collect(),
)),
["nodes", name] => match node_item(()) {
Some(v) if *name == app.host.hostname => json_ok(&v),
_ => not_found_kind("NodeMetrics", name),
},
["pods"] => json_ok(&list("PodMetricsList", pod_items(None))),
["namespaces", ns, "pods"] => json_ok(&list("PodMetricsList", pod_items(Some(ns)))),
["namespaces", ns, "pods", name] => match pod_items(Some(ns))
.into_iter()
.find(|v| v["metadata"]["name"] == *name)
{
Some(v) => json_ok(&v),
None => not_found_kind("PodMetrics", name),
},
_ => error(ApiError::not_found_path()),
}
}
fn prometheus<R: Runtime>(app: &Arc<App<R>>) -> Response<Body> {
let pods = app.store.list("pods/").items.len();
let out = format!(
"# TYPE krab_process_resident_memory_bytes gauge\nkrab_process_resident_memory_bytes {}\n# TYPE krab_store_revision gauge\nkrab_store_revision {}\n# TYPE krab_store_watch_log_bytes gauge\nkrab_store_watch_log_bytes {}\n# TYPE krab_pods gauge\nkrab_pods {}\n# TYPE krab_build_info gauge\nkrab_build_info{{version=\"{}\"}} 1\n",
rss_kib() * 1024,
app.store.rev(),
app.store.log_bytes(),
pods,
objects::VERSION
);
respond(StatusCode::OK, "text/plain; version=0.0.4", out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn percent_decode_is_byte_safe() {
assert_eq!(percent_decode("%aé"), "%aé");
assert_eq!(percent_decode("é%4"), "é%4");
assert_eq!(percent_decode("%é%%41"), "%é%A");
assert_eq!(percent_decode("a%20b+c"), "a b c");
let q = parse_query(Some(
"timeoutSeconds=999999999&labelSelector=%aé&container=c",
));
assert_eq!(q.timeout, MAX_WATCH_SECS);
assert_eq!(q.container.as_deref(), Some("c"));
}
#[test]
fn docker_ids_must_be_hex() {
assert!(docker_id_ok("abcdef012345"));
assert!(!docker_id_ok("victim/archive?path=/etc/shadow&"));
assert!(!docker_id_ok("abc"));
}
}