1use std::future::Future;
27use std::io;
28use std::path::{Path, PathBuf};
29use std::pin::Pin;
30use std::sync::Arc;
31use std::time::Duration;
32
33use parking_lot::Mutex;
34use thiserror::Error;
35use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
36use tokio::net::{UnixListener, UnixStream};
37#[cfg(unix)]
38use tokio::signal::unix::{SignalKind, signal};
39use tokio::sync::{mpsc, oneshot};
40use tokio::task::JoinHandle;
41use tracing::{debug, error, info, warn};
42
43use crate::protocol::{
44 ActionKind, EngineHealth, PROTOCOL_VERSION, Request, Response, StatusReply, SupervisorState,
45};
46use crate::state::{PersistError, State};
47
48pub type ProbeFuture<'a> = Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'a>>;
53
54#[derive(Debug, Error)]
55pub enum DaemonError {
56 #[error("socket bind error at {path}: {source}")]
57 Bind {
58 path: PathBuf,
59 #[source]
60 source: io::Error,
61 },
62 #[error("socket i/o error at {path}: {source}")]
63 Socket {
64 path: PathBuf,
65 #[source]
66 source: io::Error,
67 },
68 #[error("state error: {0}")]
69 Persist(#[from] PersistError),
70 #[error("missing configuration: {0}")]
71 MissingConfig(String),
72}
73
74pub trait EngineProbe: Send + Sync + 'static {
82 fn probe(&self) -> ProbeFuture<'_>;
83}
84
85#[derive(Debug, Default)]
89pub struct AlwaysReachable;
90
91impl EngineProbe for AlwaysReachable {
92 fn probe(&self) -> ProbeFuture<'_> {
93 Box::pin(async { Ok(()) })
94 }
95}
96
97#[derive(Debug, Default)]
100pub struct AlwaysUnreachable;
101
102impl EngineProbe for AlwaysUnreachable {
103 fn probe(&self) -> ProbeFuture<'_> {
104 Box::pin(async { Err("probe fault-injected".into()) })
105 }
106}
107
108#[derive(Debug)]
113pub struct HttpEngineProbe {
114 client: zero_engine_client::HttpClient,
115}
116
117impl HttpEngineProbe {
118 #[must_use]
119 pub fn new(client: zero_engine_client::HttpClient) -> Self {
120 Self { client }
121 }
122}
123
124impl EngineProbe for HttpEngineProbe {
125 fn probe(&self) -> ProbeFuture<'_> {
126 Box::pin(async move {
127 self.client
128 .health()
129 .await
130 .map(|_| ())
131 .map_err(|e| e.to_string())
132 })
133 }
134}
135
136#[derive(Debug, Clone)]
139pub struct Config {
140 pub socket_path: PathBuf,
141 pub state_path: PathBuf,
142 pub config_present: bool,
145}
146
147impl Config {
148 #[must_use]
152 pub fn for_test(base: &Path) -> Self {
153 Self {
154 socket_path: crate::paths::socket_in(base),
155 state_path: crate::paths::state_in(base),
156 config_present: true,
157 }
158 }
159}
160
161#[derive(Debug)]
166pub struct Shutdown {
167 tx: Option<oneshot::Sender<()>>,
168 join: Option<JoinHandle<Result<(), DaemonError>>>,
169 socket_path: PathBuf,
170}
171
172impl Shutdown {
173 pub fn socket_path(&self) -> &Path {
174 &self.socket_path
175 }
176
177 pub fn shutdown(&mut self) {
179 if let Some(tx) = self.tx.take() {
180 let _ = tx.send(());
181 }
182 }
183
184 pub async fn join(mut self) -> Result<(), DaemonError> {
186 self.shutdown();
187 match self.join.take() {
188 Some(handle) => match handle.await {
189 Ok(res) => res,
190 Err(join_err) => {
191 error!(?join_err, "daemon task panicked");
192 Ok(())
193 }
194 },
195 None => Ok(()),
196 }
197 }
198}
199
200pub struct Daemon {
204 cfg: Config,
205 state: Arc<Mutex<State>>,
206 probe: Arc<dyn EngineProbe>,
207 last_engine: Arc<Mutex<EngineHealth>>,
208}
209
210impl std::fmt::Debug for Daemon {
211 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212 f.debug_struct("Daemon")
213 .field("cfg", &self.cfg)
214 .field("state", &*self.state.lock())
215 .field("last_engine", &*self.last_engine.lock())
216 .finish_non_exhaustive()
217 }
218}
219
220impl Daemon {
221 pub fn new(cfg: Config, probe: Arc<dyn EngineProbe>) -> Result<Self, DaemonError> {
225 if !cfg.config_present {
226 return Err(DaemonError::MissingConfig(
227 "zero config missing — run `zero onboard` first".into(),
228 ));
229 }
230 let state = State::load(&cfg.state_path)?;
231 Ok(Self {
232 cfg,
233 state: Arc::new(Mutex::new(state)),
234 probe,
235 last_engine: Arc::new(Mutex::new(EngineHealth::Unknown)),
236 })
237 }
238
239 pub fn spawn(self) -> Result<Shutdown, DaemonError> {
244 if self.cfg.socket_path.exists() {
249 let _ = std::fs::remove_file(&self.cfg.socket_path);
250 }
251 if let Some(parent) = self.cfg.socket_path.parent()
252 && let Err(source) = std::fs::create_dir_all(parent)
253 {
254 return Err(DaemonError::Bind {
255 path: parent.to_path_buf(),
256 source,
257 });
258 }
259
260 let listener =
261 UnixListener::bind(&self.cfg.socket_path).map_err(|source| DaemonError::Bind {
262 path: self.cfg.socket_path.clone(),
263 source,
264 })?;
265
266 info!(socket = %self.cfg.socket_path.display(), "zero-headlessd listening");
267
268 let (tx, rx) = oneshot::channel::<()>();
269 let socket_path = self.cfg.socket_path.clone();
270 let join = tokio::spawn(self.run_accept_loop(listener, rx));
271 Ok(Shutdown {
272 tx: Some(tx),
273 join: Some(join),
274 socket_path,
275 })
276 }
277
278 pub async fn run(self) -> Result<(), DaemonError> {
281 let mut handle = self.spawn()?;
282
283 #[cfg(unix)]
284 {
285 let mut term =
286 signal(SignalKind::terminate()).map_err(|source| DaemonError::Socket {
287 path: handle.socket_path.clone(),
288 source,
289 })?;
290 let mut int =
291 signal(SignalKind::interrupt()).map_err(|source| DaemonError::Socket {
292 path: handle.socket_path.clone(),
293 source,
294 })?;
295 tokio::select! {
296 _ = term.recv() => {
297 info!("SIGTERM received — draining");
298 }
299 _ = int.recv() => {
300 info!("SIGINT received — draining");
301 }
302 }
303 }
304
305 handle.shutdown();
306 handle.join().await
307 }
308
309 async fn run_accept_loop(
310 self,
311 listener: UnixListener,
312 mut shutdown_rx: oneshot::Receiver<()>,
313 ) -> Result<(), DaemonError> {
314 let (drain_permit, mut drain_wait) = mpsc::channel::<()>(1);
320
321 loop {
322 tokio::select! {
323 _ = &mut shutdown_rx => {
324 info!("shutdown requested — closing accept loop");
325 break;
326 }
327 accept = listener.accept() => {
328 match accept {
329 Ok((stream, _addr)) => {
330 let permit = drain_permit.clone();
331 let state = self.state.clone();
332 let state_path = self.cfg.state_path.clone();
333 let probe = self.probe.clone();
334 let last_engine = self.last_engine.clone();
335 tokio::spawn(async move {
336 if let Err(err) = handle_connection(
337 stream,
338 &state,
339 &state_path,
340 probe.as_ref(),
341 &last_engine,
342 )
343 .await
344 {
345 warn!(?err, "connection handler error");
346 }
347 drop(permit);
348 });
349 }
350 Err(source) => {
351 error!(?source, "accept failed");
352 }
353 }
354 }
355 }
356 }
357
358 drop(drain_permit);
359 while (drain_wait.recv().await).is_some() {}
363
364 let _ = std::fs::remove_file(&self.cfg.socket_path);
367 Ok(())
368 }
369}
370
371async fn handle_connection(
372 stream: UnixStream,
373 state: &Arc<Mutex<State>>,
374 state_path: &Path,
375 probe: &dyn EngineProbe,
376 last_engine: &Arc<Mutex<EngineHealth>>,
377) -> Result<(), DaemonError> {
378 let (read_half, mut write_half) = stream.into_split();
379 let mut reader = BufReader::new(read_half);
380 let mut line = String::new();
381 let n = reader
382 .read_line(&mut line)
383 .await
384 .map_err(|source| DaemonError::Socket {
385 path: state_path.to_path_buf(),
386 source,
387 })?;
388 if n == 0 {
389 return Ok(());
390 }
391 let trimmed = line.trim_end_matches(['\r', '\n']);
392
393 let response = match serde_json::from_str::<Request>(trimmed) {
394 Ok(req) => dispatch(req, state, state_path, probe, last_engine).await,
395 Err(err) => Response::Error {
396 reason: format!("malformed request: {err}"),
397 },
398 };
399
400 let mut reply = serde_json::to_string(&response).unwrap_or_else(|_| {
401 "{\"kind\":\"error\",\"reason\":\"internal serialize failure\"}".into()
405 });
406 reply.push('\n');
407 write_half
408 .write_all(reply.as_bytes())
409 .await
410 .map_err(|source| DaemonError::Socket {
411 path: state_path.to_path_buf(),
412 source,
413 })?;
414 write_half
415 .flush()
416 .await
417 .map_err(|source| DaemonError::Socket {
418 path: state_path.to_path_buf(),
419 source,
420 })?;
421 debug!(?response, "reply sent");
422 Ok(())
423}
424
425async fn dispatch(
426 req: Request,
427 state: &Arc<Mutex<State>>,
428 state_path: &Path,
429 probe: &dyn EngineProbe,
430 last_engine: &Arc<Mutex<EngineHealth>>,
431) -> Response {
432 match req {
433 Request::Status => status_reply(state, probe, last_engine).await,
434 Request::Start => mutate(state, state_path, |s| {
435 s.set_intent(SupervisorState::On);
436 s.push_action(ActionKind::Started, "start requested via socket");
437 }),
438 Request::Stop => mutate(state, state_path, |s| {
439 s.set_intent(SupervisorState::Off);
440 s.push_action(ActionKind::Stopped, "stop requested via socket");
441 }),
442 Request::Kill => {
443 let _ = mutate(state, state_path, |s| {
447 s.set_intent(SupervisorState::Off);
448 s.push_action(ActionKind::Killed, "kill-switch fired via socket");
449 });
450 Response::Accepted {
451 state: SupervisorState::Off,
452 protocol_version: PROTOCOL_VERSION,
453 }
454 }
462 }
463}
464
465fn mutate<F>(state: &Arc<Mutex<State>>, state_path: &Path, f: F) -> Response
466where
467 F: FnOnce(&mut State),
468{
469 let snap = {
470 let mut guard = state.lock();
471 f(&mut guard);
472 guard.clone()
473 };
474 if let Err(err) = snap.save(state_path) {
475 error!(?err, "state persist failed");
476 return Response::Refused {
477 reason: format!("state persist failed: {err}"),
478 };
479 }
480 Response::Accepted {
481 state: snap.intent,
482 protocol_version: PROTOCOL_VERSION,
483 }
484}
485
486async fn status_reply(
487 state: &Arc<Mutex<State>>,
488 probe: &dyn EngineProbe,
489 last_engine: &Arc<Mutex<EngineHealth>>,
490) -> Response {
491 let probe_fut = probe.probe();
495 let fresh = match tokio::time::timeout(Duration::from_millis(500), probe_fut).await {
496 Ok(Ok(())) => Some(EngineHealth::Reachable {
497 at: chrono::Utc::now(),
498 }),
499 Ok(Err(reason)) => Some(EngineHealth::Unreachable {
500 at: chrono::Utc::now(),
501 reason,
502 }),
503 Err(_) => None,
504 };
505 if let Some(ref h) = fresh {
506 *last_engine.lock() = h.clone();
507 }
508
509 if let Some(ref fresh_h) = fresh {
515 let note = match fresh_h {
516 EngineHealth::Reachable { .. } => "engine probe: reachable".to_string(),
517 EngineHealth::Unreachable { reason, .. } => {
518 format!("engine probe: unreachable ({reason})")
519 }
520 EngineHealth::Unknown => "engine probe: unknown".to_string(),
521 };
522 state.lock().push_action(ActionKind::Probed, note);
523 }
524
525 let (intent, latest_action) = {
526 let s = state.lock();
527 (s.intent, s.recent_actions.first().cloned())
528 };
529 let engine = last_engine.lock().clone();
530
531 Response::Status(StatusReply {
532 state: intent,
533 engine,
534 latest_action,
535 protocol_version: PROTOCOL_VERSION,
536 })
537}