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);
}
}
}
}
}
}