use std::future::Future;
use std::io;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use parking_lot::Mutex;
use thiserror::Error;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{UnixListener, UnixStream};
#[cfg(unix)]
use tokio::signal::unix::{SignalKind, signal};
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tracing::{debug, error, info, warn};
use crate::protocol::{
ActionKind, EngineHealth, PROTOCOL_VERSION, Request, Response, StatusReply, SupervisorState,
};
use crate::state::{PersistError, State};
pub type ProbeFuture<'a> = Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'a>>;
#[derive(Debug, Error)]
pub enum DaemonError {
#[error("socket bind error at {path}: {source}")]
Bind {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("socket i/o error at {path}: {source}")]
Socket {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("state error: {0}")]
Persist(#[from] PersistError),
#[error("missing configuration: {0}")]
MissingConfig(String),
}
pub trait EngineProbe: Send + Sync + 'static {
fn probe(&self) -> ProbeFuture<'_>;
}
#[derive(Debug, Default)]
pub struct AlwaysReachable;
impl EngineProbe for AlwaysReachable {
fn probe(&self) -> ProbeFuture<'_> {
Box::pin(async { Ok(()) })
}
}
#[derive(Debug, Default)]
pub struct AlwaysUnreachable;
impl EngineProbe for AlwaysUnreachable {
fn probe(&self) -> ProbeFuture<'_> {
Box::pin(async { Err("probe fault-injected".into()) })
}
}
#[derive(Debug)]
pub struct HttpEngineProbe {
client: zero_engine_client::HttpClient,
}
impl HttpEngineProbe {
#[must_use]
pub fn new(client: zero_engine_client::HttpClient) -> Self {
Self { client }
}
}
impl EngineProbe for HttpEngineProbe {
fn probe(&self) -> ProbeFuture<'_> {
Box::pin(async move {
self.client
.health()
.await
.map(|_| ())
.map_err(|e| e.to_string())
})
}
}
#[derive(Debug, Clone)]
pub struct Config {
pub socket_path: PathBuf,
pub state_path: PathBuf,
pub config_present: bool,
}
impl Config {
#[must_use]
pub fn for_test(base: &Path) -> Self {
Self {
socket_path: crate::paths::socket_in(base),
state_path: crate::paths::state_in(base),
config_present: true,
}
}
}
#[derive(Debug)]
pub struct Shutdown {
tx: Option<oneshot::Sender<()>>,
join: Option<JoinHandle<Result<(), DaemonError>>>,
socket_path: PathBuf,
}
impl Shutdown {
pub fn socket_path(&self) -> &Path {
&self.socket_path
}
pub fn shutdown(&mut self) {
if let Some(tx) = self.tx.take() {
let _ = tx.send(());
}
}
pub async fn join(mut self) -> Result<(), DaemonError> {
self.shutdown();
match self.join.take() {
Some(handle) => match handle.await {
Ok(res) => res,
Err(join_err) => {
error!(?join_err, "daemon task panicked");
Ok(())
}
},
None => Ok(()),
}
}
}
pub struct Daemon {
cfg: Config,
state: Arc<Mutex<State>>,
probe: Arc<dyn EngineProbe>,
last_engine: Arc<Mutex<EngineHealth>>,
}
impl std::fmt::Debug for Daemon {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Daemon")
.field("cfg", &self.cfg)
.field("state", &*self.state.lock())
.field("last_engine", &*self.last_engine.lock())
.finish_non_exhaustive()
}
}
impl Daemon {
pub fn new(cfg: Config, probe: Arc<dyn EngineProbe>) -> Result<Self, DaemonError> {
if !cfg.config_present {
return Err(DaemonError::MissingConfig(
"zero config missing — run `zero onboard` first".into(),
));
}
let state = State::load(&cfg.state_path)?;
Ok(Self {
cfg,
state: Arc::new(Mutex::new(state)),
probe,
last_engine: Arc::new(Mutex::new(EngineHealth::Unknown)),
})
}
pub fn spawn(self) -> Result<Shutdown, DaemonError> {
if self.cfg.socket_path.exists() {
let _ = std::fs::remove_file(&self.cfg.socket_path);
}
if let Some(parent) = self.cfg.socket_path.parent()
&& let Err(source) = std::fs::create_dir_all(parent)
{
return Err(DaemonError::Bind {
path: parent.to_path_buf(),
source,
});
}
let listener =
UnixListener::bind(&self.cfg.socket_path).map_err(|source| DaemonError::Bind {
path: self.cfg.socket_path.clone(),
source,
})?;
info!(socket = %self.cfg.socket_path.display(), "zero-headlessd listening");
let (tx, rx) = oneshot::channel::<()>();
let socket_path = self.cfg.socket_path.clone();
let join = tokio::spawn(self.run_accept_loop(listener, rx));
Ok(Shutdown {
tx: Some(tx),
join: Some(join),
socket_path,
})
}
pub async fn run(self) -> Result<(), DaemonError> {
let mut handle = self.spawn()?;
#[cfg(unix)]
{
let mut term =
signal(SignalKind::terminate()).map_err(|source| DaemonError::Socket {
path: handle.socket_path.clone(),
source,
})?;
let mut int =
signal(SignalKind::interrupt()).map_err(|source| DaemonError::Socket {
path: handle.socket_path.clone(),
source,
})?;
tokio::select! {
_ = term.recv() => {
info!("SIGTERM received — draining");
}
_ = int.recv() => {
info!("SIGINT received — draining");
}
}
}
handle.shutdown();
handle.join().await
}
async fn run_accept_loop(
self,
listener: UnixListener,
mut shutdown_rx: oneshot::Receiver<()>,
) -> Result<(), DaemonError> {
let (drain_permit, mut drain_wait) = mpsc::channel::<()>(1);
loop {
tokio::select! {
_ = &mut shutdown_rx => {
info!("shutdown requested — closing accept loop");
break;
}
accept = listener.accept() => {
match accept {
Ok((stream, _addr)) => {
let permit = drain_permit.clone();
let state = self.state.clone();
let state_path = self.cfg.state_path.clone();
let probe = self.probe.clone();
let last_engine = self.last_engine.clone();
tokio::spawn(async move {
if let Err(err) = handle_connection(
stream,
&state,
&state_path,
probe.as_ref(),
&last_engine,
)
.await
{
warn!(?err, "connection handler error");
}
drop(permit);
});
}
Err(source) => {
error!(?source, "accept failed");
}
}
}
}
}
drop(drain_permit);
while (drain_wait.recv().await).is_some() {}
let _ = std::fs::remove_file(&self.cfg.socket_path);
Ok(())
}
}
async fn handle_connection(
stream: UnixStream,
state: &Arc<Mutex<State>>,
state_path: &Path,
probe: &dyn EngineProbe,
last_engine: &Arc<Mutex<EngineHealth>>,
) -> Result<(), DaemonError> {
let (read_half, mut write_half) = stream.into_split();
let mut reader = BufReader::new(read_half);
let mut line = String::new();
let n = reader
.read_line(&mut line)
.await
.map_err(|source| DaemonError::Socket {
path: state_path.to_path_buf(),
source,
})?;
if n == 0 {
return Ok(());
}
let trimmed = line.trim_end_matches(['\r', '\n']);
let response = match serde_json::from_str::<Request>(trimmed) {
Ok(req) => dispatch(req, state, state_path, probe, last_engine).await,
Err(err) => Response::Error {
reason: format!("malformed request: {err}"),
},
};
let mut reply = serde_json::to_string(&response).unwrap_or_else(|_| {
"{\"kind\":\"error\",\"reason\":\"internal serialize failure\"}".into()
});
reply.push('\n');
write_half
.write_all(reply.as_bytes())
.await
.map_err(|source| DaemonError::Socket {
path: state_path.to_path_buf(),
source,
})?;
write_half
.flush()
.await
.map_err(|source| DaemonError::Socket {
path: state_path.to_path_buf(),
source,
})?;
debug!(?response, "reply sent");
Ok(())
}
async fn dispatch(
req: Request,
state: &Arc<Mutex<State>>,
state_path: &Path,
probe: &dyn EngineProbe,
last_engine: &Arc<Mutex<EngineHealth>>,
) -> Response {
match req {
Request::Status => status_reply(state, probe, last_engine).await,
Request::Start => mutate(state, state_path, |s| {
s.set_intent(SupervisorState::On);
s.push_action(ActionKind::Started, "start requested via socket");
}),
Request::Stop => mutate(state, state_path, |s| {
s.set_intent(SupervisorState::Off);
s.push_action(ActionKind::Stopped, "stop requested via socket");
}),
Request::Kill => {
let _ = mutate(state, state_path, |s| {
s.set_intent(SupervisorState::Off);
s.push_action(ActionKind::Killed, "kill-switch fired via socket");
});
Response::Accepted {
state: SupervisorState::Off,
protocol_version: PROTOCOL_VERSION,
}
}
}
}
fn mutate<F>(state: &Arc<Mutex<State>>, state_path: &Path, f: F) -> Response
where
F: FnOnce(&mut State),
{
let snap = {
let mut guard = state.lock();
f(&mut guard);
guard.clone()
};
if let Err(err) = snap.save(state_path) {
error!(?err, "state persist failed");
return Response::Refused {
reason: format!("state persist failed: {err}"),
};
}
Response::Accepted {
state: snap.intent,
protocol_version: PROTOCOL_VERSION,
}
}
async fn status_reply(
state: &Arc<Mutex<State>>,
probe: &dyn EngineProbe,
last_engine: &Arc<Mutex<EngineHealth>>,
) -> Response {
let probe_fut = probe.probe();
let fresh = match tokio::time::timeout(Duration::from_millis(500), probe_fut).await {
Ok(Ok(())) => Some(EngineHealth::Reachable {
at: chrono::Utc::now(),
}),
Ok(Err(reason)) => Some(EngineHealth::Unreachable {
at: chrono::Utc::now(),
reason,
}),
Err(_) => None,
};
if let Some(ref h) = fresh {
*last_engine.lock() = h.clone();
}
if let Some(ref fresh_h) = fresh {
let note = match fresh_h {
EngineHealth::Reachable { .. } => "engine probe: reachable".to_string(),
EngineHealth::Unreachable { reason, .. } => {
format!("engine probe: unreachable ({reason})")
}
EngineHealth::Unknown => "engine probe: unknown".to_string(),
};
state.lock().push_action(ActionKind::Probed, note);
}
let (intent, latest_action) = {
let s = state.lock();
(s.intent, s.recent_actions.first().cloned())
};
let engine = last_engine.lock().clone();
Response::Status(StatusReply {
state: intent,
engine,
latest_action,
protocol_version: PROTOCOL_VERSION,
})
}