pitchfork_cli/supervisor/mod.rs
1//! Supervisor module - daemon process supervisor
2//!
3//! This module is split into focused submodules:
4//! - `state`: State access layer (get/set operations)
5//! - `lifecycle`: Daemon start/stop operations
6//! - `adopt`: Re-adoption of orphaned daemons after a supervisor crash
7//! - `log_sink`: Out-of-process capture of daemon output
8//! - `autostop`: Autostop logic and boot daemon startup
9//! - `retry`: Retry logic with backoff
10//! - `watchers`: Background tasks (interval, cron, file watching)
11//! - `ipc_handlers`: IPC request dispatch
12
13mod adopt;
14mod autostop;
15mod health;
16mod hooks;
17mod idle;
18mod ipc_handlers;
19mod lifecycle;
20mod log_sink;
21#[cfg(unix)]
22mod pty;
23mod retry;
24mod state;
25mod watchers;
26
27use crate::daemon_id::DaemonId;
28use crate::daemon_status::DaemonStatus;
29use crate::deps::reverse_stop_order;
30use crate::ipc::server::{IpcServer, IpcServerHandle, StartupLock};
31
32use crate::procs::PROCS;
33use crate::settings::settings;
34use crate::state_file::StateFile;
35use crate::{Result, env};
36#[cfg(unix)]
37use duct::cmd;
38#[cfg(unix)]
39use miette::IntoDiagnostic;
40use once_cell::sync::Lazy;
41use std::collections::HashMap;
42use std::collections::HashSet;
43use std::fs;
44#[cfg(unix)]
45use std::os::unix::fs::PermissionsExt;
46use std::path::PathBuf;
47use std::process::exit;
48use std::sync::atomic;
49use std::sync::atomic::{AtomicBool, AtomicU32};
50use std::time::Duration;
51#[cfg(unix)]
52use tokio::signal::unix::SignalKind;
53use tokio::sync::{Mutex, Notify};
54use tokio::task::JoinHandle;
55use tokio::{signal, time};
56
57/// Exit statuses reaped by the container-mode zombie reaper for managed daemon
58/// PIDs. On non-Linux Unix platforms where `waitid(WNOWAIT)` is unavailable,
59/// `waitpid(None, WNOHANG)` may race with Tokio's `child.wait()`. When the
60/// zombie reaper wins, the exit status is stashed here so the monitoring task
61/// in lifecycle.rs can recover it instead of treating the ECHILD as a failure.
62///
63/// On Linux this map is unused because the reaper uses `waitid` with `WNOWAIT`
64/// to peek before reaping, which avoids the race entirely.
65#[cfg(all(unix, not(target_os = "linux")))]
66pub(crate) static REAPED_STATUSES: Lazy<Mutex<HashMap<u32, i32>>> =
67 Lazy::new(|| Mutex::new(HashMap::new()));
68
69// Re-export types needed by other modules
70pub(crate) use state::UpsertDaemonOpts;
71
72pub struct Supervisor {
73 pub(crate) state_file: Mutex<StateFile>,
74 pub(crate) pending_notifications: Mutex<Vec<(log::LevelFilter, String)>>,
75 pub(crate) last_refreshed_at: Mutex<time::Instant>,
76 /// Daemons whose retry sequence a `run` is already working
77 /// through, each with the flag that asks it to stop. The backoff between
78 /// its attempts leaves the record errored with no PID, which is exactly
79 /// what `check_retry` looks for, so without this the background checker
80 /// would start the next attempt itself and the foreground call would be
81 /// left reporting on a run it does not own. `stop` raises the flag, so the
82 /// sequence ends rather than starting another attempt behind the user's
83 /// back.
84 /// One flag per claim: two starts can be working through the same
85 /// daemon's retries at once, and a stop has to reach all of them.
86 pub(crate) retrying: std::sync::Mutex<HashMap<DaemonId, Vec<RetryClaim>>>,
87 /// How many times each daemon has been stopped. The retry checker reads
88 /// this when it decides to run an attempt and again when it is about to
89 /// start one, holding the daemon's lock: a stop in between means the
90 /// attempt it approved is one the user has since called off.
91 pub(crate) stop_epochs: std::sync::Mutex<HashMap<DaemonId, u64>>,
92 /// Map of daemon ID to scheduled autostop time
93 pub(crate) pending_autostops: Mutex<HashMap<DaemonId, time::Instant>>,
94 /// Autostop stops that have been spawned as detached tasks but have not
95 /// yet begun stopping. `cancel_pending_autostops_for_dir` flips the flag
96 /// to call off the stop when a shell re-enters the directory while the
97 /// stop task is still in flight.
98 pub(crate) in_flight_autostops:
99 Mutex<HashMap<DaemonId, std::sync::Arc<std::sync::atomic::AtomicBool>>>,
100 /// Handle for graceful IPC server shutdown
101 pub(crate) ipc_shutdown: Mutex<Option<IpcServerHandle>>,
102 /// Tracks in-flight hook tasks so shutdown can wait for them to complete
103 pub(crate) hook_tasks: Mutex<Vec<JoinHandle<()>>>,
104 /// Number of monitoring tasks that are still running (between process exit
105 /// and hook registration completion). Used by `close()` to know when it is
106 /// safe to drain `hook_tasks`.
107 pub(crate) active_monitors: AtomicU32,
108 /// Signalled by each monitoring task after it finishes registering hooks
109 /// (or decides it has nothing to register). `close()` waits on this.
110 pub(crate) monitor_done: Notify,
111 /// Cancellation token for the proxy server — cancelled on shutdown to
112 /// stop accepting new connections and drain in-flight ones.
113 pub(crate) proxy_cancel: Mutex<Option<tokio_util::sync::CancellationToken>>,
114 /// Join handle for the proxy task so shutdown can wait for cleanup.
115 pub(crate) proxy_task: Mutex<Option<JoinHandle<()>>>,
116 /// Join handle for the loopback DNS resolver, cancelled by `proxy_cancel`.
117 pub(crate) dns_task: Mutex<Option<JoinHandle<()>>>,
118 /// mDNS publisher for LAN mode (None if LAN mode is disabled).
119 /// Shared with the LAN IP monitor task so it can re-publish on IP change.
120 pub(crate) mdns_publisher:
121 Mutex<Option<std::sync::Arc<tokio::sync::Mutex<crate::proxy::mdns::MdnsPublisher>>>>,
122 /// Join handle for the LAN IP monitor task.
123 pub(crate) lan_monitor_task: Mutex<Option<JoinHandle<()>>>,
124 /// Cancellation token for the background state flush task.
125 pub(crate) flush_cancel: std::sync::Mutex<Option<tokio_util::sync::CancellationToken>>,
126 /// Daemons that currently have a live monitoring task (child `wait()`
127 /// monitor or adopted-orphan poll monitor), keyed to the PID being
128 /// monitored plus a unique registration token. Lets orphan
129 /// reconciliation tell a supervised daemon from one whose monitor died
130 /// with a previous supervisor process.
131 pub(crate) monitored: std::sync::Mutex<HashMap<DaemonId, adopt::MonitorEntry>>,
132 /// Where to deliver output a log sink reports over IPC.
133 ///
134 /// A daemon whose output is captured by a sink writes nothing this process
135 /// reads, so the sink evaluates the daemon's readiness pattern itself and
136 /// sends back the line that matched. The monitoring task registers here
137 /// before the sink starts and unregisters when it ends, so a line arriving
138 /// from a sink that outlived its daemon has nowhere to go and is dropped.
139 pub(crate) sink_output: std::sync::Mutex<HashMap<DaemonId, log_sink::Relay>>,
140 /// Per-daemon stop locks. A stop holds the daemon's lock for its whole
141 /// duration (which now includes waiting for the entire process group to
142 /// exit), and starts/orphan-cleanup acquire it first — serializing them
143 /// against in-flight stops instead of racing the Stopping window.
144 pub(crate) stop_locks: Mutex<HashMap<DaemonId, std::sync::Arc<tokio::sync::Mutex<()>>>>,
145 /// Pending readiness by daemon ID and PID. Starts handling retries publish
146 /// their final result; other background starts publish the attempt's result.
147 /// Concurrent starts await it rather than treating a spawned process as ready.
148 pub(crate) ready_checks: std::sync::Mutex<HashMap<DaemonId, ReadyCheck>>,
149 /// Set when `close()` begins. From then on this supervisor's own
150 /// state-file record is on its way out and must not be restored.
151 pub(crate) shutting_down: AtomicBool,
152 /// Set once the starts under way when shutdown began have finished (see
153 /// `freeze_starts`). Everyone who needs the final list of daemons waits
154 /// on the same freeze.
155 starts_frozen: tokio::sync::OnceCell<()>,
156}
157
158/// The result of a readiness wait: `None` while pending. If the wait ends
159/// without a result, the channel closes.
160pub(crate) type StartResult = tokio::sync::watch::Receiver<Option<crate::ipc::IpcResponse>>;
161
162#[derive(Debug)]
163pub(crate) struct RetryClaim {
164 cancel: std::sync::Arc<AtomicBool>,
165 result: Option<StartResult>,
166}
167
168#[derive(Debug, Clone)]
169pub(crate) struct ReadyCheck {
170 pid: u32,
171 result: StartResult,
172 attempt: StartResult,
173}
174
175/// A line of daemon output on its way to the monitoring task.
176#[derive(Debug, Clone)]
177pub(crate) struct OutputLine {
178 pub(crate) text: String,
179 pub(crate) source: OutputSource,
180}
181
182/// Where a line of daemon output came from, which decides what is left to do
183/// with it.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub(crate) enum OutputSource {
186 /// Read by this process from the daemon's stdout, stderr or PTY master.
187 /// Nothing has been done with it yet.
188 Local,
189 /// Reported by the daemon's log sink, which has already written the line to
190 /// the store — storing it again here would duplicate it.
191 ///
192 /// `fires_hook` is the sink's answer to whether this line passed the
193 /// `on_output` hook's filter and debounce. It is carried rather than
194 /// re-derived because a line can be reported for readiness alone, and
195 /// firing a hook that filters for something else would be wrong.
196 Sink { fires_hook: bool },
197}
198
199pub(crate) fn interval_duration() -> Duration {
200 settings().general_interval()
201}
202
203pub static SUPERVISOR: Lazy<Supervisor> =
204 Lazy::new(|| Supervisor::new().expect("Error creating supervisor"));
205
206pub async fn start_if_not_running() -> Result<()> {
207 let sf = StateFile::get();
208 if let Some(d) = sf.daemons.get(&DaemonId::pitchfork())
209 && supervisor_record_is_live(d)
210 {
211 return Ok(());
212 }
213 // The record can be missing or stale while a supervisor keeps serving
214 // IPC, e.g. when state.toml was replaced or rewritten by another tool.
215 // Starting another one would take over the socket and leave the running
216 // supervisor, and every daemon it manages, unreachable.
217 if crate::ipc::supervisor_listening().await {
218 debug!("supervisor is listening on the IPC socket but not recorded in the state file");
219 return Ok(());
220 }
221 start_in_background()
222}
223
224/// How long `supervisor start/run --force` waits for the supervisor it
225/// replaces to stop serving IPC. A supervisor being stopped keeps its socket until its daemons
226/// have stopped, which can take a while.
227pub(crate) const IPC_SOCKET_RELEASE_TIMEOUT: Duration = Duration::from_secs(30);
228
229/// How long a daemon's monitor keeps reading output left in its pipe after
230/// the process exits, before it records the exit. A child that inherited the
231/// pipe can hold it open for all of that.
232pub(crate) const EXIT_OUTPUT_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
233/// How often changes to the state are written to the state file.
234pub(crate) const STATE_FLUSH_INTERVAL: Duration = Duration::from_secs(1);
235
236/// How long `close()` waits for the LAN IP monitor to stop on its own.
237const LAN_MONITOR_STOP_WAIT: Duration = Duration::from_secs(1);
238/// How long `close()` waits for the DNS resolver to stop on its own.
239const DNS_STOP_WAIT: Duration = Duration::from_secs(5);
240/// How long `close()` waits for the proxy: longer than its own drain budget,
241/// so it finishes on its own terms rather than being cut off mid-drain.
242const PROXY_STOP_WAIT: Duration =
243 Duration::from_secs(crate::proxy::server::SHUTDOWN_DRAIN_BUDGET.as_secs() + 2);
244/// The longest `close()` can spend before it starts stopping daemons.
245const SHUTDOWN_PRE_STOP_BUDGET: Duration = Duration::from_secs(
246 LAN_MONITOR_STOP_WAIT.as_secs() + DNS_STOP_WAIT.as_secs() + PROXY_STOP_WAIT.as_secs(),
247);
248/// How long `close()` waits, once the daemons are stopped, for their
249/// monitoring tasks to register the hooks they fire.
250const MONITOR_DRAIN_WAIT: Duration = Duration::from_secs(5);
251/// How long `close()` then waits for those hooks to finish, all together.
252const HOOK_DRAIN_WAIT: Duration = Duration::from_secs(30);
253/// The longest `close()` can spend after stopping daemons.
254const SHUTDOWN_POST_STOP_BUDGET: Duration =
255 Duration::from_secs(MONITOR_DRAIN_WAIT.as_secs() + HOOK_DRAIN_WAIT.as_secs());
256
257/// Wait until no supervisor is listening on the IPC socket, failing if one
258/// still is after [`IPC_SOCKET_RELEASE_TIMEOUT`].
259///
260/// Used when replacing a supervisor: the old one keeps serving IPC while it
261/// shuts down, and binding the socket before it lets go would leave clients
262/// talking to whichever supervisor they happen to reach.
263pub(crate) async fn wait_for_ipc_socket_release() -> Result<()> {
264 let deadline = time::Instant::now() + IPC_SOCKET_RELEASE_TIMEOUT;
265 let mut waiting = false;
266 while crate::ipc::supervisor_listening().await {
267 if time::Instant::now() >= deadline {
268 return Err(miette::miette!(
269 "another pitchfork supervisor is still listening on {} after {}s; \
270 stop it with `pitchfork supervisor stop` before starting a new one",
271 crate::ipc::socket_display(),
272 IPC_SOCKET_RELEASE_TIMEOUT.as_secs()
273 ));
274 }
275 if !waiting {
276 info!(
277 "waiting for the supervisor listening on {} to shut down",
278 crate::ipc::socket_display()
279 );
280 waiting = true;
281 }
282 time::sleep(Duration::from_millis(100)).await;
283 }
284 Ok(())
285}
286
287/// Whether the supervisor's own state-file record still describes a live
288/// pitchfork supervisor, rather than a stale entry whose PID the OS has since
289/// handed to an unrelated process.
290///
291/// The record survives crashes and reboots, so a bare liveness probe on its
292/// PID is not enough: after a reboot low PIDs go to early system daemons, and
293/// a `kill(pid, 0)` on one of those says "alive". The check therefore also
294/// requires the identity the supervisor recorded about itself at startup to
295/// match the live process — see [`supervisor_identity_matches`]. When the
296/// PID is alive but the identity does not match, the record is stale; callers
297/// are free to overwrite it and must never signal that PID.
298pub(crate) fn supervisor_record_is_live(record: &crate::daemon::Daemon) -> bool {
299 let Some(pid) = record.pid else {
300 return false;
301 };
302 if !PROCS.is_running(pid) {
303 return false;
304 }
305 if record.start_time.is_none() && record.boot_time.is_none() {
306 // A record from a supervisor older than v2.18.0 carries no identity
307 // at all, so nothing can contradict it. Rather than trust any live
308 // PID, require the process to at least be a pitchfork binary: that
309 // rejects the reboot case (an unrelated system daemon on the PID)
310 // while a still-running old supervisor stays recognisable.
311 PROCS.refresh_pids(&[pid]);
312 let title = PROCS.title(pid);
313 if legacy_supervisor_title_matches(title.as_deref()) {
314 return true;
315 }
316 warn!(
317 "pid {pid} recorded for the supervisor by an older pitchfork is now {title:?}, not a pitchfork process; treating the record as stale"
318 );
319 return false;
320 }
321 if supervisor_identity_matches(
322 record.start_time,
323 PROCS.start_time(pid),
324 record.boot_time,
325 PROCS.boot_time(),
326 ) {
327 return true;
328 }
329 warn!(
330 "pid {pid} recorded for the supervisor belongs to another process now (recorded start_time {:?} boot_time {:?}, live start_time {:?} boot_time {}); treating the record as stale",
331 record.start_time,
332 record.boot_time,
333 PROCS.start_time(pid),
334 PROCS.boot_time()
335 );
336 false
337}
338
339/// Whether a live process name can be a pitchfork supervisor. Only used for
340/// legacy records that carry no start or boot time (see
341/// [`supervisor_record_is_live`]); an unreadable name is not accepted, since
342/// the record has nothing else vouching for it.
343pub(crate) fn legacy_supervisor_title_matches(title: Option<&str>) -> bool {
344 title.is_some_and(|t| t.to_ascii_lowercase().starts_with("pitchfork"))
345}
346
347/// Whether a live process can be the supervisor a state-file record describes.
348///
349/// The kernel start token is the identity, as in [`process_identity_matches`]:
350/// when both the recorded and the live token can be read, they alone decide.
351/// Equal tokens mean the same process generation; different tokens mean the
352/// PID was recycled, within this boot or across a reboot.
353///
354/// The recorded boot time is only consulted when a token is missing on either
355/// side. It must not veto matching tokens: on Linux and macOS the reported
356/// boot time is derived from the realtime clock, so an NTP step or a
357/// sleep/resume moves it while the supervisor keeps running, and treating that
358/// as a reboot would spawn a second supervisor and orphan the first. Without
359/// tokens, though, a boot time from a previous boot is the one thing that can
360/// still prove the record stale, and a record predating both fields is not
361/// contradicted by anything (callers apply a weaker check to those).
362pub(crate) fn supervisor_identity_matches(
363 recorded_start_time: Option<u64>,
364 current_start_time: Option<u64>,
365 recorded_boot_time: Option<u64>,
366 current_boot_time: u64,
367) -> bool {
368 match (recorded_start_time, current_start_time) {
369 (Some(recorded), Some(current)) => recorded == current,
370 _ => recorded_boot_time.is_none_or(|recorded| {
371 recorded.abs_diff(current_boot_time) <= BOOT_TIME_TOLERANCE_SECS
372 }),
373 }
374}
375
376/// Start the supervisor as a detached background process (`pitchfork
377/// supervisor run`). Returns once the process is spawned, not once it is
378/// ready.
379///
380/// On Unix its stderr is appended to the pitchfork log file, it leaves the
381/// caller's session, and it inherits none of the CLI's descriptors beyond
382/// stdio. On Windows it is created without inheriting any handles.
383pub fn start_in_background() -> Result<()> {
384 debug!("starting supervisor in background");
385 // Ensure the log directory exists so we can redirect stderr there.
386 // Panics and other fatal errors from the background supervisor process
387 // would otherwise be silently swallowed.
388 let log_file = &*env::PITCHFORK_LOG_FILE;
389 if let Some(parent) = log_file.parent() {
390 let _ = fs::create_dir_all(parent);
391 }
392 #[cfg(unix)]
393 fix_state_dir_permissions();
394
395 // On Unix, use duct with stderr redirected to the log file.
396 #[cfg(unix)]
397 {
398 let stderr_file = fs::OpenOptions::new()
399 .create(true)
400 .append(true)
401 .open(log_file)
402 .into_diagnostic()?;
403 cmd!(&*env::PITCHFORK_BIN, "supervisor", "run")
404 .env_remove("PITCHFORK_CONFIG")
405 .stdin_null()
406 .stdout_null()
407 .stderr_file(stderr_file)
408 .before_spawn(move |cmd| {
409 use crate::inherited_fds::CloseInheritedFds;
410 use std::os::unix::process::CommandExt;
411 // Descriptors the CLI inherited from its caller must not stay
412 // open in the long-lived supervisor; see crate::inherited_fds.
413 cmd.close_inherited_fds();
414 // SAFETY: the hook only issues the setsid syscall, which is
415 // async-signal-safe, and does not allocate.
416 unsafe {
417 cmd.pre_exec(move || {
418 // Leave the caller's session and process group. Left in
419 // them, the supervisor would receive the SIGHUP the
420 // kernel sends the foreground process group when the
421 // controlling terminal hangs up (an ssh logout, a closed
422 // terminal), and SIGHUP makes it stop every daemon.
423 // The result is deliberately ignored. In a freshly forked
424 // child setsid() fails only if a sandbox (seccomp, ...)
425 // denies it, or the child is already a process group
426 // leader, which duct never arranges. Failing the spawn
427 // would stop pitchfork working at all there, which is
428 // worse than a supervisor that is merely not detached:
429 // that is how it behaved before. This hook cannot log
430 // (async-signal-safe only), so it cannot warn either.
431 let _ = libc::setsid();
432 Ok(())
433 });
434 }
435 Ok(())
436 })
437 .start()
438 .into_diagnostic()?;
439 }
440
441 // On Windows, use CreateProcessW directly with bInheritHandles=FALSE.
442 // std::process::Command always sets bInheritHandles=TRUE when any stdio
443 // handle is configured (even Stdio::null()), which causes the background
444 // supervisor to inherit ALL inheritable handles from the parent —
445 // including bats' stdout capture pipe. The supervisor keeps the pipe
446 // open after the CLI exits, and bats hangs forever waiting for EOF.
447 //
448 // CreateProcessW with bInheritHandles=FALSE prevents any handle
449 // inheritance. We pass NUL device handles for stdin/stdout/stderr
450 // via STARTUPINFO without inheriting any parent handles.
451 #[cfg(windows)]
452 {
453 use windows_sys::Win32::Foundation::{CloseHandle, FALSE};
454 use windows_sys::Win32::System::Threading::{
455 CREATE_NO_WINDOW, CREATE_UNICODE_ENVIRONMENT, CreateProcessW, DETACHED_PROCESS,
456 PROCESS_INFORMATION, STARTUPINFOW,
457 };
458
459 // With bInheritHandles=FALSE, the child inherits NO parent handles.
460 // The supervisor uses its own internal file-based logger
461 // (PITCHFORK_LOG_FILE), so it doesn't need stdio from the parent.
462 // We don't set STARTF_USESTDHANDLES because that flag requires
463 // bInheritHandles=TRUE to function correctly per Microsoft docs.
464 // Without stdio handles, the detached process gets null stdio by
465 // default, which is exactly what we want.
466 let mut si: STARTUPINFOW = unsafe { std::mem::zeroed() };
467 si.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
468
469 let bin_path = &*env::PITCHFORK_BIN;
470 let mut cmd_line: Vec<u16> = format!("\"{}\" supervisor run\0", bin_path.to_string_lossy())
471 .encode_utf16()
472 .collect();
473
474 use std::os::windows::ffi::OsStrExt;
475 let mut vars: Vec<_> = std::env::vars_os()
476 .filter(|(k, _)| !k.to_string_lossy().eq_ignore_ascii_case("PITCHFORK_CONFIG"))
477 .collect();
478 vars.sort_by_key(|(k, _)| k.to_string_lossy().to_uppercase());
479 let mut environment = Vec::<u16>::new();
480 for (key, value) in vars {
481 environment.extend(key.encode_wide());
482 environment.push(b'=' as u16);
483 environment.extend(value.encode_wide());
484 environment.push(0);
485 }
486 environment.extend([0, 0]);
487 let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
488 let ok = unsafe {
489 CreateProcessW(
490 std::ptr::null(),
491 cmd_line.as_mut_ptr(),
492 std::ptr::null(),
493 std::ptr::null(),
494 FALSE, // bInheritHandles = FALSE — the whole point
495 DETACHED_PROCESS | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
496 environment.as_ptr().cast(),
497 std::ptr::null(),
498 &si,
499 &mut pi,
500 )
501 };
502
503 if ok == 0 {
504 return Err(miette::miette!(
505 "CreateProcessW failed for supervisor: {}",
506 std::io::Error::last_os_error()
507 ));
508 }
509
510 // Close process/thread handles — we don't need them (detached process).
511 unsafe {
512 CloseHandle(pi.hProcess);
513 CloseHandle(pi.hThread);
514 }
515 }
516
517 Ok(())
518}
519
520/// Decide whether a project session should be removed during refresh.
521///
522/// `recorded_title` is the title snapshot taken at the start of refresh.
523/// `session` is the current state entry re-read under the lock. If the state
524/// has been updated since the snapshot (e.g., re-entered with the same
525/// PID/dir but a new title), we must skip removal to avoid deleting the new
526/// session. The host PID lives in the session key now, so there is no
527/// `liveness_pid` field to compare against.
528#[cfg(any(unix, test))]
529fn should_remove_liveness_session(
530 session: &crate::state_file::ProjectSession,
531 recorded_title: &Option<String>,
532 current_title: Option<&str>,
533 is_running: bool,
534) -> bool {
535 // If the state was updated since the snapshot (e.g., re-entered with the
536 // same PID/dir but a new title), skip removal to avoid deleting the new
537 // session.
538 if session.liveness_title.as_ref() != recorded_title.as_ref() {
539 return false;
540 }
541 // Dead host process — evict.
542 if !is_running {
543 return true;
544 }
545 // Host is alive. Evict only on a real title mismatch (PID reuse). If no
546 // title was recorded, or the current title is unavailable, we cannot
547 // reliably detect PID reuse — keep the session rather than risk evicting
548 // a live process.
549 match (recorded_title.as_deref(), current_title) {
550 (Some(recorded), Some(current)) => recorded != current,
551 _ => false,
552 }
553}
554
555/// How long stopping `daemons` can take on shutdown, on top of `base`.
556///
557/// The supervisor stops its daemons dependents first, one level after
558/// another, and each can take its whole stop timeout plus the wait after
559/// SIGKILL. Killed before it is done, the supervisor leaves the daemons of the
560/// later levels running with no supervisor. So `base` (the
561/// `supervisor.stop_timeout` setting, also each daemon's default timeout) is
562/// extended by every running daemon's stop in turn: an upper bound, since the
563/// daemons of one level stop at the same time.
564pub(crate) fn daemons_stop_budget<'a>(
565 daemons: impl IntoIterator<Item = &'a crate::daemon::Daemon>,
566 base: std::time::Duration,
567) -> std::time::Duration {
568 let pitchfork_id = DaemonId::pitchfork();
569 daemons
570 .into_iter()
571 .filter(|d| d.pid.is_some() && d.id != pitchfork_id)
572 .map(|d| {
573 // A daemon without its own timeout is given the supervisor's.
574 let timeout = d.stop_signal.and_then(|s| s.timeout).unwrap_or(base);
575 timeout + crate::procs::PROCESS_GROUP_SIGKILL_WAIT
576 })
577 .fold(base, |total, stop| total.saturating_add(stop))
578}
579
580/// The longest the supervisor's whole shutdown can take with `daemons` to
581/// stop, so `supervisor stop` can allow for it before killing the supervisor:
582/// the daemons' stops (see [`daemons_stop_budget`]) and what `close()` does
583/// before and after them.
584pub(crate) fn shutdown_budget<'a>(
585 daemons: impl IntoIterator<Item = &'a crate::daemon::Daemon>,
586 base: std::time::Duration,
587) -> std::time::Duration {
588 daemons_stop_budget(daemons, base)
589 .saturating_add(SHUTDOWN_PRE_STOP_BUDGET)
590 .saturating_add(SHUTDOWN_POST_STOP_BUDGET)
591}
592
593/// Set when a graceful shutdown begins, by a signal or a `Shutdown` request.
594/// A signal received after that forces the exit (see `force_exit`).
595static SHUTDOWN_BEGUN: AtomicBool = AtomicBool::new(false);
596
597/// Taken by whichever exit ends the process: a graceful stop once `close()`
598/// has returned, or a forced exit as soon as it starts. The other then waits
599/// for the process to end instead of exiting with its own status, so a forced
600/// exit's status cannot be overtaken by a graceful exit with success.
601static EXIT_CLAIMED: AtomicBool = AtomicBool::new(false);
602
603/// Wait for an exit another path has claimed; it ends the process.
604async fn wait_for_claimed_exit() -> ! {
605 loop {
606 std::future::pending::<()>().await;
607 }
608}
609
610/// End a graceful stop with success, unless a forced exit claimed the process
611/// first.
612async fn exit_gracefully() -> ! {
613 if EXIT_CLAIMED.swap(true, atomic::Ordering::SeqCst) {
614 wait_for_claimed_exit().await
615 }
616 exit(0)
617}
618
619impl Supervisor {
620 pub fn new() -> Result<Self> {
621 Ok(Self {
622 state_file: Mutex::new(StateFile::read(&*env::PITCHFORK_STATE_FILE).unwrap_or_else(
623 |e| {
624 warn!("failed to read state file, starting with empty state: {e}");
625 StateFile::new(env::PITCHFORK_STATE_FILE.clone())
626 },
627 )),
628 last_refreshed_at: Mutex::new(time::Instant::now()),
629 pending_notifications: Mutex::new(vec![]),
630 retrying: std::sync::Mutex::new(HashMap::new()),
631 stop_epochs: std::sync::Mutex::new(HashMap::new()),
632 pending_autostops: Mutex::new(HashMap::new()),
633 in_flight_autostops: Mutex::new(HashMap::new()),
634 ipc_shutdown: Mutex::new(None),
635 hook_tasks: Mutex::new(Vec::new()),
636 active_monitors: AtomicU32::new(0),
637 monitor_done: Notify::new(),
638 proxy_cancel: Mutex::new(None),
639 proxy_task: Mutex::new(None),
640 dns_task: Mutex::new(None),
641 mdns_publisher: Mutex::new(None),
642 lan_monitor_task: Mutex::new(None),
643 flush_cancel: std::sync::Mutex::new(None),
644 monitored: std::sync::Mutex::new(HashMap::new()),
645 sink_output: std::sync::Mutex::new(HashMap::new()),
646 stop_locks: Mutex::new(HashMap::new()),
647 ready_checks: std::sync::Mutex::new(HashMap::new()),
648 shutting_down: AtomicBool::new(false),
649 starts_frozen: tokio::sync::OnceCell::new(),
650 })
651 }
652
653 /// Get (or create) the per-daemon stop lock for `id`.
654 pub(crate) async fn stop_lock(&self, id: &DaemonId) -> std::sync::Arc<tokio::sync::Mutex<()>> {
655 self.stop_locks
656 .lock()
657 .await
658 .entry(id.clone())
659 .or_default()
660 .clone()
661 }
662
663 /// A restart in flight when the previous supervisor exited will never
664 /// finish: no one is left to start the new process. A record it left
665 /// without a process is recorded as stopped, and one whose old process
666 /// was still being stopped as stopping, which is what a plain stop
667 /// interrupted at the same point leaves for orphan cleanup to reconcile.
668 async fn settle_interrupted_restarts(&self) {
669 let mut state_file = self.state_file.lock().await;
670 let restarting: Vec<(DaemonId, bool)> = state_file
671 .daemons
672 .values()
673 .filter(|d| d.status.is_restarting())
674 .map(|d| (d.id.clone(), d.pid.is_some()))
675 .collect();
676 for (id, has_pid) in restarting {
677 let status = if has_pid {
678 DaemonStatus::Stopping
679 } else {
680 DaemonStatus::Stopped
681 };
682 debug!(
683 "daemon {id} was left restarting by a previous supervisor; recording it as {status}"
684 );
685 state_file.set_status(&id, status);
686 }
687 }
688
689 pub async fn start(
690 &self,
691 is_boot: bool,
692 container: bool,
693 web_port: Option<u16>,
694 web_path: Option<String>,
695 ) -> Result<()> {
696 // Ensure the state directory and its contents are accessible by non-root
697 // users. This is needed when the supervisor is started with `sudo` — all
698 // files it creates are owned by root, which prevents normal CLI clients
699 // from reading/writing state or connecting to the IPC socket.
700 #[cfg(unix)]
701 fix_state_dir_permissions();
702
703 // Ignoring Ctrl+C is inherited, so a supervisor started from a process
704 // that ignores it would neither see Ctrl+C itself nor let its daemons
705 // see it: a daemon with `stop_signal = "SIGINT"` would never get the
706 // Ctrl+C sent to stop it. Handle it again before any daemon starts.
707 #[cfg(windows)]
708 if unsafe { windows_sys::Win32::System::Console::SetConsoleCtrlHandler(None, 0) } == 0 {
709 warn!(
710 "failed to stop ignoring Ctrl+C: {}",
711 std::io::Error::last_os_error()
712 );
713 }
714
715 // Refuse to run beside a supervisor that is already listening, and
716 // do so before recording ourselves in the state file or starting any
717 // daemons: taking over its socket would leave it running but
718 // unreachable. (`--force` has already waited for the one it replaced
719 // to let go of the socket.) The lock is held until our own listener
720 // is bound, so a supervisor starting at the same time waits here and
721 // then finds this one listening.
722 let startup_lock = StartupLock::acquire().await?;
723 if crate::ipc::supervisor_listening().await {
724 return Err(miette::miette!(
725 "another pitchfork supervisor is already listening on {}",
726 crate::ipc::socket_display()
727 ));
728 }
729
730 let pid = std::process::id();
731 // Ensure PROCS has data for the supervisor PID before upsert_daemon reads title()
732 PROCS.refresh_pids(&[pid]);
733 // Determine container mode: CLI flag takes priority, then settings.
734 // Running as PID 1 always enables it: orphaned descendants of daemons
735 // re-parent to us, and without the zombie reaper they would accumulate
736 // as unreaped zombies — which also keep their process group alive,
737 // stalling whole-group stop waits indefinitely.
738 let container_mode =
739 container || settings().supervisor.container || std::process::id() == 1;
740 if container_mode {
741 info!("Starting supervisor in container/PID1 mode with pid {pid}");
742 } else {
743 info!("Starting supervisor with pid {pid}");
744 }
745
746 // Whether the previous supervisor exited uncleanly must be read before
747 // we record ourselves in the state file just below (see
748 // `supervisor_exited_uncleanly`); the background cleanup task runs
749 // after that record exists, so it receives the answer instead of
750 // reading it too late.
751 let unclean = supervisor_exited_uncleanly(self).await;
752
753 self.upsert_daemon(
754 UpsertDaemonOpts::builder(DaemonId::pitchfork())
755 .set(|o| {
756 o.pid = Some(pid);
757 o.status = DaemonStatus::Running;
758 })
759 .build(),
760 )
761 .await?;
762 self.settle_interrupted_restarts().await;
763 #[cfg(unix)]
764 fix_state_dir_permissions();
765
766 // Self-heal: if the boot registration points to a stale binary path
767 // (e.g. after a brew/mise upgrade), re-register with the current path.
768 // Runs in the background — must not block or fail supervisor startup.
769 tokio::task::spawn_blocking(|| {
770 if let Ok(boot_manager) = crate::boot_manager::BootManager::new() {
771 boot_manager.check_and_reregister_if_stale();
772 }
773 });
774
775 // If the previous supervisor died uncleanly, its daemon child processes
776 // may still be alive (orphaned, re-parented to init). Terminate them
777 // before starting replacements so we don't end up with duplicate
778 // processes holding the same ports.
779 //
780 // This runs in the background: each orphan kill now waits for its
781 // whole process group to exit (seconds per orphan), and doing that
782 // inline would delay IPC socket creation past the CLI's short connect
783 // budget on autostart. Per-daemon stop locks serialize the cleanup
784 // against any Run/Stop requests that arrive for the same daemon in the
785 // meantime, and boot daemons start after cleanup completes so they
786 // cannot observe an orphan as "already running".
787 let boot_after_cleanup = is_boot;
788 tokio::spawn(async move {
789 cleanup_orphaned_daemons(&SUPERVISOR, unclean).await;
790 if boot_after_cleanup {
791 info!("Boot start mode enabled, starting boot_start daemons");
792 if let Err(e) = SUPERVISOR.start_boot_daemons().await {
793 error!("failed to start boot daemons: {e}");
794 }
795 }
796 });
797
798 self.interval_watch()?;
799
800 // Run the first cron check synchronously before starting the cron
801 // watcher and IPC server. This registers config-only cron daemons and
802 // fires any `immediate=true` triggers in the foreground, so they cannot
803 // race with a concurrent `pitchfork start` IPC. By the time the cron
804 // watcher's first tick runs, `last_cron_triggered` is already anchored
805 // and the immediate daemons are already running.
806 if let Err(e) = self.check_cron_schedules().await {
807 error!("failed to check cron schedules on startup: {e}");
808 }
809
810 self.cron_watch()?;
811 self.signals()?;
812 self.daemon_file_watch().await?;
813
814 // In container mode, install SIGCHLD handler to reap orphaned/zombie processes
815 #[cfg(unix)]
816 if container_mode {
817 self.reap_zombies()?;
818 }
819
820 // Start web server: CLI --web-port takes priority, then settings.web.auto_start + bind_port
821 let s = settings();
822 let effective_port = web_port.or_else(|| {
823 if s.web.auto_start {
824 match u16::try_from(s.web.bind_port).ok().filter(|&p| p > 0) {
825 Some(p) => Some(p),
826 None => {
827 error!(
828 "web.bind_port {} is out of valid port range (1-65535), web UI disabled",
829 s.web.bind_port
830 );
831 None
832 }
833 }
834 } else {
835 None
836 }
837 });
838 // CLI --web-path takes priority, then settings.web.base_path
839 let effective_path = web_path.or_else(|| {
840 let bp = s.web.base_path.clone();
841 if bp.is_empty() { None } else { Some(bp) }
842 });
843 if let Some(port) = effective_port {
844 tokio::spawn(async move {
845 if let Err(e) = crate::web::serve(port, effective_path).await {
846 error!("Web server error: {e}");
847 }
848 });
849 }
850
851 // Start standalone API server if configured
852 let api_port = if s.api.auto_start {
853 match u16::try_from(s.api.bind_port).ok().filter(|&p| p > 0) {
854 Some(p) => Some(p),
855 None => {
856 error!(
857 "api.bind_port {} is out of valid port range (1-65535), API server disabled",
858 s.api.bind_port
859 );
860 None
861 }
862 }
863 } else {
864 None
865 };
866 if let Some(port) = api_port {
867 tokio::spawn(async move {
868 if let Err(e) = crate::web::serve_api(port, None).await {
869 error!("API server error: {e}");
870 }
871 });
872 }
873
874 // Start reverse proxy server if enabled
875 if s.proxy.enable {
876 // Pre-generate the TLS certificate synchronously before spawning the proxy
877 // task. This ensures the cert exists immediately after `sup start` returns,
878 // so `proxy trust` can be run right away without waiting for the async task.
879 #[cfg(feature = "proxy-tls")]
880 if s.proxy.https {
881 let proxy_dir = crate::env::PITCHFORK_STATE_DIR.join("proxy");
882 let ca_cert_path = proxy_dir.join("ca.pem");
883 let ca_key_path = proxy_dir.join("ca-key.pem");
884 // Checked and written under the CA lock: `proxy setup` may be
885 // generating the same pair right now.
886 match crate::proxy::server::ensure_ca(&ca_cert_path, &ca_key_path, || {
887 ca_cert_path.exists() && ca_key_path.exists()
888 }) {
889 Ok(true) => {
890 info!(
891 "Generated local CA certificate at {}",
892 ca_cert_path.display()
893 );
894 }
895 Ok(false) => {}
896 Err(e) => {
897 error!("Failed to generate CA certificate: {e}");
898 }
899 }
900
901 // Auto-trust: attempt to install the CA certificate into the
902 // system trust store. May fail silently due to permissions;
903 // user can run `pitchfork proxy trust` manually.
904 if s.proxy.auto_trust && ca_cert_path.exists() {
905 use crate::proxy::trust::{AutoTrustResult, auto_trust};
906 match auto_trust(&ca_cert_path) {
907 AutoTrustResult::AlreadyTrusted => {}
908 AutoTrustResult::Trusted => {
909 info!("CA certificate auto-trusted in system store");
910 }
911 AutoTrustResult::NotTrusted { reason } => {
912 warn!("Auto-trust skipped: {reason}");
913 warn!("Run `pitchfork proxy trust` to install manually");
914 }
915 }
916 }
917 }
918 // Spawn the proxy server and wait for its bind result via a oneshot
919 // channel. This avoids the TOCTOU race of a pre-flight bind check
920 // while still surfacing binding failures immediately.
921 let (bind_tx, bind_rx) = tokio::sync::oneshot::channel();
922 let proxy_cancel = tokio_util::sync::CancellationToken::new();
923 let proxy_cancel_clone = proxy_cancel.clone();
924 *self.proxy_cancel.lock().await = Some(proxy_cancel);
925 let proxy_task = tokio::spawn(async move {
926 if let Err(e) = crate::proxy::server::serve(bind_tx, proxy_cancel_clone).await {
927 error!("Proxy server error: {e}");
928 }
929 });
930 *self.proxy_task.lock().await = Some(proxy_task);
931 match bind_rx.await {
932 Ok(Ok(())) => {
933 info!("Proxy server bound successfully");
934 // Resolved once and shared: mDNS and the DNS resolver
935 // must advertise the same address.
936 let lan_ip = self.resolve_lan_ip().await;
937 self.start_mdns(lan_ip).await;
938 self.start_dns_resolver(lan_ip).await;
939 }
940 Ok(Err(msg)) => {
941 error!("{msg}");
942 self.add_notification(log::LevelFilter::Error, msg).await;
943 }
944 Err(_) => {
945 // Sender dropped without sending — serve() panicked or
946 // returned before signalling. Already logged by the
947 // spawn error handler above.
948 }
949 }
950 }
951
952 // Pre-warm slug cache so the first /api/proxies request is fast.
953 // Spawned as a background task so it does not block startup.
954 tokio::spawn(async {
955 crate::proxy::server::get_cached_slugs().await;
956 });
957
958 let (ipc, ipc_handle) = IpcServer::new(startup_lock).await?;
959 *self.ipc_shutdown.lock().await = Some(ipc_handle);
960 self.start_state_flush_task();
961 self.conn_watch(ipc).await
962 }
963
964 /// Start the loopback DNS resolver for the proxy TLD.
965 ///
966 /// The resolver shares the proxy's cancellation token, so it stops with the
967 /// proxy. A bind failure is a notification rather than a fatal error: the
968 /// proxy still works for anyone who reaches it some other way.
969 async fn start_dns_resolver(&self, lan_ip: Option<std::net::Ipv4Addr>) {
970 let s = crate::settings::settings();
971 if !s.proxy.dns {
972 return;
973 }
974 let cfg = crate::proxy::dns::config_from_settings(&s, lan_ip);
975 let port = crate::proxy::dns::dns_port(&s);
976 // Loopback only: the resolver is for this machine's stub resolver, and
977 // LAN peers are served by mDNS instead.
978 let addr = std::net::SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, port));
979
980 // The token's guard is held until the handle is stored. `close` takes
981 // the token under this lock before it collects `dns_task`, so it either
982 // runs first — and there is no token to spawn with — or waits until
983 // the handle is in place to be drained. Releasing it earlier left a
984 // window where `close` found no handle and the task outlived shutdown
985 // holding the resolver's sockets.
986 let cancel_guard = self.proxy_cancel.lock().await;
987 let Some(cancel) = cancel_guard.clone() else {
988 return;
989 };
990 let (bind_tx, bind_rx) = tokio::sync::oneshot::channel();
991 let task = tokio::spawn(async move {
992 if let Err(e) = crate::proxy::dns::serve(cfg, addr, bind_tx, cancel).await {
993 error!("DNS resolver error: {e}");
994 }
995 });
996 *self.dns_task.lock().await = Some(task);
997 drop(cancel_guard);
998 match bind_rx.await {
999 Ok(Ok(())) => info!("DNS resolver bound successfully"),
1000 Ok(Err(msg)) => {
1001 let msg = format!(
1002 "{msg}\nProxy host names will not resolve through pitchfork. \
1003 Choose another port with proxy.dns_port, or set proxy.dns = false."
1004 );
1005 error!("{msg}");
1006 self.add_notification(log::LevelFilter::Error, msg).await;
1007 }
1008 Err(_) => {}
1009 }
1010 }
1011
1012 /// Watch the LAN address and keep the DNS responder, and mDNS when it is
1013 /// running, pointed at the current one.
1014 ///
1015 /// Started even when the mDNS publisher could not be created: the DNS
1016 /// responder serves this machine regardless, and an address it keeps
1017 /// answering with after the interface has moved is worse than useless.
1018 ///
1019 /// Does nothing when `proxy.lan_ip` pins an address. That is a choice to
1020 /// respect, not a starting point to drift from — the check lives here so
1021 /// neither caller can forget it.
1022 async fn start_lan_ip_monitor(
1023 &self,
1024 initial_ip: std::net::Ipv4Addr,
1025 port: u16,
1026 publisher: Option<std::sync::Arc<tokio::sync::Mutex<crate::proxy::mdns::MdnsPublisher>>>,
1027 ) {
1028 if !crate::settings::settings().proxy.lan_ip.is_empty() {
1029 return;
1030 }
1031 // No cancellation token means `close` has already taken it, so shutdown
1032 // is under way. Spawning here would leave a task polling with no way to
1033 // stop it, and past the point where `close` collects the handle.
1034 //
1035 // Held until the handle is stored, for the reason `start_dns_resolver`
1036 // gives: otherwise `close` can collect `lan_monitor_task` in between.
1037 let cancel_guard = self.proxy_cancel.lock().await;
1038 let Some(cancel) = cancel_guard.clone() else {
1039 debug!("Not starting the LAN IP monitor: the supervisor is shutting down");
1040 return;
1041 };
1042 let monitor_cancel = Some(cancel);
1043 let task = tokio::spawn(async move {
1044 let mut last_ip = initial_ip;
1045 let mut ticker = tokio::time::interval(std::time::Duration::from_secs(5));
1046 ticker.tick().await; // first tick is immediate
1047 loop {
1048 // Cancellation is raced against the tick, not checked after
1049 // it. Checking afterwards means the task only notices once the
1050 // full interval has elapsed, so a shutdown that waits a second
1051 // for it always gives up and aborts instead — the graceful
1052 // path would never once be taken.
1053 match monitor_cancel.as_ref() {
1054 Some(cancel) => {
1055 tokio::select! {
1056 _ = ticker.tick() => {}
1057 _ = cancel.cancelled() => break,
1058 }
1059 }
1060 None => {
1061 ticker.tick().await;
1062 }
1063 }
1064 if let Some(new_ip) = crate::proxy::lan_ip::detect_lan_ip_if_changed(last_ip).await
1065 {
1066 log::info!("LAN IP changed: {last_ip} → {new_ip}");
1067 last_ip = new_ip;
1068 crate::proxy::dns::update_lan_ip(new_ip);
1069 if let Some(publisher) = publisher.as_ref() {
1070 publisher.lock().await.republish_all(new_ip, port);
1071 }
1072 }
1073 }
1074 });
1075 *self.lan_monitor_task.lock().await = Some(task);
1076 drop(cancel_guard);
1077 }
1078
1079 /// Start mDNS publishing for LAN mode (called after the proxy binds successfully).
1080 /// The LAN address mDNS publishes and the DNS resolver answers with.
1081 ///
1082 /// Resolved once and handed to both. Detecting separately in each let them
1083 /// disagree when the interface address changed in between, which would
1084 /// advertise one address over mDNS and serve another over DNS, and probed
1085 /// the network twice at startup for one answer.
1086 ///
1087 /// `None` means LAN mode is off, or is on and the address could not be
1088 /// determined; either way the caller has nothing to publish. The reason is
1089 /// reported here so it is said once rather than by each caller.
1090 async fn resolve_lan_ip(&self) -> Option<std::net::Ipv4Addr> {
1091 let s = crate::settings::settings();
1092 let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
1093 if !s.proxy.enable || !lan_enabled {
1094 return None;
1095 }
1096 if s.proxy.lan_ip.is_empty() {
1097 let detected = crate::proxy::lan_ip::detect_lan_ip().await;
1098 if detected.is_none() {
1099 error!(
1100 "LAN mode is enabled but no LAN IP address could be detected. \
1101 Set proxy.lan_ip to a specific address, or ensure you are connected to a network."
1102 );
1103 }
1104 return detected;
1105 }
1106 match s.proxy.lan_ip.parse::<std::net::Ipv4Addr>() {
1107 Ok(ip) => Some(ip),
1108 Err(e) => {
1109 let msg = format!(
1110 concat!(
1111 "proxy.lan_ip {:?} is not a valid IPv4 address: {}. ",
1112 "LAN mode will not start; fix the setting or clear it ",
1113 "to auto-detect."
1114 ),
1115 s.proxy.lan_ip, e
1116 );
1117 error!("{msg}");
1118 self.add_notification(log::LevelFilter::Error, msg).await;
1119 None
1120 }
1121 }
1122 }
1123
1124 async fn start_mdns(&self, lan_ip: Option<std::net::Ipv4Addr>) {
1125 let s = crate::settings::settings();
1126 let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
1127 if !s.proxy.enable || !lan_enabled {
1128 return;
1129 }
1130
1131 let Some(lan_ip) = lan_ip else { return };
1132 let port = u16::try_from(s.proxy.port).unwrap_or(443);
1133
1134 let Some(mut publisher) = crate::proxy::mdns::MdnsPublisher::new(lan_ip) else {
1135 error!("Failed to start mDNS publisher. Is Avahi (Linux) or Bonjour (macOS) running?");
1136 // The DNS responder hands out this address too, and it is useful on
1137 // this machine whether or not mDNS came up. Keep watching the
1138 // interface so its answers do not go stale.
1139 self.start_lan_ip_monitor(lan_ip, port, None).await;
1140 return;
1141 };
1142
1143 // Publish all registered slugs.
1144 let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
1145 for slug in slugs.keys() {
1146 let hostname = format!("{slug}.local");
1147 publisher.publish(&hostname, port);
1148 }
1149
1150 log::info!(
1151 "LAN mode: mDNS publishing on {lan_ip}, {} slug(s) registered",
1152 slugs.len()
1153 );
1154
1155 let publisher = std::sync::Arc::new(tokio::sync::Mutex::new(publisher));
1156
1157 // Start the IP monitor. It declines on its own when the address is
1158 // pinned rather than auto-detected.
1159 self.start_lan_ip_monitor(lan_ip, port, Some(publisher.clone()))
1160 .await;
1161
1162 *self.mdns_publisher.lock().await = Some(publisher);
1163 }
1164
1165 /// Re-read slugs from config and update mDNS records.
1166 ///
1167 /// Publishes new slugs and unpublishes removed ones. Called via IPC when
1168 /// `proxy add` or `proxy remove` modifies the slug registry.
1169 async fn sync_mdns(&self) {
1170 // Clone the Arc and release the outer lock immediately so we don't
1171 // block close() from taking the publisher during shutdown.
1172 let publisher = {
1173 let guard = self.mdns_publisher.lock().await;
1174 match guard.as_ref() {
1175 Some(p) => p.clone(),
1176 None => {
1177 debug!("sync_mdns: mDNS publisher not active, skipping");
1178 return;
1179 }
1180 }
1181 };
1182
1183 let s = crate::settings::settings();
1184 let port = u16::try_from(s.proxy.port).unwrap_or(443);
1185
1186 let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
1187 let mut pub_guard = publisher.lock().await;
1188
1189 // Unpublish slugs that no longer exist in config.
1190 let current_keys: Vec<&String> = slugs.keys().collect();
1191 let registered: Vec<String> = pub_guard.registered_hostnames();
1192 for hostname in ®istered {
1193 // hostname is "slug.local" — extract slug part.
1194 let slug = hostname.strip_suffix(".local").unwrap_or(hostname);
1195 if !current_keys.iter().any(|k| k.as_str() == slug) {
1196 log::info!("mDNS: unpublishing removed slug {slug}");
1197 pub_guard.unpublish(hostname);
1198 }
1199 }
1200
1201 // Publish new slugs that aren't yet registered.
1202 for slug in slugs.keys() {
1203 let hostname = format!("{slug}.local");
1204 if !pub_guard.is_published(&hostname) {
1205 log::info!("mDNS: publishing new slug {slug}");
1206 pub_guard.publish(&hostname, port);
1207 }
1208 }
1209 }
1210
1211 /// Spawn a background task that periodically flushes the state file to
1212 /// disk if it has been marked dirty. Uses debouncing (1s interval) to
1213 /// batch rapid state changes.
1214 fn start_state_flush_task(&self) {
1215 let cancel = tokio_util::sync::CancellationToken::new();
1216 *self.flush_cancel.lock().unwrap() = Some(cancel.clone());
1217 tokio::spawn(async move {
1218 let mut interval = time::interval(STATE_FLUSH_INTERVAL);
1219 interval.set_missed_tick_behavior(time::MissedTickBehavior::Skip);
1220 loop {
1221 tokio::select! {
1222 _ = interval.tick() => {}
1223 _ = cancel.cancelled() => {
1224 debug!("state flush task received shutdown signal");
1225 break;
1226 }
1227 }
1228 let state = SUPERVISOR.state_file.lock().await;
1229 if state.is_dirty()
1230 && let Err(e) = state.write()
1231 {
1232 warn!("failed to flush state file: {e}");
1233 }
1234 }
1235 debug!("state flush task exiting");
1236 });
1237 }
1238
1239 pub(crate) async fn flush_state(&self) {
1240 let state = self.state_file.lock().await;
1241 if state.is_dirty()
1242 && let Err(e) = state.write()
1243 {
1244 warn!("failed to flush state file: {e}");
1245 }
1246 }
1247
1248 pub(crate) async fn refresh(&self) -> Result<()> {
1249 trace!("refreshing");
1250
1251 // Collect PIDs we need to check (shell PIDs and liveness PIDs)
1252 // This is more efficient than refreshing all processes on the system
1253 let dirs_with_pids = self.get_dirs_with_shell_pids().await;
1254 let liveness_sessions = self.get_liveness_sessions().await;
1255 let pids_to_check: Vec<u32> = dirs_with_pids
1256 .values()
1257 .flatten()
1258 .copied()
1259 .chain(liveness_sessions.iter().map(|(pid, _, _)| *pid))
1260 .collect::<std::collections::HashSet<_>>()
1261 .into_iter()
1262 .collect();
1263
1264 if pids_to_check.is_empty() {
1265 // No PIDs to check, skip the expensive refresh
1266 trace!("no tracked PIDs to check, skipping process refresh");
1267 } else {
1268 debug!("refreshing PIDs: {pids_to_check:?}");
1269 PROCS.refresh_pids(&pids_to_check);
1270 }
1271
1272 let mut last_refreshed_at = self.last_refreshed_at.lock().await;
1273 *last_refreshed_at = time::Instant::now();
1274
1275 self.restore_own_record().await;
1276
1277 #[cfg_attr(not(unix), allow(unused_mut))]
1278 let mut dirs_to_leave: Vec<PathBuf> = Vec::new();
1279
1280 // Prune shell PIDs that are no longer running. This is essential on
1281 // Unix so that exited shells don't keep daemons alive forever.
1282 //
1283 // On Windows, skip this check: Git Bash (MSYS2) PIDs from `$$` are
1284 // Cygwin-internal PIDs that are invisible to sysinfo (which sees
1285 // Windows PIDs). The is_running check would always return false,
1286 // immediately removing every registered shell and breaking autostop.
1287 // Shell registration/deregistration relies on UpdateShellDir IPC
1288 // messages instead.
1289 #[cfg(unix)]
1290 for (dir, pids) in dirs_with_pids {
1291 let to_remove = pids
1292 .iter()
1293 .filter(|pid| !PROCS.is_running(**pid))
1294 .collect::<Vec<_>>();
1295 for pid in &to_remove {
1296 self.remove_shell_pid(**pid).await?
1297 }
1298 if to_remove.len() == pids.len() {
1299 dirs_to_leave.push(dir);
1300 }
1301 }
1302
1303 // Atomically remove project sessions whose host PID has died or whose
1304 // recorded title no longer matches the current process title. Every
1305 // project session carries a host PID in its key, so we iterate all of
1306 // them. Re-reading the sessions under the lock prevents enter/leave
1307 // interleaving from deleting a session that was just replaced with a
1308 // new title snapshot.
1309 //
1310 // Gated to Unix to mirror the shell-PID pruning above: on Windows,
1311 // Git Bash (MSYS2) `$$` PIDs are Cygwin-internal and invisible to
1312 // sysinfo, so the liveness check would immediately revoke every
1313 // freshly-entered session. Windows relies on explicit `project leave`
1314 // (or shell UpdateShellDir) for deregistration instead.
1315 #[cfg(unix)]
1316 {
1317 let mut state = self.state_file.lock().await;
1318 for (pid, dir, recorded_title) in liveness_sessions {
1319 let Some(session) = state.get_project_session(pid, &dir) else {
1320 continue;
1321 };
1322 let current_title = PROCS.title(pid);
1323 let is_running = PROCS.is_running(pid);
1324 debug!(
1325 "refresh liveness session pid {pid} dir {} recorded_title={recorded_title:?} current_title={current_title:?} is_running={is_running}",
1326 dir.display()
1327 );
1328 if should_remove_liveness_session(
1329 session,
1330 &recorded_title,
1331 current_title.as_deref(),
1332 is_running,
1333 ) {
1334 warn!(
1335 "removing project session pid {pid} dir {} (liveness pid title mismatch or dead)",
1336 dir.display()
1337 );
1338 if state.remove_project_session(pid, &dir).is_some() {
1339 dirs_to_leave.push(dir);
1340 }
1341 }
1342 }
1343 }
1344
1345 for dir in dirs_to_leave {
1346 self.leave_dir(&dir).await?;
1347 }
1348
1349 // Catch state-`running` daemons that lost their monitor (e.g. the
1350 // monitor died with a previous supervisor): mark dead ones errored
1351 // and re-adopt live ones. Runs before check_retry so a daemon marked
1352 // errored here is retried on this same tick.
1353 self.reconcile_unmonitored_daemons().await;
1354
1355 self.check_retry().await?;
1356 self.process_pending_autostops().await?;
1357
1358 Ok(())
1359 }
1360
1361 /// Install a SIGCHLD handler that reaps orphaned zombie child processes.
1362 ///
1363 /// When running as PID 1 inside a container, orphaned processes are
1364 /// re-parented to PID 1. Without explicit reaping, they accumulate
1365 /// as zombies in the process table indefinitely.
1366 ///
1367 /// Only reaps processes that are NOT managed by the supervisor (i.e.
1368 /// not tracked in the state file). Managed daemon processes are reaped
1369 /// by their monitoring tasks via `child.wait()`.
1370 ///
1371 /// ## Strategy
1372 ///
1373 /// **Linux**: Uses `waitid(Id::All, WNOHANG | WNOWAIT | WEXITED)` to
1374 /// *peek* at the next zombie without consuming its status. If the PID
1375 /// belongs to a managed daemon, the reaper skips it so Tokio's
1376 /// `child.wait()` can collect the status normally. Only unmanaged
1377 /// orphans are actually reaped (via `waitpid(Pid, WNOHANG)`). This
1378 /// eliminates the race entirely.
1379 ///
1380 /// **Non-Linux Unix** (e.g. macOS — mainly for local development;
1381 /// container mode targets Linux): `waitid` is unavailable, so we fall
1382 /// back to `waitpid(None, WNOHANG)`. If the reaper accidentally
1383 /// consumes a managed PID's status, it stashes the exit code in
1384 /// [`REAPED_STATUSES`] for the monitoring task to recover.
1385 #[cfg(unix)]
1386 fn reap_zombies(&self) -> Result<()> {
1387 let mut stream = signal::unix::signal(SignalKind::child())
1388 .map_err(|e| miette::miette!("Failed to register SIGCHLD handler: {e}"))?;
1389 tokio::spawn(async move {
1390 loop {
1391 stream.recv().await;
1392 // Collect PIDs of managed daemons so we don't steal their exit status
1393 let managed_pids: HashSet<u32> = SUPERVISOR
1394 .state_file
1395 .lock()
1396 .await
1397 .daemons
1398 .values()
1399 .filter_map(|d| d.pid)
1400 .collect();
1401 // Reap all available zombie children that are NOT managed
1402 Self::reap_unmanaged_zombies(&managed_pids).await;
1403 }
1404 });
1405 info!("container mode: SIGCHLD zombie reaper installed");
1406 Ok(())
1407 }
1408
1409 /// Linux implementation: peek with `waitid(WNOWAIT)` then selectively reap.
1410 ///
1411 /// `WNOWAIT` leaves the zombie in the table so we can inspect its PID
1412 /// without consuming the exit status. Only if the PID is *not* managed
1413 /// do we call `waitpid(Pid, WNOHANG)` to actually reap it.
1414 #[cfg(target_os = "linux")]
1415 async fn reap_unmanaged_zombies(managed_pids: &HashSet<u32>) {
1416 use nix::sys::wait::{Id, WaitPidFlag, WaitStatus, waitid, waitpid};
1417 use nix::unistd::Pid;
1418
1419 loop {
1420 // Peek at the next zombie without consuming it
1421 let peek_flags = WaitPidFlag::WNOHANG | WaitPidFlag::WNOWAIT | WaitPidFlag::WEXITED;
1422 match waitid(Id::All, peek_flags) {
1423 Ok(WaitStatus::StillAlive) => break,
1424 Ok(status) => {
1425 let Some(pid_raw) = status.pid().map(|p| p.as_raw() as u32) else {
1426 break;
1427 };
1428 if managed_pids.contains(&pid_raw) {
1429 // This is a managed daemon — leave it for Tokio's child.wait().
1430 // We must break out of the loop because waitid(Id::All) would
1431 // keep returning the same zombie if we don't consume it.
1432 trace!(
1433 "zombie reaper: skipping managed daemon pid {pid_raw}, \
1434 leaving for Tokio to reap"
1435 );
1436 break;
1437 }
1438 // Not managed — actually reap it
1439 match waitpid(Pid::from_raw(pid_raw as i32), Some(WaitPidFlag::WNOHANG)) {
1440 Ok(s) => trace!("reaped orphaned zombie child: {s:?}"),
1441 Err(nix::errno::Errno::ECHILD) => break,
1442 Err(e) => {
1443 trace!("waitpid error reaping pid {pid_raw}: {e}");
1444 break;
1445 }
1446 }
1447 }
1448 Err(nix::errno::Errno::ECHILD) => break, // no children at all
1449 Err(e) => {
1450 trace!("waitid error in zombie reaper: {e}");
1451 break;
1452 }
1453 }
1454 }
1455 }
1456
1457 /// Non-Linux fallback: blind `waitpid(None, WNOHANG)` with stash recovery.
1458 ///
1459 /// Since `waitid(WNOWAIT)` is not available, we cannot peek. If we
1460 /// accidentally reap a managed PID, we stash the exit code in
1461 /// [`REAPED_STATUSES`] so the monitoring task can recover it.
1462 #[cfg(all(unix, not(target_os = "linux")))]
1463 async fn reap_unmanaged_zombies(managed_pids: &HashSet<u32>) {
1464 use nix::sys::wait::{WaitPidFlag, WaitStatus, waitpid};
1465
1466 loop {
1467 match waitpid(None, Some(WaitPidFlag::WNOHANG)) {
1468 Ok(WaitStatus::StillAlive) => break,
1469 Ok(status) => {
1470 let Some(pid) = status.pid().map(|p| p.as_raw() as u32) else {
1471 continue;
1472 };
1473 if managed_pids.contains(&pid) {
1474 // Race lost — stash the exit code for lifecycle recovery
1475 let exit_code = match status {
1476 WaitStatus::Exited(_, code) => code,
1477 WaitStatus::Signaled(_, sig, _) => -(sig as i32),
1478 _ => -1,
1479 };
1480 warn!(
1481 "zombie reaper reaped managed daemon pid {pid} \
1482 (exit_code={exit_code}); stashing status for recovery"
1483 );
1484 REAPED_STATUSES.lock().await.insert(pid, exit_code);
1485 } else {
1486 trace!("reaped orphaned zombie child: {status:?}");
1487 }
1488 }
1489 Err(nix::errno::Errno::ECHILD) => break, // no more children
1490 Err(e) => {
1491 trace!("waitpid error in zombie reaper: {e}");
1492 break;
1493 }
1494 }
1495 }
1496 }
1497
1498 #[cfg(unix)]
1499 fn signals(&self) -> Result<()> {
1500 let signals = [
1501 SignalKind::terminate(),
1502 SignalKind::alarm(),
1503 SignalKind::interrupt(),
1504 SignalKind::quit(),
1505 SignalKind::hangup(),
1506 SignalKind::user_defined1(),
1507 SignalKind::user_defined2(),
1508 ];
1509 for signal in signals {
1510 let stream = match signal::unix::signal(signal) {
1511 Ok(s) => s,
1512 Err(e) => {
1513 warn!("Failed to register signal handler for {signal:?}: {e}");
1514 continue;
1515 }
1516 };
1517 tokio::spawn(async move {
1518 let mut stream = stream;
1519 loop {
1520 stream.recv().await;
1521 if SHUTDOWN_BEGUN.swap(true, atomic::Ordering::SeqCst) {
1522 SUPERVISOR.force_exit().await;
1523 } else {
1524 // Spawned, so this loop keeps receiving: a second
1525 // signal of the same kind must reach `force_exit`
1526 // rather than wait for the graceful stop to finish.
1527 tokio::spawn(SUPERVISOR.handle_signal());
1528 }
1529 }
1530 });
1531 }
1532 Ok(())
1533 }
1534
1535 #[cfg(windows)]
1536 fn signals(&self) -> Result<()> {
1537 tokio::spawn(async move {
1538 loop {
1539 if let Err(e) = signal::ctrl_c().await {
1540 error!("Failed to wait for ctrl-c: {}", e);
1541 return;
1542 }
1543 if SHUTDOWN_BEGUN.swap(true, atomic::Ordering::SeqCst) {
1544 SUPERVISOR.force_exit().await;
1545 } else {
1546 tokio::spawn(SUPERVISOR.handle_signal());
1547 }
1548 }
1549 });
1550 Ok(())
1551 }
1552
1553 async fn handle_signal(&self) {
1554 info!("received signal, stopping");
1555 self.close().await;
1556 exit_gracefully().await
1557 }
1558
1559 /// A second signal while `close()` is still stopping daemons: exit now,
1560 /// but kill the daemons not stopped yet first. They run in their own
1561 /// sessions, so exiting without this would leave them running with no
1562 /// supervisor.
1563 async fn force_exit(&self) -> ! {
1564 if EXIT_CLAIMED.swap(true, atomic::Ordering::SeqCst) {
1565 // The graceful stop has finished and is exiting already.
1566 wait_for_claimed_exit().await
1567 }
1568 // Set by `close()` too, but this may run first: from now on a start
1569 // that takes its daemon's lock does not spawn (see `run_once`).
1570 self.shutting_down.store(true, atomic::Ordering::Release);
1571 warn!("received another signal while stopping; killing the remaining daemons and exiting");
1572 let mut killed = HashSet::new();
1573 self.kill_active_daemons(&mut killed).await;
1574 // A start that passed its check before the flag holds its daemon's
1575 // stop lock until the daemon's PID is recorded. Its process is killed
1576 // above if it has already spawned (it is monitored from the moment it
1577 // spawns); wait the locks out for one still on its way, then kill
1578 // again. The stops `close()` holds locks for end quickly now that
1579 // their daemons are killed; the wait is bounded all the same, by one
1580 // deadline for all the locks so a forced exit is not held up by each.
1581 let locks: Vec<_> = self.stop_locks.lock().await.values().cloned().collect();
1582 let deadline = time::Instant::now() + Duration::from_secs(5);
1583 for lock in locks {
1584 let _ = time::timeout_at(deadline, lock.lock()).await;
1585 }
1586 self.kill_active_daemons(&mut killed).await;
1587 exit(1)
1588 }
1589
1590 /// Kill the process group of every active daemon not in `killed` at once,
1591 /// with no grace period, adding each one dealt with to `killed`.
1592 ///
1593 /// Daemons being monitored count as well: a start registers its process
1594 /// for monitoring as soon as it spawns, before its PID is recorded in
1595 /// state, and that can take a while (a cron start writes the state file
1596 /// first).
1597 ///
1598 /// The group is killed even when its leader, the PID on record, has
1599 /// already exited: the graceful stop may have ended a shell whose children
1600 /// ignore the signal. While the group has members its ID cannot be reused,
1601 /// so it is still this daemon's; a live leader is checked against its
1602 /// recorded start time, as `stop` does. A kill that fails is not counted,
1603 /// so a later pass tries again.
1604 async fn kill_active_daemons(&self, killed: &mut HashSet<(DaemonId, u32)>) {
1605 let mut kills = tokio::task::JoinSet::new();
1606 let mut targets: Vec<((DaemonId, u32), Option<u64>)> = self
1607 .active_daemons()
1608 .await
1609 .into_iter()
1610 .filter_map(|d| Some(((d.id, d.pid?), d.start_time)))
1611 .collect();
1612 let monitored: Vec<_> = self
1613 .monitored
1614 .lock()
1615 .expect("monitored lock poisoned")
1616 .iter()
1617 .map(|(id, entry)| (id.clone(), entry.pid))
1618 .collect();
1619 for key in monitored {
1620 if !targets.iter().any(|(k, _)| *k == key) {
1621 // Not recorded yet, so there is no start time to check it
1622 // against; it is a child this supervisor has just spawned.
1623 targets.push((key, None));
1624 }
1625 }
1626 for (key, start_time) in targets {
1627 let pid = key.1;
1628 if killed.contains(&key) {
1629 continue;
1630 }
1631 if PROCS.is_running(pid) {
1632 if !signalling_pid_is_authorized(start_time, PROCS.start_time(pid)) {
1633 // Recycled: not the daemon's process any more.
1634 killed.insert(key);
1635 continue;
1636 }
1637 } else if !PROCS.process_group_alive(pid) {
1638 // Leader and group both gone: nothing left to kill.
1639 killed.insert(key);
1640 continue;
1641 }
1642 kills.spawn(async move {
1643 // The stop signal is followed by SIGKILL at once.
1644 let result = PROCS
1645 .kill_process_group_async(
1646 pid,
1647 crate::config_types::StopSignal::default().into(),
1648 Some(Duration::from_millis(1)),
1649 )
1650 .await;
1651 if let Err(e) = &result {
1652 error!("failed to kill daemon {}: {e}", key.0);
1653 }
1654 (key, result.is_ok())
1655 });
1656 }
1657 for (key, ok) in kills.join_all().await {
1658 if ok {
1659 killed.insert(key);
1660 }
1661 }
1662 }
1663
1664 /// Stop new daemons from starting, and wait for the starts already under
1665 /// way to finish, so the active daemons can be listed for good.
1666 ///
1667 /// A start that took its daemon's stop lock before `shutting_down` was set
1668 /// may still be spawning; its daemon must be in the list. A start that
1669 /// takes a lock from now on sees the flag and does not spawn (see
1670 /// `run_once`).
1671 ///
1672 /// Done once: a caller that comes while the freeze is under way waits for
1673 /// it to finish, and one that comes later returns at once. By then the
1674 /// locks may be held by `close()`'s stops, which waiting for would hold a
1675 /// `Shutdown` reply until those stops end.
1676 async fn freeze_starts(&self) {
1677 self.shutting_down.store(true, atomic::Ordering::Release);
1678 self.starts_frozen
1679 .get_or_init(|| async {
1680 let locks: Vec<_> = self.stop_locks.lock().await.values().cloned().collect();
1681 for lock in locks {
1682 drop(lock.lock().await);
1683 }
1684 })
1685 .await;
1686 }
1687
1688 /// Begin a graceful shutdown for `supervisor stop` and return how long it
1689 /// may take: the client waits that long before killing the supervisor.
1690 ///
1691 /// The budget is computed here rather than by the client: only the
1692 /// supervisor knows its own settings, and only once new starts are frozen
1693 /// is the list of daemons to stop final.
1694 pub(crate) async fn begin_shutdown(&self) -> Duration {
1695 // Under way already, the freeze is waited for rather than skipped: a
1696 // daemon whose start it waits for is not listed until that start ends.
1697 // A shutdown that has frozen starts already answers at once, and the
1698 // daemons it has yet to stop are still active.
1699 self.freeze_starts().await;
1700 let base = settings().supervisor_stop_timeout();
1701 let budget = shutdown_budget(&self.active_daemons().await, base);
1702 if !SHUTDOWN_BEGUN.swap(true, atomic::Ordering::SeqCst) {
1703 tokio::spawn(async {
1704 info!("stop requested, stopping");
1705 SUPERVISOR.close().await;
1706 exit_gracefully().await
1707 });
1708 }
1709 budget
1710 }
1711
1712 pub(crate) async fn close(&self) {
1713 self.shutting_down.store(true, atomic::Ordering::Release);
1714 // Signal the proxy server to stop accepting new connections
1715 // and drain in-flight ones, *before* stopping daemons so the
1716 // proxy has time to finish forwarding active requests.
1717 if let Some(cancel) = self.proxy_cancel.lock().await.take() {
1718 cancel.cancel();
1719 }
1720
1721 // Stop the LAN IP monitor task. It watches the token that was just
1722 // cancelled, so give it a moment to come back on its own rather than
1723 // cutting it off mid-iteration the instant after asking it to stop.
1724 if let Some(mut monitor_task) = self.lan_monitor_task.lock().await.take()
1725 && tokio::time::timeout(LAN_MONITOR_STOP_WAIT, &mut monitor_task)
1726 .await
1727 .is_err()
1728 {
1729 monitor_task.abort();
1730 }
1731
1732 // Shutdown the mDNS publisher (sends goodbye packets).
1733 if let Some(publisher) = self.mdns_publisher.lock().await.take() {
1734 publisher.lock().await.shutdown();
1735 }
1736
1737 if let Some(mut dns_task) = self.dns_task.lock().await.take()
1738 && tokio::time::timeout(DNS_STOP_WAIT, &mut dns_task)
1739 .await
1740 .is_err()
1741 {
1742 // Cancelled but still running: aborted, as the LAN monitor is,
1743 // so its sockets are not left bound to the resolver port.
1744 dns_task.abort();
1745 }
1746
1747 if let Some(proxy_task) = self.proxy_task.lock().await.take() {
1748 let _ = tokio::time::timeout(PROXY_STOP_WAIT, proxy_task).await;
1749 }
1750
1751 // Clean up /etc/hosts entries managed by pitchfork
1752 let s = settings();
1753 if s.proxy.enable && s.proxy.sync_hosts {
1754 crate::proxy::hosts::clean_hosts_file();
1755 }
1756
1757 self.freeze_starts().await;
1758
1759 let pitchfork_id = DaemonId::pitchfork();
1760 let active = self.active_daemons().await;
1761 let active_ids: Vec<DaemonId> = active
1762 .iter()
1763 .filter(|d| d.id != pitchfork_id)
1764 .map(|d| d.id.clone())
1765 .collect();
1766
1767 // Stop daemons in reverse dependency order, from the dependencies
1768 // they were started with: the supervisor's own directory need not
1769 // see their projects' config.
1770 // Daemons within the same level are stopped concurrently.
1771 //
1772 // Each stop waits for the daemon's whole process group (bounded by its
1773 // stop budget) and levels are sequential, so total shutdown time is the
1774 // sum of the slowest stop per level. If an external manager (docker,
1775 // systemd) kills us before this completes, cleanup_orphaned_daemons()
1776 // recovers the leftover processes and stale state on the next start.
1777 let daemons = self.state_file.lock().await.daemons.clone();
1778 let ids = active_ids.clone();
1779 let stop_levels =
1780 match tokio::task::spawn_blocking(move || reverse_stop_order(&ids, &daemons)).await {
1781 Ok(levels) => levels,
1782 // Stopping everything at once still stops everything.
1783 Err(e) => {
1784 error!("computing the shutdown order panicked: {e}");
1785 vec![active_ids.clone()]
1786 }
1787 };
1788 for level in &stop_levels {
1789 let mut tasks = Vec::new();
1790 for id in level {
1791 let id = id.clone();
1792 tasks.push(tokio::spawn(async move {
1793 if let Err(err) = SUPERVISOR.stop(&id).await {
1794 error!("failed to stop daemon {id}: {err}");
1795 }
1796 }));
1797 }
1798 for task in tasks {
1799 let _ = task.await;
1800 }
1801 }
1802 // A forced exit kills the daemons, so the stops above can finish
1803 // before it has. Shutting the IPC server down next would let the
1804 // supervisor return and exit with success, so leave the exit to it.
1805 // (A graceful stop claims the exit only after this returns.)
1806 if EXIT_CLAIMED.load(atomic::Ordering::SeqCst) {
1807 wait_for_claimed_exit().await
1808 }
1809 let _ = self.remove_daemon(&pitchfork_id).await;
1810
1811 // Signal the background state flush task to exit so it doesn't
1812 // keep waking up and acquiring the state mutex after shutdown.
1813 if let Some(cancel) = self.flush_cancel.lock().unwrap().take() {
1814 cancel.cancel();
1815 }
1816
1817 // Force-flush state to disk before shutting down IPC so no
1818 // in-memory-only changes are lost.
1819 {
1820 let state = self.state_file.lock().await;
1821 if state.is_dirty()
1822 && let Err(e) = state.write()
1823 {
1824 warn!("failed to flush state file during shutdown: {e}");
1825 }
1826 }
1827
1828 // Signal IPC server to shut down gracefully
1829 if let Some(mut handle) = self.ipc_shutdown.lock().await.take() {
1830 handle.shutdown().await;
1831 }
1832
1833 // Wait for all in-flight monitoring tasks to finish registering their
1834 // hook handles. Each monitoring task increments `active_monitors` when
1835 // its process exits, and decrements it (+ notifies `monitor_done`)
1836 // after all fire_hook() calls complete. This replaces the old
1837 // yield_now() approach which had a race window.
1838 let drain_timeout = time::sleep(MONITOR_DRAIN_WAIT);
1839 tokio::pin!(drain_timeout);
1840 loop {
1841 if self.active_monitors.load(atomic::Ordering::Acquire) == 0 {
1842 break;
1843 }
1844 tokio::select! {
1845 _ = self.monitor_done.notified() => {}
1846 _ = &mut drain_timeout => {
1847 warn!("timed out waiting for monitoring tasks to register hooks, proceeding with shutdown");
1848 break;
1849 }
1850 }
1851 }
1852 // The hooks run at the same time, so they are given one deadline
1853 // together: `supervisor stop` allows for this wait, and must not be
1854 // outlasted by it.
1855 let handles: Vec<JoinHandle<()>> = std::mem::take(&mut *self.hook_tasks.lock().await);
1856 let hook_deadline = time::Instant::now() + HOOK_DRAIN_WAIT;
1857 for handle in handles {
1858 match time::timeout_at(hook_deadline, handle).await {
1859 Ok(_) => {} // Hook completed (success or error, doesn't matter)
1860 Err(_) => {
1861 warn!(
1862 "hook task did not complete within {HOOK_DRAIN_WAIT:?} during shutdown, skipping"
1863 );
1864 }
1865 }
1866 }
1867
1868 // Unix: remove the socket directory if it is empty. The IPC server
1869 // already removed our socket; anything left belongs to a supervisor
1870 // that replaced this one (e.g. `supervisor run --force`) while we
1871 // were stopping daemons, and must not be deleted.
1872 // Windows: named pipes have no filesystem component.
1873 #[cfg(unix)]
1874 let _ = fs::remove_dir(&*env::IPC_SOCK_DIR);
1875 }
1876
1877 pub(crate) async fn add_notification(&self, level: log::LevelFilter, message: String) {
1878 self.pending_notifications
1879 .lock()
1880 .await
1881 .push((level, message));
1882 }
1883}
1884
1885/// Fix ownership on the state directory so non-root users can access files
1886/// created by a `sudo`-started supervisor.
1887///
1888/// When `[settings.supervisor] user`, a recorded invoking user (see
1889/// [`env::InvokingUser`]), or `SUDO_UID`/`SUDO_GID` are set, we
1890/// `chown` the state directory and safe subdirectories back to that non-root
1891/// runtime user. This is strictly better than `chmod 0o666` because it does not
1892/// widen the permission bits — the files stay owner-only (0o600/0o700) but the
1893/// *owner* is the user that daemon processes and CLI clients need to share.
1894///
1895/// **Security**: The `proxy/` subtree is intentionally skipped. It contains
1896/// `ca-key.pem` which must remain `0o600` and owned by the process that
1897/// generated it. Changing its ownership or permissions would expose the CA
1898/// private key to other local users.
1899///
1900/// If none of these are available (e.g. a direct root login, or a boot service
1901/// installed from a root shell), we fall back to relaxing permissions on only
1902/// the `sock/` and `logs/` subdirectories (plus `state.toml`) so CLI clients
1903/// can still function.
1904#[cfg(unix)]
1905fn fix_state_dir_permissions() {
1906 let state_dir = &*env::PITCHFORK_STATE_DIR;
1907 if let Some((uid, gid)) = state_owner_ids() {
1908 if !state_dir.exists()
1909 && let Err(err) = fs::create_dir_all(state_dir)
1910 {
1911 warn!(
1912 "failed to create state directory for ownership fix at {}: {err}",
1913 state_dir.display()
1914 );
1915 return;
1916 }
1917
1918 // Best path: chown back to the runtime user. Permissions stay tight.
1919 chown_recursive(state_dir, uid, gid, true);
1920 debug!(
1921 "chowned state directory to uid={uid} gid={gid} at {}",
1922 state_dir.display()
1923 );
1924 } else {
1925 if !state_dir.exists() {
1926 return;
1927 }
1928
1929 // Fallback: relax permissions on safe subdirectories only.
1930 // proxy/ is never touched.
1931 chmod_safe_subtrees(state_dir);
1932 debug!(
1933 "relaxed permissions on safe subtrees at {}",
1934 state_dir.display()
1935 );
1936 }
1937}
1938
1939#[cfg(unix)]
1940pub(crate) fn state_owner_ids() -> Option<(u32, u32)> {
1941 if !nix::unistd::Uid::effective().is_root() {
1942 return None;
1943 }
1944
1945 let s = settings();
1946 let user = s.supervisor.user.trim();
1947 if !user.is_empty() {
1948 return resolve_supervisor_user_ids(user).or_else(|| {
1949 warn!(
1950 "failed to resolve supervisor.user '{user}' for state ownership; falling back to the invoking user"
1951 );
1952 env::invoking_user_ids()
1953 });
1954 }
1955
1956 env::invoking_user_ids()
1957}
1958
1959#[cfg(unix)]
1960fn resolve_supervisor_user_ids(user: &str) -> Option<(u32, u32)> {
1961 let user_record = if user.chars().all(|c| c.is_ascii_digit()) {
1962 let uid = user.parse::<u32>().ok()?;
1963 nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
1964 .ok()
1965 .flatten()
1966 } else {
1967 nix::unistd::User::from_name(user).ok().flatten()
1968 }?;
1969
1970 Some((user_record.uid.as_raw(), user_record.gid.as_raw()))
1971}
1972
1973/// Recursively `chown` a directory tree. If `skip_proxy` is true, the `proxy/`
1974/// subdirectory is skipped entirely to protect the CA private key.
1975#[cfg(unix)]
1976fn chown_recursive(dir: &std::path::Path, uid: u32, gid: u32, skip_proxy: bool) {
1977 // chown the directory itself
1978 let _ = chown_path(dir, uid, gid);
1979
1980 let entries = match std::fs::read_dir(dir) {
1981 Ok(e) => e,
1982 Err(_) => return,
1983 };
1984 for entry in entries.flatten() {
1985 let path = entry.path();
1986 if path.is_dir() {
1987 // Skip proxy/ at the top level of the state directory
1988 if skip_proxy
1989 && let Some(name) = path.file_name().and_then(|n| n.to_str())
1990 && name == "proxy"
1991 {
1992 continue;
1993 }
1994 chown_recursive(&path, uid, gid, false);
1995 } else {
1996 let _ = chown_path(&path, uid, gid);
1997 }
1998 }
1999}
2000
2001/// `chown` a single path using libc. Returns Ok(()) on success.
2002#[cfg(unix)]
2003fn chown_path(path: &std::path::Path, uid: u32, gid: u32) -> std::io::Result<()> {
2004 use std::ffi::CString;
2005 use std::os::unix::ffi::OsStrExt;
2006 let c_path = CString::new(path.as_os_str().as_bytes())
2007 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
2008 let ret = unsafe { libc::chown(c_path.as_ptr(), uid, gid) };
2009 if ret == 0 {
2010 Ok(())
2011 } else {
2012 Err(std::io::Error::last_os_error())
2013 }
2014}
2015
2016/// Fallback: relax permissions on safe subdirectories only (sock/, logs/, and
2017/// state.toml). The proxy/ subtree is never touched.
2018#[cfg(unix)]
2019fn chmod_safe_subtrees(state_dir: &std::path::Path) {
2020 // The state directory itself needs to be traversable
2021 let _ = fs::set_permissions(state_dir, fs::Permissions::from_mode(0o755));
2022
2023 // state.toml — needs to be readable by CLI clients
2024 let state_file = state_dir.join("state.toml");
2025 if state_file.exists() {
2026 let _ = fs::set_permissions(&state_file, fs::Permissions::from_mode(0o644));
2027 }
2028
2029 // Safe subdirectories: sock/ and logs/
2030 for subdir_name in &["sock", "logs"] {
2031 let subdir = state_dir.join(subdir_name);
2032 if subdir.is_dir() {
2033 chmod_recursive(&subdir);
2034 }
2035 }
2036}
2037
2038/// On startup, reconcile daemon processes left behind by a previous supervisor
2039/// that was terminated unexpectedly (e.g. `kill -9`).
2040///
2041/// This iterates the state file for daemon entries with a recorded PID. If the
2042/// PID is still alive and its current identity matches the recorded start time
2043/// (or the recorded title for older state files), it is assumed to be an orphan
2044/// from the previous supervisor session and `supervisor.orphan_policy` decides
2045/// its fate: `adopt` (default) resumes supervision via a poll monitor and keeps
2046/// the daemon's state intact; `kill` terminates it and resets its state to
2047/// `Stopped` with no PID. If a matching live process cannot be terminated
2048/// securely, its running state is retained to prevent a duplicate instance
2049/// from being started.
2050///
2051/// Missing or mismatched identity data fails closed so a PID recycled by an
2052/// unrelated process is never adopted or killed. On Unix platforms without
2053/// durable process handles, orphan termination also fails closed because the
2054/// PID/PGID cannot be pinned between identity validation and signaling.
2055///
2056/// This is gated by the `supervisor.cleanup_orphans` setting (default: true).
2057///
2058/// `unclean` is whether the previous supervisor exited uncleanly (see
2059/// [`supervisor_exited_uncleanly`]). It is read in `start()` before the
2060/// starting supervisor records itself in the state file — this function runs
2061/// in the background after that record exists, so reading it here would
2062/// always report unclean.
2063async fn cleanup_orphaned_daemons(supervisor: &Supervisor, unclean: bool) {
2064 if !settings().supervisor.cleanup_orphans {
2065 return;
2066 }
2067
2068 let candidates: Vec<_> = {
2069 let state = supervisor.state_file.lock().await;
2070 state
2071 .daemons
2072 .values()
2073 .filter(|d| d.id != DaemonId::pitchfork() && d.pid.is_some())
2074 .cloned()
2075 .collect()
2076 };
2077
2078 if candidates.is_empty() {
2079 return;
2080 }
2081
2082 info!(
2083 "checking {} daemon(s) for orphaned processes",
2084 candidates.len()
2085 );
2086
2087 let policy = orphan_policy();
2088 let boot_time = PROCS.boot_time();
2089
2090 // Reconcile orphans in parallel — a kill waits for the daemon's whole
2091 // process group to exit, bounded by that daemon's stop budget, so
2092 // sequential processing would make total cleanup time the sum of the
2093 // budgets.
2094 let tasks: Vec<_> = candidates
2095 .into_iter()
2096 .map(|daemon| {
2097 let policy = policy.clone();
2098 tokio::spawn(cleanup_orphaned_daemon(daemon, policy, boot_time, unclean))
2099 })
2100 .collect();
2101 for task in tasks {
2102 let _ = task.await;
2103 }
2104}
2105
2106/// Reconcile a single orphan candidate: adopt it, kill it, or reset its state,
2107/// per the policy and identity checks described on [`cleanup_orphaned_daemons`].
2108///
2109/// Holds the daemon's stop lock so a concurrent Run/Stop request for the same
2110/// daemon (cleanup runs in the background) serializes with the orphan kill,
2111/// and re-checks the recorded PID under the lock: if it changed, another path
2112/// already replaced or cleaned up this record and the snapshot is stale.
2113async fn cleanup_orphaned_daemon(
2114 daemon: crate::daemon::Daemon,
2115 policy: String,
2116 boot_time: u64,
2117 unclean: bool,
2118) {
2119 let supervisor: &Supervisor = &SUPERVISOR;
2120 let Some(pid) = daemon.pid else { return };
2121
2122 let lock = supervisor.stop_lock(&daemon.id).await;
2123 let _guard = lock.lock().await;
2124 let current_pid = {
2125 let state = supervisor.state_file.lock().await;
2126 state.daemons.get(&daemon.id).and_then(|d| d.pid)
2127 };
2128 if current_pid != Some(pid) {
2129 debug!(
2130 "orphan cleanup: daemon {} pid changed (recorded {pid}, now {current_pid:?}), skipping",
2131 daemon.id
2132 );
2133 return;
2134 }
2135
2136 // Refresh the candidate immediately before checking it: waiting for the
2137 // stop lock can await another path's stop timeout, during which this PID
2138 // may exit and be recycled.
2139 PROCS.refresh_pids(&[pid]);
2140
2141 if !PROCS.is_running(pid) {
2142 // PID already dead — the daemon exited while unsupervised, so
2143 // record a terminal status that reflects whether it died under a
2144 // crashed supervisor (retryable) or with the machine.
2145 let status = unobserved_exit_status(
2146 &daemon.status,
2147 daemon.boot_time,
2148 boot_time,
2149 unclean,
2150 daemon.oneshot,
2151 );
2152 reset_daemon_state(supervisor, &daemon.id, status, ExitObservation::Unobserved).await;
2153 return;
2154 }
2155
2156 // Safety check: verify the live process really is the daemon we
2157 // recorded, not an unrelated process that received a recycled PID.
2158 // The kernel start time is a stable identity for the lifetime of a
2159 // process, and is the only thing accepted as one.
2160 let current_start_time = PROCS.start_time(pid);
2161 let matches = process_identity_matches(daemon.start_time, current_start_time);
2162
2163 if !matches {
2164 // Either side missing means the identity cannot be checked at all,
2165 // which is different from checking it and finding a stranger: retain
2166 // the running state rather than resetting a record whose process may
2167 // well still be the daemon.
2168 if daemon.start_time.is_none() || current_start_time.is_none() {
2169 warn!(
2170 "could not verify the identity of live pid {pid} recorded for daemon {}; retaining running state",
2171 daemon.id,
2172 );
2173 return;
2174 }
2175 warn!(
2176 "pid {pid} recorded for daemon {} belongs to a different process now (PID recycled); resetting state without killing",
2177 daemon.id,
2178 );
2179 // The daemon died at some unknown point and the OS handed its PID
2180 // to something else — same unobserved exit as a dead PID.
2181 let status = unobserved_exit_status(
2182 &daemon.status,
2183 daemon.boot_time,
2184 boot_time,
2185 unclean,
2186 daemon.oneshot,
2187 );
2188 reset_daemon_state(supervisor, &daemon.id, status, ExitObservation::Unobserved).await;
2189 return;
2190 }
2191
2192 // Both policies need a verified start time: killing revalidates it
2193 // while pinned to the process, and adoption anchors its poll monitor
2194 // to it so a later PID recycle is never mistaken for the daemon.
2195 let Some(expected_start_time) = current_start_time else {
2196 warn!(
2197 "could not read start time for live pid {pid} recorded for daemon {}; retaining running state",
2198 daemon.id,
2199 );
2200 return;
2201 };
2202
2203 // Identity verified — the process really is our orphaned daemon.
2204 // The policy decides whether supervision resumes or the slate is
2205 // wiped clean.
2206 if policy == "adopt" {
2207 supervisor
2208 .adopt_daemon(&daemon, pid, expected_start_time)
2209 .await;
2210 return;
2211 }
2212
2213 info!("terminating orphaned daemon {} (pid {pid})", daemon.id);
2214
2215 let stop_cfg = daemon.stop_signal.unwrap_or_default();
2216 let termination_result = PROCS
2217 .kill_process_group_if_start_time_matches_async(
2218 pid,
2219 Some(expected_start_time),
2220 stop_cfg.signal.into(),
2221 stop_cfg.timeout,
2222 )
2223 .await;
2224
2225 match termination_result {
2226 Ok(true) => {}
2227 Ok(false) => {
2228 warn!(
2229 "could not securely terminate orphaned daemon {} (pid {pid}); retaining running state",
2230 daemon.id
2231 );
2232 return;
2233 }
2234 Err(err) => {
2235 warn!(
2236 "failed to terminate orphaned daemon {} (pid {pid}): {err}; retaining running state",
2237 daemon.id
2238 );
2239 return;
2240 }
2241 }
2242
2243 // We terminated the orphan ourselves, so this is an observed,
2244 // intentional stop rather than an unobserved exit.
2245 reset_daemon_state(
2246 supervisor,
2247 &daemon.id,
2248 DaemonStatus::Stopped,
2249 ExitObservation::Terminated,
2250 )
2251 .await;
2252}
2253
2254/// Effective `supervisor.orphan_policy`, warning on an unrecognized value
2255/// (which falls back to the default of adopting).
2256pub(crate) fn orphan_policy() -> String {
2257 let policy = settings().supervisor.orphan_policy.clone();
2258 match policy.as_str() {
2259 "adopt" | "kill" => policy,
2260 other => {
2261 warn!("unknown supervisor.orphan_policy '{other}', defaulting to 'adopt'");
2262 "adopt".to_string()
2263 }
2264 }
2265}
2266
2267/// Verify that live process identity matches the persisted daemon identity.
2268///
2269/// Both start times are required. A process name was once accepted in place of
2270/// a recorded start time, for state written before start times existed, but a
2271/// name is not an identity: a recycled PID belonging to another copy of the same
2272/// program matches it, and adopting or killing on that basis acts on the wrong
2273/// process. Missing identity, on either side, means unverifiable — and
2274/// unverifiable must never authorize acting on a process.
2275fn process_identity_matches(
2276 recorded_start_time: Option<u64>,
2277 current_start_time: Option<u64>,
2278) -> bool {
2279 match (recorded_start_time, current_start_time) {
2280 (Some(recorded), Some(current)) => recorded == current,
2281 _ => false,
2282 }
2283}
2284
2285/// Whether a PID read from persisted state may be signalled.
2286///
2287/// Stopping a daemon signals its whole process *group*, so acting on a PID that
2288/// has been recycled since it was recorded takes down an unrelated process tree.
2289/// Records are refused only when their identity is positively contradicted: if
2290/// either start time is unknown the PID stays as signallable as it was before
2291/// identities were recorded, so a daemon whose record predates the field can
2292/// still be stopped rather than becoming permanently unstoppable.
2293///
2294/// This is deliberately weaker than [`process_identity_matches`], which decides
2295/// whether to adopt or kill a process nobody asked about. Here the user has
2296/// named the daemon and asked for it to stop; the check exists to catch the
2297/// case where the answer is provably the wrong process.
2298pub(crate) fn signalling_pid_is_authorized(
2299 recorded_start_time: Option<u64>,
2300 current_start_time: Option<u64>,
2301) -> bool {
2302 !matches!(
2303 (recorded_start_time, current_start_time),
2304 (Some(recorded), Some(current)) if recorded != current
2305 )
2306}
2307
2308/// How a daemon's run ended, which decides what happens to the recorded
2309/// `last_exit_success` that cron `retrigger = "success" | "fail"` reads.
2310#[derive(Clone, Copy, PartialEq, Eq)]
2311pub(crate) enum ExitObservation {
2312 /// Nobody saw how the run ended, because the monitor that would have
2313 /// observed it died with a previous supervisor. The recorded outcome is
2314 /// cleared to `None`.
2315 ///
2316 /// Every option here is imperfect, so this picks the one that asserts
2317 /// nothing false. `Some(false)` would fabricate a failure, silently
2318 /// breaking a `retrigger = "success"` chain whose run may well have
2319 /// succeeded; `Some(true)` fabricates the opposite; keeping the previous
2320 /// value attributes an earlier run's outcome to this one. `None` says
2321 /// "unknown", reusing the reading the cron watcher already applies to a
2322 /// daemon that has never run.
2323 ///
2324 /// The tradeoff is that `None` satisfies both `retrigger = "success"`
2325 /// (`unwrap_or(true)`) and `retrigger = "fail"` (`!unwrap_or(false)`), so
2326 /// such a daemon fires once at its next scheduled time regardless of which
2327 /// it configured. That is schedule-gated rather than a loop, and it biases
2328 /// toward running the daemon over leaving it permanently untriggered.
2329 /// Distinguishing "unknown" from "never ran" would require a third cron
2330 /// state and is deliberately left out of scope here.
2331 Unobserved,
2332 /// We terminated the process ourselves, so the outcome is not a mystery:
2333 /// it stopped because we asked it to. Recorded as a success, matching the
2334 /// convention `Supervisor::stop` already uses for a deliberate stop.
2335 Terminated,
2336}
2337
2338impl ExitObservation {
2339 /// The `last_exit_success` value this observation implies.
2340 pub(crate) fn last_exit_success(self) -> Option<bool> {
2341 match self {
2342 ExitObservation::Unobserved => None,
2343 ExitObservation::Terminated => Some(true),
2344 }
2345 }
2346}
2347
2348/// Clear a daemon's runtime state (pid, process identity, active port) after
2349/// its process is gone or is no longer ours to manage.
2350///
2351/// Config fields are preserved by cloning the existing record, so a reset can
2352/// never drop a daemon's command, retry policy, or schedule.
2353async fn reset_daemon_state(
2354 supervisor: &Supervisor,
2355 id: &DaemonId,
2356 status: DaemonStatus,
2357 observation: ExitObservation,
2358) {
2359 let mut state_file = supervisor.state_file.lock().await;
2360 let Some(existing) = state_file.daemons.get(id) else {
2361 return;
2362 };
2363 let mut daemon = existing.clone();
2364 daemon.pid = None;
2365 daemon.title = None;
2366 daemon.start_time = None;
2367 daemon.boot_time = None;
2368 daemon.status = status;
2369 daemon.last_exit_success = observation.last_exit_success();
2370 daemon.active_port = None;
2371 state_file.clear_active_port(id);
2372 state_file.insert_daemon(id, daemon);
2373}
2374
2375/// Boot times this far apart are treated as different boots.
2376///
2377/// Sized to the only platform that reports a jittery value: Windows derives
2378/// boot time as `now - GetTickCount64()`, sampling two clocks independently,
2379/// so consecutive calls within one boot can differ by about a second. Linux
2380/// (`/proc/stat` btime) and macOS (`kern.boottime`) report stable values.
2381///
2382/// Deliberately kept this tight so a genuine reboot can never fall inside it:
2383/// a prior session would have to boot, start the supervisor, spawn a daemon,
2384/// have that daemon die, and complete a reboot inside two seconds, which no
2385/// real boot cycle reaches. A larger window would misread a short-lived
2386/// previous boot (e.g. a device in a reboot loop) as the current one and
2387/// resurrect daemons a reboot should have left stopped.
2388pub(crate) const BOOT_TIME_TOLERANCE_SECS: u64 = 2;
2389
2390/// Terminal status for a daemon whose process is gone and whose exit was
2391/// never observed, because the monitor that would have seen it died with a
2392/// previous supervisor.
2393///
2394/// A daemon recorded `Running` was expected to still be alive, so it died
2395/// under the crashed supervisor: `Errored(-1)` ("unknown exit code") makes it
2396/// eligible for its configured retries. Two cases stay `Stopped` instead:
2397///
2398/// - records from an earlier boot, whose processes died with the machine —
2399/// auto-restarting those is what `boot_start` is for, and reviving every
2400/// retry-configured daemon after a reboot would be a surprise
2401/// - any other status (in practice `Stopping`), i.e. an intentional stop that
2402/// completed while the supervisor was gone
2403pub(crate) fn unobserved_exit_status(
2404 status: &DaemonStatus,
2405 recorded_boot_time: Option<u64>,
2406 current_boot_time: u64,
2407 supervisor_exited_uncleanly: bool,
2408 oneshot: bool,
2409) -> DaemonStatus {
2410 let same_boot = recorded_boot_time
2411 .is_some_and(|recorded| recorded.abs_diff(current_boot_time) <= BOOT_TIME_TOLERANCE_SECS);
2412 // A task gets `stopped` rather than `errored` for the same reason the
2413 // adopted path does: `errored` is what `check_retry` looks for, and
2414 // nobody saw how this run ended, so retrying it would re-run a migration
2415 // or a seed that may well have succeeded. Leave re-running to an explicit
2416 // start.
2417 if status.is_running() && same_boot && supervisor_exited_uncleanly && !oneshot {
2418 DaemonStatus::Errored(-1)
2419 } else {
2420 DaemonStatus::Stopped
2421 }
2422}
2423
2424/// Whether the supervisor that owned this state file failed to shut down
2425/// cleanly, meaning any daemon it left behind stopped for reasons nobody
2426/// recorded.
2427///
2428/// A clean shutdown removes the supervisor's own entry: `close()` does it on
2429/// Unix, where the stop signal is delivered and handled, and the
2430/// `supervisor stop` command does it on Windows, which has no POSIX signals
2431/// and force-terminates the process instead. A crash, an external `kill -9`,
2432/// or a `--force` replacement all leave the entry behind.
2433///
2434/// This must be read before the starting supervisor records itself, which is
2435/// why `cleanup_orphaned_daemons` runs first in `start()`.
2436async fn supervisor_exited_uncleanly(supervisor: &Supervisor) -> bool {
2437 supervisor
2438 .state_file
2439 .lock()
2440 .await
2441 .daemons
2442 .contains_key(&DaemonId::pitchfork())
2443}
2444
2445/// Recursively chmod: directories → 0o755, files → 0o644.
2446#[cfg(unix)]
2447fn chmod_recursive(dir: &std::path::Path) {
2448 let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o755));
2449 let entries = match fs::read_dir(dir) {
2450 Ok(e) => e,
2451 Err(_) => return,
2452 };
2453 for entry in entries.flatten() {
2454 let path = entry.path();
2455 if path.is_dir() {
2456 chmod_recursive(&path);
2457 } else {
2458 let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o644));
2459 }
2460 }
2461}
2462
2463#[cfg(test)]
2464mod tests {
2465 use super::{
2466 BOOT_TIME_TOLERANCE_SECS, legacy_supervisor_title_matches, process_identity_matches,
2467 should_remove_liveness_session, signalling_pid_is_authorized, supervisor_identity_matches,
2468 unobserved_exit_status,
2469 };
2470 use crate::daemon_status::DaemonStatus;
2471 use crate::state_file::ProjectSession;
2472
2473 const BOOT: u64 = 1_700_000_000;
2474
2475 #[test]
2476 fn unobserved_running_death_in_current_boot_is_retryable() {
2477 // Died under a crashed supervisor during this boot: Errored(-1) makes
2478 // the daemon eligible for its configured retries.
2479 assert!(matches!(
2480 unobserved_exit_status(&DaemonStatus::Running, Some(BOOT), BOOT, true, false),
2481 DaemonStatus::Errored(-1)
2482 ));
2483 }
2484
2485 #[test]
2486 fn unobserved_task_death_is_stopped_not_retried() {
2487 // Nobody saw how the run ended, so `errored` would hand a migration or
2488 // a seed to check_retry on a guess. Matches what the adopted path
2489 // records, and what the guide promises.
2490 assert!(matches!(
2491 unobserved_exit_status(&DaemonStatus::Running, Some(BOOT), BOOT, true, true),
2492 DaemonStatus::Stopped
2493 ));
2494 }
2495
2496 #[test]
2497 fn unobserved_running_death_from_previous_boot_is_stopped() {
2498 // The process died with the machine; reviving every retry-configured
2499 // daemon after a reboot is what boot_start is for.
2500 assert!(matches!(
2501 unobserved_exit_status(
2502 &DaemonStatus::Running,
2503 Some(BOOT - 86_400),
2504 BOOT,
2505 true,
2506 false
2507 ),
2508 DaemonStatus::Stopped
2509 ));
2510 }
2511
2512 #[test]
2513 fn unobserved_exit_tolerates_boot_time_jitter() {
2514 // Windows recomputes boot time as now - GetTickCount64(), which can
2515 // drift about a second between samples within one boot.
2516 let within = BOOT + BOOT_TIME_TOLERANCE_SECS;
2517 assert!(matches!(
2518 unobserved_exit_status(&DaemonStatus::Running, Some(within), BOOT, true, false),
2519 DaemonStatus::Errored(-1)
2520 ));
2521 let beyond = BOOT + BOOT_TIME_TOLERANCE_SECS + 1;
2522 assert!(matches!(
2523 unobserved_exit_status(&DaemonStatus::Running, Some(beyond), BOOT, true, false),
2524 DaemonStatus::Stopped
2525 ));
2526 }
2527
2528 #[test]
2529 fn unobserved_exit_after_clean_shutdown_is_stopped() {
2530 // A deliberate `supervisor stop` can leave running records behind on
2531 // platforms where the supervisor cannot handle the stop signal. Those
2532 // daemons were stopped on purpose, so they must not be reported as
2533 // failures or resurrected by the retry checker.
2534 assert!(matches!(
2535 unobserved_exit_status(&DaemonStatus::Running, Some(BOOT), BOOT, false, false),
2536 DaemonStatus::Stopped
2537 ));
2538 }
2539
2540 #[test]
2541 fn unobserved_exit_treats_short_previous_boot_as_previous() {
2542 // A device in a reboot loop can produce consecutive boots seconds
2543 // apart. The jitter window must stay far below that so those records
2544 // are still recognised as belonging to an earlier boot.
2545 for gap in [5, 30, 59, 60] {
2546 assert!(
2547 matches!(
2548 unobserved_exit_status(
2549 &DaemonStatus::Running,
2550 Some(BOOT - gap),
2551 BOOT,
2552 true,
2553 false
2554 ),
2555 DaemonStatus::Stopped
2556 ),
2557 "boot {gap}s earlier should be treated as a previous boot"
2558 );
2559 }
2560 }
2561
2562 #[test]
2563 fn unobserved_exit_without_recorded_boot_time_is_stopped() {
2564 // Legacy state files predating the field fail closed to today's
2565 // behavior rather than triggering surprise retries.
2566 assert!(matches!(
2567 unobserved_exit_status(&DaemonStatus::Running, None, BOOT, true, false),
2568 DaemonStatus::Stopped
2569 ));
2570 }
2571
2572 #[test]
2573 fn supervisor_identity_matches_same_generation() {
2574 assert!(supervisor_identity_matches(
2575 Some(100),
2576 Some(100),
2577 Some(BOOT),
2578 BOOT
2579 ));
2580 }
2581
2582 #[test]
2583 fn supervisor_identity_survives_clock_steps_when_tokens_match() {
2584 // An NTP step or sleep/resume moves the realtime-derived boot time by
2585 // far more than the tolerance while the supervisor keeps running.
2586 // Matching start tokens prove it is the same process; declaring it
2587 // stale here would start a second supervisor.
2588 assert!(supervisor_identity_matches(
2589 Some(100),
2590 Some(100),
2591 Some(BOOT),
2592 BOOT + 3600
2593 ));
2594 assert!(supervisor_identity_matches(
2595 Some(100),
2596 Some(100),
2597 Some(BOOT + 3600),
2598 BOOT
2599 ));
2600 }
2601
2602 #[test]
2603 fn supervisor_identity_rejects_recycled_pid() {
2604 // The supervisor died and something else got its PID, within this
2605 // boot or across a reboot: the token differs either way.
2606 assert!(!supervisor_identity_matches(
2607 Some(100),
2608 Some(200),
2609 Some(BOOT),
2610 BOOT
2611 ));
2612 assert!(!supervisor_identity_matches(
2613 Some(100),
2614 Some(200),
2615 Some(BOOT),
2616 BOOT + 3600
2617 ));
2618 }
2619
2620 #[test]
2621 fn supervisor_identity_uses_boot_time_when_a_token_is_missing() {
2622 // Discussion #877: the record survived a reboot and an early system
2623 // daemon now owns the PID. With no live token to compare, the boot
2624 // time is what proves the record stale.
2625 assert!(!supervisor_identity_matches(
2626 Some(100),
2627 None,
2628 Some(BOOT),
2629 BOOT + 3600
2630 ));
2631 // Same boot (within Windows boot-time jitter) and no contradiction.
2632 assert!(supervisor_identity_matches(
2633 Some(100),
2634 None,
2635 Some(BOOT),
2636 BOOT + BOOT_TIME_TOLERANCE_SECS
2637 ));
2638 }
2639
2640 #[test]
2641 fn supervisor_identity_tolerates_legacy_records() {
2642 // A record written before either field existed is not contradicted by
2643 // anything here; `supervisor_record_is_live` applies the process-name
2644 // check to those instead.
2645 assert!(supervisor_identity_matches(None, Some(100), None, BOOT));
2646 // A record with only a boot time is still rejected across a reboot.
2647 assert!(!supervisor_identity_matches(
2648 None,
2649 Some(100),
2650 Some(BOOT),
2651 BOOT + 3600
2652 ));
2653 assert!(supervisor_identity_matches(
2654 None,
2655 Some(100),
2656 Some(BOOT),
2657 BOOT
2658 ));
2659 }
2660
2661 #[test]
2662 fn legacy_supervisor_title_requires_a_pitchfork_process() {
2663 assert!(legacy_supervisor_title_matches(Some("pitchfork")));
2664 assert!(legacy_supervisor_title_matches(Some("pitchfork.exe")));
2665 assert!(legacy_supervisor_title_matches(Some("Pitchfork")));
2666 // Discussion #877: an Apple LaunchAgent inherited the PID after a reboot.
2667 assert!(!legacy_supervisor_title_matches(Some(
2668 "AMPDeviceDiscoveryAgent"
2669 )));
2670 assert!(!legacy_supervisor_title_matches(Some("sleep")));
2671 assert!(!legacy_supervisor_title_matches(None));
2672 }
2673
2674 #[test]
2675 fn unobserved_exit_of_stopping_daemon_is_stopped() {
2676 // An intentional stop that completed while the supervisor was gone is
2677 // not a failure, even within the same boot.
2678 assert!(matches!(
2679 unobserved_exit_status(&DaemonStatus::Stopping, Some(BOOT), BOOT, true, false),
2680 DaemonStatus::Stopped
2681 ));
2682 }
2683
2684 #[test]
2685 fn orphan_identity_requires_both_start_times() {
2686 assert!(process_identity_matches(Some(123), Some(123)));
2687 assert!(!process_identity_matches(Some(123), Some(456)));
2688 // Unreadable current identity: unverifiable, so not a match.
2689 assert!(!process_identity_matches(Some(123), None));
2690 }
2691
2692 #[test]
2693 fn signalling_is_refused_only_for_a_contradicted_identity() {
2694 // Provably someone else's process group: refuse.
2695 assert!(!signalling_pid_is_authorized(Some(123), Some(456)));
2696 // Verified as the daemon's own.
2697 assert!(signalling_pid_is_authorized(Some(123), Some(123)));
2698 // Unknown on either side. Stopping stays possible, because the user has
2699 // named this daemon and a record that cannot be verified must not become
2700 // one that can never be stopped.
2701 assert!(signalling_pid_is_authorized(None, Some(123)));
2702 assert!(signalling_pid_is_authorized(Some(123), None));
2703 assert!(signalling_pid_is_authorized(None, None));
2704 }
2705
2706 #[test]
2707 fn orphan_identity_rejects_records_without_a_start_time() {
2708 // State written before start times were recorded. A process name used
2709 // to stand in here, but another copy of the same program on a recycled
2710 // PID matches a name, so such records are no longer verifiable and must
2711 // not authorize adopting or killing anything.
2712 assert!(!process_identity_matches(None, Some(123)));
2713 assert!(!process_identity_matches(None, None));
2714 }
2715
2716 #[test]
2717 fn should_not_remove_when_state_title_differs_from_snapshot() {
2718 // The session was re-entered after the snapshot was taken, producing a
2719 // new title in state. The snapshot title is stale; skip removal.
2720 let session = ProjectSession {
2721 liveness_title: Some("new_title".to_string()),
2722 };
2723 let recorded_title = Some("old_title".to_string());
2724
2725 assert!(!should_remove_liveness_session(
2726 &session,
2727 &recorded_title,
2728 Some("new_title"),
2729 true,
2730 ));
2731 }
2732
2733 #[test]
2734 fn should_remove_when_running_title_mismatches() {
2735 let session = ProjectSession {
2736 liveness_title: Some("recorded_title".to_string()),
2737 };
2738 let recorded_title = Some("recorded_title".to_string());
2739
2740 assert!(should_remove_liveness_session(
2741 &session,
2742 &recorded_title,
2743 Some("different_title"),
2744 true,
2745 ));
2746 }
2747
2748 #[test]
2749 fn should_remove_when_dead() {
2750 let session = ProjectSession {
2751 liveness_title: Some("recorded_title".to_string()),
2752 };
2753 let recorded_title = Some("recorded_title".to_string());
2754
2755 assert!(should_remove_liveness_session(
2756 &session,
2757 &recorded_title,
2758 Some("recorded_title"),
2759 false,
2760 ));
2761 }
2762
2763 #[test]
2764 fn should_not_remove_when_alive_and_title_matches() {
2765 let session = ProjectSession {
2766 liveness_title: Some("recorded_title".to_string()),
2767 };
2768 let recorded_title = Some("recorded_title".to_string());
2769
2770 assert!(!should_remove_liveness_session(
2771 &session,
2772 &recorded_title,
2773 Some("recorded_title"),
2774 true,
2775 ));
2776 }
2777
2778 fn budget_daemon(
2779 name: &str,
2780 pid: Option<u32>,
2781 timeout: Option<std::time::Duration>,
2782 ) -> crate::daemon::Daemon {
2783 crate::daemon::Daemon {
2784 id: crate::daemon_id::DaemonId::new("proj", name),
2785 pid,
2786 stop_signal: timeout.map(|timeout| crate::config_types::StopConfig {
2787 timeout: Some(timeout),
2788 ..crate::config_types::StopConfig::default()
2789 }),
2790 ..crate::daemon::Daemon::default()
2791 }
2792 }
2793
2794 #[test]
2795 fn stop_budget_covers_each_running_daemon_in_turn() {
2796 let base = std::time::Duration::from_secs(5);
2797 let sigkill = crate::procs::PROCESS_GROUP_SIGKILL_WAIT;
2798 let daemons = [
2799 budget_daemon("db", Some(1), Some(std::time::Duration::from_secs(4))),
2800 budget_daemon("app", Some(2), Some(std::time::Duration::from_secs(4))),
2801 // No timeout of its own: the supervisor's applies.
2802 budget_daemon("worker", Some(3), None),
2803 // Not running: nothing to stop.
2804 budget_daemon("idle", None, Some(std::time::Duration::from_secs(60))),
2805 crate::daemon::Daemon {
2806 id: crate::daemon_id::DaemonId::pitchfork(),
2807 pid: Some(4),
2808 ..crate::daemon::Daemon::default()
2809 },
2810 ];
2811 assert_eq!(
2812 super::daemons_stop_budget(&daemons, base),
2813 base + (std::time::Duration::from_secs(4) + sigkill) * 2 + (base + sigkill)
2814 );
2815 }
2816
2817 #[test]
2818 fn stop_budget_is_the_base_with_no_running_daemons() {
2819 let base = std::time::Duration::from_secs(5);
2820 assert_eq!(super::daemons_stop_budget(&[], base), base);
2821 }
2822}