Skip to main content

krab_controllers/kubelet/
probe.rs

1use crate::util::s;
2use krab_runtime::Runtime;
3use serde_json::Value;
4use std::time::Duration;
5use tokio::io::{AsyncReadExt, AsyncWriteExt};
6use tokio::net::TcpStream;
7use tokio::time::timeout;
8
9#[derive(Clone, Copy, PartialEq, Eq, Debug)]
10pub enum Kind {
11    Startup = 0,
12    Liveness = 1,
13    Readiness = 2,
14}
15
16impl Kind {
17    pub fn field(self) -> &'static str {
18        match self {
19            Kind::Startup => "startupProbe",
20            Kind::Liveness => "livenessProbe",
21            Kind::Readiness => "readinessProbe",
22        }
23    }
24
25    pub fn title(self) -> &'static str {
26        match self {
27            Kind::Startup => "Startup",
28            Kind::Liveness => "Liveness",
29            Kind::Readiness => "Readiness",
30        }
31    }
32}
33
34pub struct Params {
35    pub initial_delay: u64,
36    pub period: u64,
37    pub timeout: u64,
38    pub success: u32,
39    pub failure: u32,
40}
41
42pub fn params(p: &Value) -> Params {
43    let n = |k: &str, d: u64| p[k].as_u64().unwrap_or(d);
44    Params {
45        initial_delay: n("initialDelaySeconds", 0),
46        period: n("periodSeconds", 10).max(1),
47        timeout: n("timeoutSeconds", 1).max(1),
48        success: n("successThreshold", 1).max(1) as u32,
49        failure: n("failureThreshold", 3).max(1) as u32,
50    }
51}
52
53fn resolve_port(c: &Value, port: &Value) -> Option<u16> {
54    match port {
55        Value::Number(n) => n.as_u64().and_then(|p| u16::try_from(p).ok()),
56        Value::String(name) => name.parse().ok().or_else(|| {
57            c["ports"].as_array()?.iter().find_map(|p| {
58                (p["name"].as_str() == Some(name)).then(|| {
59                    p["containerPort"]
60                        .as_u64()
61                        .and_then(|x| u16::try_from(x).ok())
62                })?
63            })
64        }),
65        _ => None,
66    }
67}
68
69pub async fn run<R: Runtime>(
70    rt: &R,
71    id: &str,
72    c: &Value,
73    p: &Value,
74    pod_ip: &str,
75) -> Result<(), String> {
76    let prm = params(p);
77    let limit = Duration::from_secs(prm.timeout);
78    if let Some(cmd) = p["exec"]["command"].as_array() {
79        let cmd: Vec<String> = cmd
80            .iter()
81            .filter_map(|x| x.as_str().map(str::to_string))
82            .collect();
83        return match timeout(limit, rt.exec_run(id, &cmd)).await {
84            Err(_) => Err(format!("command timed out after {}s", prm.timeout)),
85            Ok(Err(e)) => Err(e.to_string()),
86            Ok(Ok((0, _))) => Ok(()),
87            Ok(Ok((code, out))) => Err(format!(
88                "command exited with {code}: {}",
89                String::from_utf8_lossy(&out[..out.len().min(256)]).trim()
90            )),
91        };
92    }
93    let (section, http) = if p["httpGet"].is_object() {
94        (&p["httpGet"], true)
95    } else if p["tcpSocket"].is_object() {
96        (&p["tcpSocket"], false)
97    } else if p["grpc"].is_object() {
98        (&p["grpc"], false)
99    } else {
100        return Ok(());
101    };
102    let port = resolve_port(c, &section["port"]).ok_or("invalid probe port")?;
103    let host = pod_ip;
104    let path = match s(section, "/path") {
105        "" => "/",
106        x => x,
107    };
108    let headers: Vec<(&str, &str)> = section["httpHeaders"]
109        .as_array()
110        .into_iter()
111        .flatten()
112        .map(|h| (s(h, "/name"), s(h, "/value")))
113        .collect();
114    let crlf = |x: &str| x.contains(['\r', '\n']);
115    if http
116        && (!path.starts_with('/')
117            || crlf(path)
118            || headers
119                .iter()
120                .any(|(k, v)| k.is_empty() || k.contains(':') || crlf(k) || crlf(v)))
121    {
122        return Err("invalid httpGet probe: path or headers contain forbidden characters".into());
123    }
124    if host.is_empty() {
125        return Err("pod has no IP".into());
126    }
127    let addr = format!("{host}:{port}");
128    let fut = async {
129        let mut stream = TcpStream::connect(&addr)
130            .await
131            .map_err(|e| format!("dial tcp {addr}: {e}"))?;
132        if !http || s(section, "/scheme").eq_ignore_ascii_case("https") {
133            return Ok(());
134        }
135        let mut req = format!(
136            "GET {path} HTTP/1.1\r\nHost: {addr}\r\nUser-Agent: kube-probe/1.34\r\nAccept: */*\r\nConnection: close\r\n"
137        );
138        for (k, v) in &headers {
139            req.push_str(&format!("{k}: {v}\r\n"));
140        }
141        req.push_str("\r\n");
142        stream
143            .write_all(req.as_bytes())
144            .await
145            .map_err(|e| e.to_string())?;
146        let mut buf = [0u8; 64];
147        let mut got = 0;
148        while got < 12 {
149            let n = stream
150                .read(&mut buf[got..])
151                .await
152                .map_err(|e| e.to_string())?;
153            if n == 0 {
154                break;
155            }
156            got += n;
157        }
158        let line = String::from_utf8_lossy(&buf[..got]);
159        let code: u16 = line
160            .split_whitespace()
161            .nth(1)
162            .and_then(|c| c.parse().ok())
163            .ok_or("malformed HTTP response")?;
164        if (200..400).contains(&code) {
165            Ok(())
166        } else {
167            Err(format!("HTTP probe failed with statuscode: {code}"))
168        }
169    };
170    match timeout(limit, fut).await {
171        Err(_) => Err(format!("Get \"http://{addr}\": context deadline exceeded")),
172        Ok(r) => r,
173    }
174}