krab-agent 0.2.0

Lightweight kubelet for a real Kubernetes control plane (krab agent)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use crate::yaml;
use bytes::{Buf, Bytes, BytesMut};
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::{Method, Request};
use hyper_util::rt::TokioIo;
use krab_controllers::util::base64_decode;
use rustls::crypto::ring::default_provider;
use rustls::{ClientConfig, RootCertStore};
use rustls_pki_types::pem::PemObject;
use rustls_pki_types::{CertificateDer, PrivateKeyDer, ServerName};
use serde_json::Value;
use std::io;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;

const MAX_BODY: usize = 16 << 20;
const WATCH_IDLE: Duration = Duration::from_secs(120);
const CALL_TIMEOUT: Duration = Duration::from_secs(30);

fn err(msg: impl Into<String>) -> io::Error {
    io::Error::other(msg.into())
}

type Sender = hyper::client::conn::http1::SendRequest<Full<Bytes>>;

const MAX_IDLE: usize = 2;
const MAX_CALLS: usize = 4;

struct Conn {
    host: String,
    port: u16,
    tls: TlsConnector,
    name: ServerName<'static>,
    token: Option<String>,
    token_file: Option<std::path::PathBuf>,
    ca: Vec<u8>,
    idle: std::sync::Mutex<Vec<Sender>>,
}

struct Loaded {
    conn: Arc<Conn>,
    mtime: Option<std::time::SystemTime>,
    checked: std::time::Instant,
}

pub struct Client {
    path: std::path::PathBuf,
    cur: std::sync::Mutex<Loaded>,
    calls: tokio::sync::Semaphore,
}

const RELOAD_CHECK: Duration = Duration::from_secs(30);

fn mtime(path: &std::path::Path) -> Option<std::time::SystemTime> {
    std::fs::metadata(path).and_then(|m| m.modified()).ok()
}

fn field(v: &Value, key: &str) -> Option<String> {
    v[key]
        .as_str()
        .map(str::to_string)
        .filter(|s| !s.is_empty())
}

fn data_or_file(v: &Value, key: &str, dir: &std::path::Path) -> Result<Option<Vec<u8>>, String> {
    if let Some(d) = field(v, &format!("{key}-data")) {
        return base64_decode(&d)
            .map(Some)
            .ok_or_else(|| format!("{key}-data is not base64"));
    }
    match field(v, key) {
        Some(p) => {
            let path = dir.join(p);
            std::fs::read(&path)
                .map(Some)
                .map_err(|e| format!("{}: {e}", path.display()))
        }
        None => Ok(None),
    }
}

fn named<'a>(list: &'a Value, name: &str) -> Option<&'a Value> {
    list.as_array()?.iter().find(|e| e["name"] == name)
}

impl Client {
    pub fn from_kubeconfig(path: &std::path::Path) -> Result<Self, String> {
        let conn = Arc::new(Conn::load(path)?);
        Ok(Self {
            path: path.to_path_buf(),
            cur: std::sync::Mutex::new(Loaded {
                conn,
                mtime: mtime(path),
                checked: std::time::Instant::now(),
            }),
            calls: tokio::sync::Semaphore::new(MAX_CALLS),
        })
    }

    fn conn(&self) -> Arc<Conn> {
        let mut g = self.cur.lock().unwrap_or_else(|e| e.into_inner());
        if g.checked.elapsed() >= RELOAD_CHECK {
            g.checked = std::time::Instant::now();
            let m = mtime(&self.path);
            if m != g.mtime {
                match Conn::load(&self.path) {
                    Ok(c) => {
                        g.conn = Arc::new(c);
                        g.mtime = m;
                    }
                    Err(e) => eprintln!("krab-agent: reload kubeconfig: {e}"),
                }
            }
        }
        g.conn.clone()
    }
}

impl Conn {
    fn load(path: &std::path::Path) -> Result<Self, String> {
        let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
        let dir = path.parent().unwrap_or(std::path::Path::new("."));
        let cfg = yaml::parse(&text);
        let ctx_name = field(&cfg, "current-context")
            .or_else(|| field(&cfg["contexts"][0], "name"))
            .ok_or("kubeconfig has no context")?;
        let ctx =
            &named(&cfg["contexts"], &ctx_name).ok_or("current-context not found")?["context"];
        let cluster = &named(&cfg["clusters"], ctx["cluster"].as_str().unwrap_or(""))
            .ok_or("cluster not found")?["cluster"];
        let user = &named(&cfg["users"], ctx["user"].as_str().unwrap_or(""))
            .ok_or("user not found")?["user"];
        let server = field(cluster, "server").ok_or("cluster has no server")?;
        let rest = server
            .strip_prefix("https://")
            .ok_or("only https servers are supported")?;
        let rest = rest.trim_end_matches('/');
        let (host, port) = match rest.rsplit_once(':') {
            Some((h, p)) if !h.ends_with(']') || h.starts_with('[') => (
                h.trim_matches(['[', ']']).to_string(),
                p.parse::<u16>().map_err(|e| e.to_string())?,
            ),
            _ => (rest.to_string(), 443),
        };
        let provider = Arc::new(default_provider());
        let mut roots = RootCertStore::empty();
        let ca_pem = data_or_file(cluster, "certificate-authority", dir)?.unwrap_or_default();
        if !ca_pem.is_empty() {
            let ca = &ca_pem;
            for c in CertificateDer::pem_slice_iter(ca) {
                roots
                    .add(c.map_err(|e| e.to_string())?)
                    .map_err(|e| e.to_string())?;
            }
        } else {
            return Err("cluster has no certificate-authority".into());
        }
        let builder = ClientConfig::builder_with_provider(provider)
            .with_safe_default_protocol_versions()
            .map_err(|e| e.to_string())?
            .with_root_certificates(roots);
        let cert = data_or_file(user, "client-certificate", dir)?;
        let key = data_or_file(user, "client-key", dir)?;
        let mut tls = match (cert, key) {
            (Some(c), Some(k)) => {
                let chain = CertificateDer::pem_slice_iter(&c)
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| e.to_string())?;
                let key = PrivateKeyDer::from_pem_slice(&k).map_err(|e| e.to_string())?;
                builder
                    .with_client_auth_cert(chain, key)
                    .map_err(|e| e.to_string())?
            }
            _ => builder.with_no_client_auth(),
        };
        tls.alpn_protocols = vec![b"http/1.1".to_vec()];
        tls.resumption = rustls::client::Resumption::disabled();
        let token = field(user, "token");
        let token_file = match &token {
            None => field(user, "tokenFile").map(|p| dir.join(p)),
            Some(_) => None,
        };
        if let Some(f) = &token_file {
            std::fs::metadata(f).map_err(|e| format!("{}: {e}", f.display()))?;
        }
        let name = ServerName::try_from(host.clone()).map_err(|e| e.to_string())?;
        Ok(Self {
            host,
            port,
            tls: TlsConnector::from(Arc::new(tls)),
            name,
            token,
            token_file,
            ca: ca_pem,
            idle: std::sync::Mutex::new(Vec::new()),
        })
    }

    fn token(&self) -> Option<String> {
        match &self.token_file {
            Some(f) => std::fs::read_to_string(f)
                .ok()
                .map(|t| t.trim().to_string())
                .filter(|t| !t.is_empty()),
            None => self.token.clone(),
        }
    }
}

impl Client {
    pub fn ca_pem(&self) -> String {
        String::from_utf8_lossy(&self.conn().ca).into_owned()
    }

    pub fn authority(&self) -> String {
        let c = self.conn();
        format!("{}:{}", c.host, c.port)
    }

    async fn connect(c: &Conn) -> io::Result<Sender> {
        let tcp = TcpStream::connect((c.host.as_str(), c.port)).await?;
        tcp.set_nodelay(true)?;
        let tls = c.tls.connect(c.name.clone(), tcp).await?;
        let (sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(tls))
            .await
            .map_err(|e| err(e.to_string()))?;
        tokio::spawn(async move {
            let _ = conn.await;
        });
        Ok(sender)
    }

    fn request(
        c: &Conn,
        method: &Method,
        path: &str,
        ctype: Option<&str>,
        body: &Option<Vec<u8>>,
    ) -> io::Result<Request<Full<Bytes>>> {
        let mut req = Request::builder()
            .method(method.clone())
            .uri(path)
            .header("host", format!("{}:{}", c.host, c.port))
            .header("accept", "application/json")
            .header("user-agent", "krab-agent");
        if let Some(t) = c.token() {
            req = req.header("authorization", format!("Bearer {t}"));
        }
        if let Some(c) = ctype {
            req = req.header("content-type", c);
        }
        req.body(Full::new(Bytes::from(body.clone().unwrap_or_default())))
            .map_err(|e| err(e.to_string()))
    }

    async fn send(
        &self,
        method: Method,
        path: &str,
        ctype: Option<&str>,
        body: Option<Vec<u8>>,
        reuse: bool,
    ) -> io::Result<(hyper::Response<Incoming>, Option<(Arc<Conn>, Sender)>)> {
        let c = self.conn();
        let pooled = if reuse {
            let mut idle = c.idle.lock().unwrap_or_else(|e| e.into_inner());
            let mut found = None;
            while let Some(s) = idle.pop() {
                if !s.is_closed() {
                    found = Some(s);
                    break;
                }
            }
            found
        } else {
            None
        };
        if let Some(mut sender) = pooled {
            let req = Self::request(&c, &method, path, ctype, &body)?;
            if let Ok(resp) = sender.send_request(req).await {
                return Ok((resp, Some((c, sender))));
            }
        }
        let mut sender = Self::connect(&c).await?;
        let req = Self::request(&c, &method, path, ctype, &body)?;
        let resp = sender
            .send_request(req)
            .await
            .map_err(|e| err(e.to_string()))?;
        Ok((resp, reuse.then_some((c, sender))))
    }

    pub async fn call(
        &self,
        method: Method,
        path: &str,
        ctype: Option<&str>,
        body: Option<Vec<u8>>,
    ) -> io::Result<(u16, Value)> {
        let _permit = self.calls.acquire().await.map_err(|e| err(e.to_string()))?;
        let fut = async {
            let (resp, pooled) = self.send(method, path, ctype, body, true).await?;
            let status = resp.status().as_u16();
            let mut body = resp.into_body();
            let mut buf = BytesMut::new();
            while let Some(frame) = body.frame().await {
                let frame = frame.map_err(|e| err(e.to_string()))?;
                if let Some(d) = frame.data_ref() {
                    if buf.len() + d.len() > MAX_BODY {
                        return Err(err("response too large"));
                    }
                    buf.extend_from_slice(d);
                }
            }
            if let Some((c, sender)) = pooled
                && !sender.is_closed()
            {
                let mut idle = c.idle.lock().unwrap_or_else(|e| e.into_inner());
                if idle.len() < MAX_IDLE {
                    idle.push(sender);
                }
            }
            Ok((status, serde_json::from_slice(&buf).unwrap_or(Value::Null)))
        };
        tokio::time::timeout(CALL_TIMEOUT, fut)
            .await
            .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "apiserver call timed out"))?
    }

    pub async fn get(&self, path: &str) -> io::Result<(u16, Value)> {
        self.call(Method::GET, path, None, None).await
    }

    pub async fn post(&self, path: &str, body: &Value) -> io::Result<(u16, Value)> {
        let b = serde_json::to_vec(body).map_err(|e| err(e.to_string()))?;
        self.call(Method::POST, path, Some("application/json"), Some(b))
            .await
    }

    pub async fn patch(&self, path: &str, ctype: &str, body: &Value) -> io::Result<(u16, Value)> {
        let b = serde_json::to_vec(body).map_err(|e| err(e.to_string()))?;
        self.call(Method::PATCH, path, Some(ctype), Some(b)).await
    }

    pub async fn delete(&self, path: &str, body: &Value) -> io::Result<(u16, Value)> {
        let b = serde_json::to_vec(body).map_err(|e| err(e.to_string()))?;
        self.call(Method::DELETE, path, Some("application/json"), Some(b))
            .await
    }

    pub async fn watch(&self, path: &str) -> io::Result<Watch> {
        let (resp, _) = tokio::time::timeout(
            CALL_TIMEOUT,
            self.send(Method::GET, path, None, None, false),
        )
        .await
        .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "watch connect timed out"))??;
        if !resp.status().is_success() {
            return Err(err(format!("watch: HTTP {}", resp.status())));
        }
        Ok(Watch {
            body: resp.into_body(),
            buf: BytesMut::new(),
        })
    }
}

pub struct Watch {
    body: Incoming,
    buf: BytesMut,
}

impl Watch {
    pub async fn next(&mut self) -> io::Result<Option<Value>> {
        loop {
            if let Some(i) = self.buf.iter().position(|b| *b == b'\n') {
                let line = self.buf.split_to(i + 1);
                if line.trim_ascii().is_empty() {
                    continue;
                }
                return serde_json::from_slice(&line)
                    .map(Some)
                    .map_err(|e| err(e.to_string()));
            }
            let frame = tokio::time::timeout(WATCH_IDLE, self.body.frame())
                .await
                .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "watch idle timeout"))?;
            match frame {
                None => return Ok(None),
                Some(Err(e)) => return Err(err(e.to_string())),
                Some(Ok(f)) => {
                    if let Some(d) = f.data_ref() {
                        if self.buf.len() + d.remaining() > MAX_BODY {
                            return Err(err("watch event too large"));
                        }
                        self.buf.extend_from_slice(d);
                    }
                }
            }
        }
    }
}