1use crate::yaml;
2use bytes::{Buf, Bytes, BytesMut};
3use http_body_util::{BodyExt, Full};
4use hyper::body::Incoming;
5use hyper::{Method, Request};
6use hyper_util::rt::TokioIo;
7use krab_controllers::util::base64_decode;
8use rustls::crypto::ring::default_provider;
9use rustls::{ClientConfig, RootCertStore};
10use rustls_pki_types::pem::PemObject;
11use rustls_pki_types::{CertificateDer, PrivateKeyDer, ServerName};
12use serde_json::Value;
13use std::io;
14use std::sync::Arc;
15use std::time::Duration;
16use tokio::net::TcpStream;
17use tokio_rustls::TlsConnector;
18
19const MAX_BODY: usize = 16 << 20;
20const WATCH_IDLE: Duration = Duration::from_secs(120);
21const CALL_TIMEOUT: Duration = Duration::from_secs(30);
22
23fn err(msg: impl Into<String>) -> io::Error {
24 io::Error::other(msg.into())
25}
26
27type Sender = hyper::client::conn::http1::SendRequest<Full<Bytes>>;
28
29const MAX_IDLE: usize = 2;
30const MAX_CALLS: usize = 4;
31
32struct Conn {
33 host: String,
34 port: u16,
35 tls: TlsConnector,
36 name: ServerName<'static>,
37 token: Option<String>,
38 token_file: Option<std::path::PathBuf>,
39 ca: Vec<u8>,
40 idle: std::sync::Mutex<Vec<Sender>>,
41}
42
43struct Loaded {
44 conn: Arc<Conn>,
45 mtime: Option<std::time::SystemTime>,
46 checked: std::time::Instant,
47}
48
49pub struct Client {
50 path: std::path::PathBuf,
51 cur: std::sync::Mutex<Loaded>,
52 calls: tokio::sync::Semaphore,
53}
54
55const RELOAD_CHECK: Duration = Duration::from_secs(30);
56
57fn mtime(path: &std::path::Path) -> Option<std::time::SystemTime> {
58 std::fs::metadata(path).and_then(|m| m.modified()).ok()
59}
60
61fn field(v: &Value, key: &str) -> Option<String> {
62 v[key]
63 .as_str()
64 .map(str::to_string)
65 .filter(|s| !s.is_empty())
66}
67
68fn data_or_file(v: &Value, key: &str, dir: &std::path::Path) -> Result<Option<Vec<u8>>, String> {
69 if let Some(d) = field(v, &format!("{key}-data")) {
70 return base64_decode(&d)
71 .map(Some)
72 .ok_or_else(|| format!("{key}-data is not base64"));
73 }
74 match field(v, key) {
75 Some(p) => {
76 let path = dir.join(p);
77 std::fs::read(&path)
78 .map(Some)
79 .map_err(|e| format!("{}: {e}", path.display()))
80 }
81 None => Ok(None),
82 }
83}
84
85fn named<'a>(list: &'a Value, name: &str) -> Option<&'a Value> {
86 list.as_array()?.iter().find(|e| e["name"] == name)
87}
88
89impl Client {
90 pub fn from_kubeconfig(path: &std::path::Path) -> Result<Self, String> {
91 let conn = Arc::new(Conn::load(path)?);
92 Ok(Self {
93 path: path.to_path_buf(),
94 cur: std::sync::Mutex::new(Loaded {
95 conn,
96 mtime: mtime(path),
97 checked: std::time::Instant::now(),
98 }),
99 calls: tokio::sync::Semaphore::new(MAX_CALLS),
100 })
101 }
102
103 fn conn(&self) -> Arc<Conn> {
104 let mut g = self.cur.lock().unwrap_or_else(|e| e.into_inner());
105 if g.checked.elapsed() >= RELOAD_CHECK {
106 g.checked = std::time::Instant::now();
107 let m = mtime(&self.path);
108 if m != g.mtime {
109 match Conn::load(&self.path) {
110 Ok(c) => {
111 g.conn = Arc::new(c);
112 g.mtime = m;
113 }
114 Err(e) => eprintln!("krab-agent: reload kubeconfig: {e}"),
115 }
116 }
117 }
118 g.conn.clone()
119 }
120}
121
122impl Conn {
123 fn load(path: &std::path::Path) -> Result<Self, String> {
124 let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
125 let dir = path.parent().unwrap_or(std::path::Path::new("."));
126 let cfg = yaml::parse(&text);
127 let ctx_name = field(&cfg, "current-context")
128 .or_else(|| field(&cfg["contexts"][0], "name"))
129 .ok_or("kubeconfig has no context")?;
130 let ctx =
131 &named(&cfg["contexts"], &ctx_name).ok_or("current-context not found")?["context"];
132 let cluster = &named(&cfg["clusters"], ctx["cluster"].as_str().unwrap_or(""))
133 .ok_or("cluster not found")?["cluster"];
134 let user = &named(&cfg["users"], ctx["user"].as_str().unwrap_or(""))
135 .ok_or("user not found")?["user"];
136 let server = field(cluster, "server").ok_or("cluster has no server")?;
137 let rest = server
138 .strip_prefix("https://")
139 .ok_or("only https servers are supported")?;
140 let rest = rest.trim_end_matches('/');
141 let (host, port) = match rest.rsplit_once(':') {
142 Some((h, p)) if !h.ends_with(']') || h.starts_with('[') => (
143 h.trim_matches(['[', ']']).to_string(),
144 p.parse::<u16>().map_err(|e| e.to_string())?,
145 ),
146 _ => (rest.to_string(), 443),
147 };
148 let provider = Arc::new(default_provider());
149 let mut roots = RootCertStore::empty();
150 let ca_pem = data_or_file(cluster, "certificate-authority", dir)?.unwrap_or_default();
151 if !ca_pem.is_empty() {
152 let ca = &ca_pem;
153 for c in CertificateDer::pem_slice_iter(ca) {
154 roots
155 .add(c.map_err(|e| e.to_string())?)
156 .map_err(|e| e.to_string())?;
157 }
158 } else {
159 return Err("cluster has no certificate-authority".into());
160 }
161 let builder = ClientConfig::builder_with_provider(provider)
162 .with_safe_default_protocol_versions()
163 .map_err(|e| e.to_string())?
164 .with_root_certificates(roots);
165 let cert = data_or_file(user, "client-certificate", dir)?;
166 let key = data_or_file(user, "client-key", dir)?;
167 let mut tls = match (cert, key) {
168 (Some(c), Some(k)) => {
169 let chain = CertificateDer::pem_slice_iter(&c)
170 .collect::<Result<Vec<_>, _>>()
171 .map_err(|e| e.to_string())?;
172 let key = PrivateKeyDer::from_pem_slice(&k).map_err(|e| e.to_string())?;
173 builder
174 .with_client_auth_cert(chain, key)
175 .map_err(|e| e.to_string())?
176 }
177 _ => builder.with_no_client_auth(),
178 };
179 tls.alpn_protocols = vec![b"http/1.1".to_vec()];
180 tls.resumption = rustls::client::Resumption::disabled();
181 let token = field(user, "token");
182 let token_file = match &token {
183 None => field(user, "tokenFile").map(|p| dir.join(p)),
184 Some(_) => None,
185 };
186 if let Some(f) = &token_file {
187 std::fs::metadata(f).map_err(|e| format!("{}: {e}", f.display()))?;
188 }
189 let name = ServerName::try_from(host.clone()).map_err(|e| e.to_string())?;
190 Ok(Self {
191 host,
192 port,
193 tls: TlsConnector::from(Arc::new(tls)),
194 name,
195 token,
196 token_file,
197 ca: ca_pem,
198 idle: std::sync::Mutex::new(Vec::new()),
199 })
200 }
201
202 fn token(&self) -> Option<String> {
203 match &self.token_file {
204 Some(f) => std::fs::read_to_string(f)
205 .ok()
206 .map(|t| t.trim().to_string())
207 .filter(|t| !t.is_empty()),
208 None => self.token.clone(),
209 }
210 }
211}
212
213impl Client {
214 pub fn ca_pem(&self) -> String {
215 String::from_utf8_lossy(&self.conn().ca).into_owned()
216 }
217
218 pub fn authority(&self) -> String {
219 let c = self.conn();
220 format!("{}:{}", c.host, c.port)
221 }
222
223 async fn connect(c: &Conn) -> io::Result<Sender> {
224 let tcp = TcpStream::connect((c.host.as_str(), c.port)).await?;
225 tcp.set_nodelay(true)?;
226 let tls = c.tls.connect(c.name.clone(), tcp).await?;
227 let (sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(tls))
228 .await
229 .map_err(|e| err(e.to_string()))?;
230 tokio::spawn(async move {
231 let _ = conn.await;
232 });
233 Ok(sender)
234 }
235
236 fn request(
237 c: &Conn,
238 method: &Method,
239 path: &str,
240 ctype: Option<&str>,
241 body: &Option<Vec<u8>>,
242 ) -> io::Result<Request<Full<Bytes>>> {
243 let mut req = Request::builder()
244 .method(method.clone())
245 .uri(path)
246 .header("host", format!("{}:{}", c.host, c.port))
247 .header("accept", "application/json")
248 .header("user-agent", "krab-agent");
249 if let Some(t) = c.token() {
250 req = req.header("authorization", format!("Bearer {t}"));
251 }
252 if let Some(c) = ctype {
253 req = req.header("content-type", c);
254 }
255 req.body(Full::new(Bytes::from(body.clone().unwrap_or_default())))
256 .map_err(|e| err(e.to_string()))
257 }
258
259 async fn send(
260 &self,
261 method: Method,
262 path: &str,
263 ctype: Option<&str>,
264 body: Option<Vec<u8>>,
265 reuse: bool,
266 ) -> io::Result<(hyper::Response<Incoming>, Option<(Arc<Conn>, Sender)>)> {
267 let c = self.conn();
268 let pooled = if reuse {
269 let mut idle = c.idle.lock().unwrap_or_else(|e| e.into_inner());
270 let mut found = None;
271 while let Some(s) = idle.pop() {
272 if !s.is_closed() {
273 found = Some(s);
274 break;
275 }
276 }
277 found
278 } else {
279 None
280 };
281 if let Some(mut sender) = pooled {
282 let req = Self::request(&c, &method, path, ctype, &body)?;
283 if let Ok(resp) = sender.send_request(req).await {
284 return Ok((resp, Some((c, sender))));
285 }
286 }
287 let mut sender = Self::connect(&c).await?;
288 let req = Self::request(&c, &method, path, ctype, &body)?;
289 let resp = sender
290 .send_request(req)
291 .await
292 .map_err(|e| err(e.to_string()))?;
293 Ok((resp, reuse.then_some((c, sender))))
294 }
295
296 pub async fn call(
297 &self,
298 method: Method,
299 path: &str,
300 ctype: Option<&str>,
301 body: Option<Vec<u8>>,
302 ) -> io::Result<(u16, Value)> {
303 let _permit = self.calls.acquire().await.map_err(|e| err(e.to_string()))?;
304 let fut = async {
305 let (resp, pooled) = self.send(method, path, ctype, body, true).await?;
306 let status = resp.status().as_u16();
307 let mut body = resp.into_body();
308 let mut buf = BytesMut::new();
309 while let Some(frame) = body.frame().await {
310 let frame = frame.map_err(|e| err(e.to_string()))?;
311 if let Some(d) = frame.data_ref() {
312 if buf.len() + d.len() > MAX_BODY {
313 return Err(err("response too large"));
314 }
315 buf.extend_from_slice(d);
316 }
317 }
318 if let Some((c, sender)) = pooled
319 && !sender.is_closed()
320 {
321 let mut idle = c.idle.lock().unwrap_or_else(|e| e.into_inner());
322 if idle.len() < MAX_IDLE {
323 idle.push(sender);
324 }
325 }
326 Ok((status, serde_json::from_slice(&buf).unwrap_or(Value::Null)))
327 };
328 tokio::time::timeout(CALL_TIMEOUT, fut)
329 .await
330 .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "apiserver call timed out"))?
331 }
332
333 pub async fn get(&self, path: &str) -> io::Result<(u16, Value)> {
334 self.call(Method::GET, path, None, None).await
335 }
336
337 pub async fn post(&self, path: &str, body: &Value) -> io::Result<(u16, Value)> {
338 let b = serde_json::to_vec(body).map_err(|e| err(e.to_string()))?;
339 self.call(Method::POST, path, Some("application/json"), Some(b))
340 .await
341 }
342
343 pub async fn patch(&self, path: &str, ctype: &str, body: &Value) -> io::Result<(u16, Value)> {
344 let b = serde_json::to_vec(body).map_err(|e| err(e.to_string()))?;
345 self.call(Method::PATCH, path, Some(ctype), Some(b)).await
346 }
347
348 pub async fn delete(&self, path: &str, body: &Value) -> io::Result<(u16, Value)> {
349 let b = serde_json::to_vec(body).map_err(|e| err(e.to_string()))?;
350 self.call(Method::DELETE, path, Some("application/json"), Some(b))
351 .await
352 }
353
354 pub async fn watch(&self, path: &str) -> io::Result<Watch> {
355 let (resp, _) = tokio::time::timeout(
356 CALL_TIMEOUT,
357 self.send(Method::GET, path, None, None, false),
358 )
359 .await
360 .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "watch connect timed out"))??;
361 if !resp.status().is_success() {
362 return Err(err(format!("watch: HTTP {}", resp.status())));
363 }
364 Ok(Watch {
365 body: resp.into_body(),
366 buf: BytesMut::new(),
367 })
368 }
369}
370
371pub struct Watch {
372 body: Incoming,
373 buf: BytesMut,
374}
375
376impl Watch {
377 pub async fn next(&mut self) -> io::Result<Option<Value>> {
378 loop {
379 if let Some(i) = self.buf.iter().position(|b| *b == b'\n') {
380 let line = self.buf.split_to(i + 1);
381 if line.trim_ascii().is_empty() {
382 continue;
383 }
384 return serde_json::from_slice(&line)
385 .map(Some)
386 .map_err(|e| err(e.to_string()));
387 }
388 let frame = tokio::time::timeout(WATCH_IDLE, self.body.frame())
389 .await
390 .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "watch idle timeout"))?;
391 match frame {
392 None => return Ok(None),
393 Some(Err(e)) => return Err(err(e.to_string())),
394 Some(Ok(f)) => {
395 if let Some(d) = f.data_ref() {
396 if self.buf.len() + d.remaining() > MAX_BODY {
397 return Err(err("watch event too large"));
398 }
399 self.buf.extend_from_slice(d);
400 }
401 }
402 }
403 }
404 }
405}