use ahash::AHashMap;
use futures_util::future;
use hyper::{Request, Response};
use std::{
fmt,
net::SocketAddr,
pin::Pin,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use tracing::{debug, info_span, Instrument};
#[derive(Debug, thiserror::Error)]
#[error("failed to bind admin server: {0}")]
pub struct BindError(#[from] std::io::Error);
type Body = http_body_util::Full<bytes::Bytes>;
type HandlerFn =
Box<dyn Fn(Request<hyper::body::Incoming>) -> Response<Body> + Send + Sync + 'static>;
#[cfg(feature = "prometheus-client")]
mod metrics;
#[derive(Clone, Debug)]
#[cfg_attr(feature = "clap", derive(clap::Parser))]
#[cfg_attr(docsrs, doc(cfg(feature = "admin")))]
pub struct AdminArgs {
#[cfg_attr(feature = "clap", clap(long, default_value = "0.0.0.0:8080"))]
pub admin_addr: SocketAddr,
}
#[cfg_attr(docsrs, doc(cfg(feature = "admin")))]
pub struct Builder {
addr: SocketAddr,
ready: Readiness,
routes: AHashMap<String, HandlerFn>,
}
#[cfg_attr(docsrs, doc(cfg(feature = "admin")))]
pub struct Bound {
addr: SocketAddr,
ready: Readiness,
listener: tokio::net::TcpListener,
server: hyper::server::conn::http1::Builder,
routes: AHashMap<String, HandlerFn>,
}
#[cfg_attr(docsrs, doc(cfg(feature = "admin")))]
#[derive(Clone, Debug)]
pub struct Readiness(Arc<AtomicBool>);
#[cfg_attr(docsrs, doc(cfg(feature = "admin")))]
#[derive(Debug)]
pub struct Server {
addr: SocketAddr,
ready: Readiness,
task: tokio::task::JoinHandle<Result<(), hyper::Error>>,
}
impl Default for AdminArgs {
fn default() -> Self {
Self {
admin_addr: SocketAddr::from(([0, 0, 0, 0], 8080)),
}
}
}
impl AdminArgs {
pub fn into_builder(self) -> Builder {
Builder::new(self.admin_addr)
}
}
impl Default for Builder {
fn default() -> Self {
AdminArgs::default().into_builder()
}
}
impl From<AdminArgs> for Builder {
fn from(args: AdminArgs) -> Self {
args.into_builder()
}
}
impl Builder {
pub fn new(addr: SocketAddr) -> Self {
Self {
addr,
ready: Readiness(Arc::new(false.into())),
routes: Default::default(),
}
}
pub fn readiness(&self) -> Readiness {
self.ready.clone()
}
pub fn set_ready(&self) {
self.ready.set(true);
}
#[cfg(feature = "prometheus-client")]
#[cfg_attr(docsrs, doc(cfg(feature = "prometheus-client")))]
pub fn with_prometheus(self, mut registry: prometheus_client::registry::Registry) -> Self {
#[cfg(not(tokio_unstable))]
tracing::debug!("Tokio runtime metrics cannot be monitored without the tokio_unstable cfg");
#[cfg(tokio_unstable)]
{
let metrics = kubert_prometheus_tokio::Runtime::register(
registry.sub_registry_with_prefix("tokio_rt"),
tokio::runtime::Handle::current(),
);
let mut interval = tokio::time::interval(Duration::from_secs(1));
tokio::spawn(
async move { metrics.updated(&mut interval).await }
.instrument(tracing::info_span!("kubert-prom-tokio-rt")),
);
}
if let Err(error) =
kubert_prometheus_process::register(registry.sub_registry_with_prefix("process"))
{
tracing::warn!(%error, "Process metrics cannot be monitored");
}
self.with_prometheus_handler("/metrics", registry)
}
#[cfg(feature = "prometheus-client")]
#[cfg_attr(docsrs, doc(cfg(feature = "prometheus-client")))]
pub fn with_prometheus_handler(
self,
path: impl ToString,
registry: prometheus_client::registry::Registry,
) -> Self {
let prom = metrics::Prometheus::new(registry);
self.with_handler(path, move |req| prom.handle_metrics(req))
}
pub fn with_handler(
mut self,
path: impl ToString,
handler: impl Fn(Request<hyper::body::Incoming>) -> Response<Body> + Send + Sync + 'static,
) -> Self {
let path = path.to_string();
assert_ne!(
path, "/ready",
"the built-in `/ready` handler cannot be overridden"
);
assert_ne!(
path, "/live",
"the built-in `/live` handler cannot be overridden"
);
self.routes.insert(path, Box::new(handler));
self
}
pub fn bind(self) -> Result<Bound, BindError> {
let Self {
addr,
ready,
routes,
} = self;
let listener = tokio::net::TcpListener::from_std(std::net::TcpListener::bind(addr)?)?;
let mut server = hyper::server::conn::http1::Builder::new();
server
.half_close(true)
.header_read_timeout(Duration::from_secs(2))
.max_buf_size(8 * 1024);
Ok(Bound {
addr,
ready,
server,
listener,
routes,
})
}
}
impl fmt::Debug for Builder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("Builder");
d.field("addr", &self.addr).field("ready", &self.ready);
d.finish()
}
}
impl Bound {
pub fn readiness(&self) -> Readiness {
self.ready.clone()
}
pub fn set_ready(&self) {
self.ready.set(true);
}
pub fn spawn(self) -> Server {
let Self {
ready,
server,
listener,
routes,
addr,
} = self;
let svc = {
let ready = ready.clone();
let routes = Arc::new(routes);
hyper::service::service_fn(move |req| handle(&ready, &routes, req))
};
let task = tokio::spawn(
async move {
loop {
let (stream, client_addr) = match listener.accept().await {
Ok(socket) => socket,
Err(error) => {
tracing::warn!(%error, "Failed to accept connection");
continue;
}
};
tracing::trace!(client.addr = ?client_addr, "Accepted connection");
let serve =
server.serve_connection(hyper_util::rt::TokioIo::new(stream), svc.clone());
tokio::spawn(
async move {
debug!("Serving");
serve.await
}
.instrument(
tracing::debug_span!("conn", client.addr = %client_addr).or_current(),
),
);
}
}
.instrument(info_span!("admin", port = %self.addr.port())),
);
Server { task, addr, ready }
}
}
impl Readiness {
pub fn get(&self) -> bool {
self.0.load(Ordering::Acquire)
}
pub fn set(&self, ready: bool) {
self.0.store(ready, Ordering::Release);
}
}
impl Server {
pub fn local_addr(&self) -> SocketAddr {
self.addr
}
pub fn readiness(&self) -> Readiness {
self.ready.clone()
}
pub fn into_join_handle(self) -> tokio::task::JoinHandle<Result<(), hyper::Error>> {
self.task
}
}
fn handle(
ready: &Readiness,
routes: &Arc<AHashMap<String, HandlerFn>>,
req: hyper::Request<hyper::body::Incoming>,
) -> Pin<
Box<
dyn std::future::Future<Output = Result<hyper::Response<Body>, tokio::task::JoinError>>
+ Send,
>,
> {
if req.uri().path() == "/live" {
Box::pin(future::ok(handle_live(req)))
} else if req.uri().path() == "/ready" {
Box::pin(future::ok(handle_ready(ready, req)))
} else if routes.contains_key(req.uri().path()) {
let routes = routes.clone();
let path = req.uri().path().to_string();
Box::pin(async move {
tokio::task::spawn_blocking(move || {
let handler = routes.get(&path).expect("routes must contain path");
handler(req)
})
.await
})
} else {
Box::pin(future::ok(
Response::builder()
.status(hyper::StatusCode::NOT_FOUND)
.body(Body::default())
.unwrap(),
))
}
}
fn handle_live(req: Request<hyper::body::Incoming>) -> Response<Body> {
match *req.method() {
hyper::Method::GET | hyper::Method::HEAD => Response::builder()
.status(hyper::StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "text/plain")
.body("alive\n".into())
.unwrap(),
_ => Response::builder()
.status(hyper::StatusCode::METHOD_NOT_ALLOWED)
.header(hyper::header::ALLOW, "GET, HEAD")
.body(Body::default())
.unwrap(),
}
}
fn handle_ready(
Readiness(ready): &Readiness,
req: Request<hyper::body::Incoming>,
) -> Response<Body> {
match *req.method() {
hyper::Method::GET | hyper::Method::HEAD => {
if ready.load(Ordering::Acquire) {
return Response::builder()
.status(hyper::StatusCode::OK)
.header(hyper::header::CONTENT_TYPE, "text/plain")
.body("ready\n".into())
.unwrap();
}
Response::builder()
.status(hyper::StatusCode::INTERNAL_SERVER_ERROR)
.header(hyper::header::CONTENT_TYPE, "text/plain")
.body("not ready\n".into())
.unwrap()
}
_ => Response::builder()
.status(hyper::StatusCode::METHOD_NOT_ALLOWED)
.header(hyper::header::ALLOW, "GET, HEAD")
.body(Body::default())
.unwrap(),
}
}