use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Clone, Default)]
pub struct ExecutorHealth {
heartbeat_ok: Arc<AtomicBool>,
}
impl ExecutorHealth {
pub fn new() -> Self {
Self::default()
}
pub fn mark_heartbeat_ok(&self) {
self.heartbeat_ok.store(true, Ordering::Release);
}
pub fn mark_heartbeat_failed(&self) {
self.heartbeat_ok.store(false, Ordering::Release);
}
pub fn is_ready(&self) -> bool {
self.heartbeat_ok.load(Ordering::Acquire)
}
}
#[cfg(feature = "build-binary")]
mod server {
use super::ExecutorHealth;
use axum::{
Router,
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
};
use ballista_core::error::BallistaError;
use log::{info, warn};
use std::net::SocketAddr;
use tokio::task::JoinHandle;
pub fn spawn_health_server(
addr: SocketAddr,
health: ExecutorHealth,
shutdown: tokio::sync::oneshot::Receiver<()>,
) -> JoinHandle<Result<(), BallistaError>> {
tokio::spawn(async move {
let router = Router::new()
.route("/healthz", get(healthz))
.route("/readyz", get(readyz))
.with_state(health);
let listener = tokio::net::TcpListener::bind(addr).await.map_err(|e| {
BallistaError::General(format!(
"failed to bind health server on {addr}: {e}"
))
})?;
info!("Executor health server listening on {addr}");
axum::serve(listener, router.into_make_service())
.with_graceful_shutdown(async move {
let _ = shutdown.await;
})
.await
.map_err(|e| {
warn!("Executor health server exited with error: {e}");
BallistaError::General(format!("health server error: {e}"))
})
})
}
async fn healthz() -> Response {
(StatusCode::OK, "ok\n").into_response()
}
async fn readyz(State(health): State<ExecutorHealth>) -> Response {
if health.is_ready() {
(StatusCode::OK, "ready\n").into_response()
} else {
(
StatusCode::SERVICE_UNAVAILABLE,
"not ready: no successful heartbeat yet\n",
)
.into_response()
}
}
}
#[cfg(feature = "build-binary")]
pub use server::spawn_health_server;