Skip to main content

krab_api/
kubelet_bridge.rs

1use crate::{App, Body, parse_query, percent_decode, pod_log, stream};
2use hyper::body::Incoming;
3use hyper::{Request, Response};
4use krab_runtime::Runtime;
5use std::sync::Arc;
6
7#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8pub enum Op {
9    Logs,
10    Exec,
11    Attach,
12    PortForward,
13}
14
15fn flag(raw: &str, long: &str, short: &str) -> bool {
16    raw.split('&').any(|p| {
17        let (k, v) = p.split_once('=').unwrap_or((p, ""));
18        (k == long || k == short) && matches!(v, "1" | "true")
19    })
20}
21
22fn normalize(raw: &str, container: Option<&str>) -> String {
23    let mut out: Vec<String> = raw
24        .split('&')
25        .filter(|p| !p.is_empty())
26        .filter(|p| {
27            let k = p.split_once('=').map_or(*p, |(k, _)| k);
28            !matches!(
29                k,
30                "input" | "output" | "error" | "stdin" | "stdout" | "stderr" | "tty" | "container"
31            )
32        })
33        .map(str::to_string)
34        .collect();
35    for (long, short, name) in [
36        ("stdin", "input", "stdin"),
37        ("stdout", "output", "stdout"),
38        ("stderr", "error", "stderr"),
39        ("tty", "tty", "tty"),
40    ] {
41        out.push(format!("{name}={}", flag(raw, long, short)));
42    }
43    if let Some(c) = container {
44        out.push(format!("container={c}"));
45    }
46    out.join("&")
47}
48
49pub async fn handle<R: Runtime>(
50    app: &Arc<App<R>>,
51    mut req: Request<Incoming>,
52    ns: &str,
53    pod: &str,
54    container: Option<&str>,
55    op: Op,
56) -> Response<Body> {
57    let container = container.map(percent_decode).filter(|c| !c.is_empty());
58    let raw = req.uri().query().unwrap_or("").to_string();
59    match op {
60        Op::Logs => {
61            let mut q = parse_query(Some(&raw));
62            if container.is_some() {
63                q.container = container;
64            }
65            pod_log(app, ns, pod, &q).await
66        }
67        Op::Exec | Op::Attach | Op::PortForward => {
68            let sub = match op {
69                Op::Exec => "exec",
70                Op::Attach => "attach",
71                _ => "portforward",
72            };
73            let query = normalize(&raw, container.as_deref());
74            if let Ok(uri) = format!("{}?{query}", req.uri().path()).parse() {
75                *req.uri_mut() = uri;
76            }
77            stream::handle(app.clone(), req, ns, pod, sub).await
78        }
79    }
80}