1use super::hooks::{self, HookType, fire_hook};
6use super::{SUPERVISOR, Supervisor};
7use crate::config_types::OneshotWait;
8use crate::daemon::RunOptions;
9use crate::daemon_id::DaemonId;
10use crate::daemon_status::DaemonStatus;
11use crate::error::PortError;
12use crate::inherited_fds::CloseInheritedFds;
13use crate::ipc::IpcResponse;
14use crate::log_store::LogStore;
15use crate::log_store::sqlite::LOG_STORE;
16use crate::pitchfork_toml::{ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort, RunCommand};
17use crate::procs::PROCS;
18use crate::settings::{resolve_shell, settings};
19use crate::shell::{HideConsoleWindow, Shell, ShellScript, mise_shell_words};
20use crate::supervisor::state::UpsertDaemonOpts;
21use crate::{Result, env};
22use indexmap::IndexMap;
23use miette::IntoDiagnostic;
24use once_cell::sync::Lazy;
25use regex::Regex;
26use std::collections::HashMap;
27#[cfg(unix)]
28use std::ffi::CString;
29use std::sync::{Arc, atomic};
30use std::time::Duration;
31use tokio::select;
32use tokio::sync::oneshot;
33use tokio::time;
34
35static REGEX_CACHE: Lazy<std::sync::Mutex<HashMap<String, Regex>>> =
37 Lazy::new(|| std::sync::Mutex::new(HashMap::new()));
38
39fn resolve_configured_ready_port(
40 configured_port: u16,
41 expected_ports: &[u16],
42 resolved_ports: &[u16],
43) -> u16 {
44 let bump_offset = resolved_ports
45 .first()
46 .unwrap_or(&0)
47 .saturating_sub(*expected_ports.first().unwrap_or(&0));
48 if expected_ports.contains(&configured_port) && bump_offset > 0 {
49 configured_port
50 .checked_add(bump_offset)
51 .unwrap_or(configured_port)
52 } else {
53 configured_port
54 }
55}
56
57fn active_port_from_ready_port(ready_port: u16, resolved_ports: &[u16]) -> Option<u16> {
58 resolved_ports
59 .first()
60 .copied()
61 .filter(|&primary_port| primary_port == ready_port)
62}
63
64#[cfg(unix)]
65#[derive(Clone, Debug, PartialEq, Eq)]
66enum RunIdentity {
67 Inherit,
68 Switch {
69 uid: nix::unistd::Uid,
70 gid: nix::unistd::Gid,
71 username: Option<CString>,
72 home: Option<std::path::PathBuf>,
74 },
75}
76
77pub(crate) fn get_or_compile_regex(pattern: &str) -> Option<Regex> {
79 let mut cache = REGEX_CACHE.lock().unwrap_or_else(|e| e.into_inner());
80 if let Some(re) = cache.get(pattern) {
81 return Some(re.clone());
82 }
83 match Regex::new(pattern) {
84 Ok(re) => {
85 cache.insert(pattern.to_string(), re.clone());
86 Some(re)
87 }
88 Err(e) => {
89 error!("invalid regex pattern '{pattern}': {e}");
90 None
91 }
92 }
93}
94
95pub(crate) struct CmdProbe {
102 pub(crate) cancel_tx: tokio::sync::oneshot::Sender<()>,
103 pub(crate) result_rx: tokio::sync::oneshot::Receiver<std::io::Result<std::process::ExitStatus>>,
104}
105
106fn apply_runtime_env(
111 command: &mut tokio::process::Command,
112 id: &DaemonId,
113 retry_count: u32,
114 daemon_env: Option<&IndexMap<String, String>>,
115 resolved_ports: &[u16],
116) {
117 if let Some(ref path) = *env::ORIGINAL_PATH {
118 command.env("PATH", path);
119 }
120 if let Some(env_vars) = daemon_env {
121 command.envs(env_vars);
122 }
123 command
124 .env("PITCHFORK_DAEMON_ID", id.qualified())
125 .env("PITCHFORK_DAEMON_NAMESPACE", id.namespace())
126 .env("PITCHFORK_RETRY_COUNT", retry_count.to_string());
127 if let Some(port) = resolved_ports.first() {
128 command.env("PORT", port.to_string());
129 for (index, port) in resolved_ports.iter().enumerate() {
130 command.env(format!("PORT{index}"), port.to_string());
131 }
132 }
133}
134
135fn closed_cmd_probe() -> CmdProbe {
139 let (cancel_tx, _) = tokio::sync::oneshot::channel();
140 let (_, result_rx) = tokio::sync::oneshot::channel();
141 CmdProbe {
142 cancel_tx,
143 result_rx,
144 }
145}
146
147pub(crate) fn spawn_cmd_probe(
154 id: &DaemonId,
155 cmd: &RunCommand,
156 dir: &std::path::Path,
157 retry_count: u32,
158 daemon_env: Option<&IndexMap<String, String>>,
159 resolved_ports: &[u16],
160) -> CmdProbe {
161 let mut command = match cmd {
162 RunCommand::Argv(argv) => {
165 let Some((program, args)) = argv.split_first().filter(|(p, _)| !p.is_empty()) else {
166 warn!("daemon {id}: ready_cmd array has no program to run");
167 return closed_cmd_probe();
168 };
169 let mut c = tokio::process::Command::new(program);
170 c.args(args);
171 c
172 }
173 RunCommand::Shell(cmd) => match resolve_shell() {
179 Ok(parts) => {
180 let (program, args) = parts.split_first().unwrap();
181 let mut c = tokio::process::Command::new(program);
182 c.shell_script(program, args, cmd);
183 c
184 }
185 Err(e) => {
186 warn!("daemon {id}: {e}; using the platform shell for this probe");
187 Shell::default_for_platform().command(cmd)
188 }
189 },
190 };
191 command
192 .current_dir(dir)
193 .stdout(std::process::Stdio::null())
194 .stderr(std::process::Stdio::null())
195 .kill_on_drop(true)
196 .hide_console_window()
197 .close_inherited_fds();
198 apply_runtime_env(&mut command, id, retry_count, daemon_env, resolved_ports);
199 let mut child = match command.spawn() {
200 Ok(child) => child,
201 Err(e) => {
202 warn!("daemon {id}: failed to spawn command probe: {e}");
203 return closed_cmd_probe();
204 }
205 };
206
207 let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
208 let (result_tx, result_rx) = tokio::sync::oneshot::channel();
209
210 tokio::spawn(async move {
211 let status = tokio::select! {
212 status = child.wait() => status,
213 _ = &mut cancel_rx => {
214 let mut child = child;
215 let _ = child.kill().await;
216 child.wait().await
217 }
218 };
219 let _ = result_tx.send(status);
220 });
221
222 CmdProbe {
223 cancel_tx,
224 result_rx,
225 }
226}
227
228fn stop_cmd_probe_state(probe: &mut Option<CmdProbe>) {
230 if let Some(p) = probe.take() {
231 let _ = p.cancel_tx.send(());
232 }
233}
234
235fn spawn_ready_fail_kill(
240 id: DaemonId,
241 pid: u32,
242 stop_cfg: crate::config_types::StopConfig,
243) -> tokio::task::JoinHandle<()> {
244 tokio::spawn(async move {
245 if let Err(e) = PROCS
246 .kill_process_group_async(pid, stop_cfg.signal.into(), stop_cfg.timeout)
247 .await
248 {
249 error!("daemon {id}: failed to kill pid {pid} after readiness failure: {e}");
250 }
251 })
252}
253
254#[allow(clippy::too_many_arguments)]
259fn any_ready_check_remaining(
260 ready_output: Option<&ReadyOutput>,
261 output_exhausted: bool,
262 ready_port: Option<&ReadyPort>,
263 port_exhausted: bool,
264 ready_http: Option<&ReadyHttp>,
265 http_exhausted: bool,
266 ready_cmd: Option<&ReadyCmd>,
267 cmd_exhausted: bool,
268) -> bool {
269 ready_output.is_some_and(|o| o.timeout.is_none() || !output_exhausted)
270 || ready_port.is_some_and(|p| p.timeout.is_none() || !port_exhausted)
271 || ready_http.is_some_and(|h| h.timeout.is_none() || !http_exhausted)
272 || ready_cmd.is_some_and(|c| c.timeout.is_none() || !cmd_exhausted)
273}
274
275fn delay_readiness_succeeded(
276 ready_notified: bool,
277 has_other_ready_check: bool,
278 process_exited: bool,
279 process_running: bool,
280) -> bool {
281 !ready_notified && !has_other_ready_check && !process_exited && process_running
282}
283
284fn terminal_exit_state(
293 exit_reason: &str,
294 oneshot: bool,
295 exit_code: i32,
296 exited_cleanly: bool,
297) -> (DaemonStatus, bool) {
298 match exit_reason {
299 "exit" if oneshot => (DaemonStatus::Completed, true),
300 "stop" | "exit" => (DaemonStatus::Stopped, exited_cleanly),
301 _ => (DaemonStatus::Errored(exit_code), false),
302 }
303}
304
305fn invalid_probe_program(id: &DaemonId, field: &str, run: Option<&RunCommand>) -> Option<String> {
323 let RunCommand::Argv(argv) = run? else {
324 return None;
325 };
326 match argv.first().map(String::as_str) {
327 None | Some("") => Some(format!(
328 "daemon {id} has no program to run in its {field} array"
329 )),
330 Some("exec") => Some(format!(
331 "daemon {id} starts its {field} array with \"exec\"; a {field} array runs the program directly, so remove \"exec\""
332 )),
333 Some(_) => None,
334 }
335}
336
337fn invalid_argv_program(id: &DaemonId, argv: &[String]) -> Option<String> {
338 match argv.first().map(String::as_str) {
339 None | Some("") => Some(format!(
340 "daemon {id} has no program to run: its run array starts with an empty value"
341 )),
342 Some("exec") => Some(format!(
343 "daemon {id} starts its run array with \"exec\"; a run array starts the program directly, so remove \"exec\""
344 )),
345 Some(_) => None,
346 }
347}
348
349#[cfg(any(windows, test))]
350fn unsupported_windows_options(opts: &RunOptions, supervisor_user: &str) -> Option<String> {
351 if opts.pty == Some(true) {
352 return Some(format!(
353 "daemon {}: pty = true is not supported on Windows; remove pty or set it to false",
354 opts.id
355 ));
356 }
357 let configured_user = opts.user.as_deref().unwrap_or_default().trim();
358 if !configured_user.is_empty() || !supervisor_user.trim().is_empty() {
359 return Some(format!(
360 "daemon {}: user switching is not supported on Windows; remove the daemon's user and settings.supervisor.user, or set them to empty strings",
361 opts.id
362 ));
363 }
364 None
365}
366
367fn launch_command(words: Vec<String>, mise_bin: Option<&std::path::Path>) -> (String, Vec<String>) {
370 match mise_bin {
371 Some(mise_bin) => {
372 let mut args = vec!["x".to_string(), "--".to_string()];
373 args.extend(words);
374 (mise_bin.to_string_lossy().to_string(), args)
375 }
376 None => {
377 let mut words = words.into_iter();
378 let program = words.next().unwrap_or_default();
381 (program, words.collect())
382 }
383 }
384}
385
386fn output_line_text(line: &[u8]) -> String {
392 let line = line.strip_suffix(b"\n").unwrap_or(line);
393 crate::cli::log_sink::decode_line(line)
394 .trim_end_matches('\r')
395 .to_string()
396}
397
398async fn forward_output_lines<R>(mut reader: R, tx: tokio::sync::mpsc::Sender<super::OutputLine>)
405where
406 R: tokio::io::AsyncBufRead + Unpin,
407{
408 use tokio::io::AsyncBufReadExt;
409 let mut line = Vec::new();
410 loop {
411 line.clear();
412 let last = match reader.read_until(b'\n', &mut line).await {
417 Ok(0) => break,
418 Ok(_) => false,
419 Err(_) if line.is_empty() => break,
420 Err(_) => true,
421 };
422 let sent = tx
423 .send(super::OutputLine {
424 text: output_line_text(&line),
425 source: super::OutputSource::Local,
426 })
427 .await;
428 if sent.is_err() || last {
429 break;
430 }
431 }
432}
433
434fn stop_keeps_finalized_status(status: &DaemonStatus) -> bool {
435 status.is_completed()
436}
437
438const SINK_OUTPUT_TIMEOUT: Duration = Duration::from_millis(400);
443
444struct StopEpochGuard(DaemonId);
451
452impl Drop for StopEpochGuard {
453 fn drop(&mut self) {
454 SUPERVISOR.bump_stop_epoch(&self.0);
455 }
456}
457
458pub(crate) struct RetryingGuard {
459 id: DaemonId,
460 cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
461}
462
463impl RetryingGuard {
464 fn is_cancelled(&self) -> bool {
466 self.cancel.load(std::sync::atomic::Ordering::Acquire)
467 }
468}
469
470impl Drop for RetryingGuard {
471 fn drop(&mut self) {
472 let mut retrying = SUPERVISOR
473 .retrying
474 .lock()
475 .unwrap_or_else(|e| e.into_inner());
476 if let Some(claims) = retrying.get_mut(&self.id) {
480 claims.retain(|flag| !std::sync::Arc::ptr_eq(flag, &self.cancel));
481 if claims.is_empty() {
482 retrying.remove(&self.id);
483 }
484 }
485 }
486}
487
488impl Supervisor {
489 pub(crate) fn is_retrying(&self, id: &DaemonId) -> bool {
492 self.retrying
493 .lock()
494 .unwrap_or_else(|e| e.into_inner())
495 .get(id)
496 .is_some_and(|claims| !claims.is_empty())
497 }
498
499 pub(crate) fn stop_epoch(&self, id: &DaemonId) -> u64 {
501 self.stop_epochs
502 .lock()
503 .unwrap_or_else(|e| e.into_inner())
504 .get(id)
505 .copied()
506 .unwrap_or(0)
507 }
508
509 fn bump_stop_epoch(&self, id: &DaemonId) {
510 *self
511 .stop_epochs
512 .lock()
513 .unwrap_or_else(|e| e.into_inner())
514 .entry(id.clone())
515 .or_default() += 1;
516 }
517
518 fn mark_retrying(&self, id: &DaemonId) -> RetryingGuard {
519 let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
520 self.retrying
521 .lock()
522 .unwrap_or_else(|e| e.into_inner())
523 .entry(id.clone())
524 .or_default()
525 .push(cancel.clone());
526 RetryingGuard {
527 id: id.clone(),
528 cancel,
529 }
530 }
531
532 pub(crate) fn cancel_retrying(&self, id: &DaemonId) {
536 if let Some(claims) = self
537 .retrying
538 .lock()
539 .unwrap_or_else(|e| e.into_inner())
540 .get(id)
541 {
542 for cancel in claims {
546 cancel.store(true, std::sync::atomic::Ordering::Release);
547 }
548 }
549 }
550
551 pub async fn run(&self, opts: RunOptions) -> Result<IpcResponse> {
553 let id = opts.id.clone();
554 let mut restart_mark = None;
555 let result = self.run_inner(opts, None, &mut restart_mark).await;
556 if let Some(mark) = restart_mark {
559 self.settle_restarting(&id, mark).await;
560 }
561 result
562 }
563
564 pub(crate) async fn settle_restarting(&self, id: &DaemonId, mark: u64) {
573 let lock = self.stop_lock(id).await;
574 let _guard = lock.lock().await;
575 if self.stop_epoch(id) != mark {
576 return;
577 }
578 let mut state_file = self.state_file.lock().await;
579 if state_file
580 .daemons
581 .get(id)
582 .is_some_and(|d| d.pid.is_none() && d.status.is_restarting())
583 {
584 debug!("daemon {id} was not started again after its restart; recording it as stopped");
585 state_file.set_status(id, DaemonStatus::Stopped);
586 }
587 }
588
589 pub(crate) async fn run_retry(
596 &self,
597 opts: RunOptions,
598 approved_at: u64,
599 restart_mark: &mut Option<u64>,
600 ) -> Result<IpcResponse> {
601 self.run_inner(opts, Some(approved_at), restart_mark).await
602 }
603
604 #[cfg(windows)]
606 async fn reject_unsupported_windows_options(
607 &self,
608 opts: &RunOptions,
609 ) -> Result<Option<IpcResponse>> {
610 let Some(error) = unsupported_windows_options(opts, &settings().supervisor.user) else {
611 return Ok(None);
612 };
613 if self
617 .get_daemon(&opts.id)
618 .await
619 .is_none_or(|d| d.pid.is_none())
620 {
621 self.upsert_daemon(
622 UpsertDaemonOpts::from_run_options(opts, DaemonStatus::Failed(error.clone()))
623 .build(),
624 )
625 .await?;
626 }
627 Ok(Some(IpcResponse::DaemonFailed { error }))
628 }
629
630 async fn run_inner(
634 &self,
635 opts: RunOptions,
636 approved_at: Option<u64>,
637 restart_mark: &mut Option<u64>,
638 ) -> Result<IpcResponse> {
639 let id = &opts.id;
640 let cmd = opts.cmd.clone();
641
642 {
644 let mut pending = self.pending_autostops.lock().await;
645 if pending.remove(id).is_some() {
646 info!("cleared pending autostop for {id} (daemon starting)");
647 }
648 }
649
650 let mut stop_guard = Some(self.stop_lock(id).await.lock_owned().await);
661 if let Some(approved_at) = approved_at
666 && self.stop_epoch(id) != approved_at
667 {
668 info!("daemon {id} was stopped after this retry was decided on; not starting it");
669 return Ok(IpcResponse::DaemonNotRunning);
670 }
671 if (approved_at.is_some() || !opts.requested_by_client)
675 && self.state_file.lock().await.disabled.contains(id)
676 {
677 info!("daemon {id} was disabled before this start; not starting it");
678 return Ok(IpcResponse::DaemonNotRunning);
679 }
680 if let Some(response) = self
681 .claim_or_defer(&opts, &mut stop_guard, restart_mark)
682 .await?
683 {
684 return Ok(response);
685 }
686
687 if opts.wait_ready && opts.retry.count() > 0 {
689 let retrying_claim = self.mark_retrying(id);
694 let max_attempts = opts.retry.count().saturating_add(1);
696 for attempt in 0..max_attempts {
697 let mut retry_opts = opts.clone();
698 retry_opts.retry_count = attempt;
699 retry_opts.cmd = cmd.clone();
700
701 let mut guard = Some(match stop_guard.take() {
705 Some(guard) => guard,
706 None => self.stop_lock(id).await.lock_owned().await,
707 });
708 if attempt > 0
718 && let Some(daemon) = self.get_daemon(id).await
719 && daemon.status.is_completed()
720 {
721 info!("daemon {id} completed while waiting to retry; not running it again");
722 return Ok(IpcResponse::DaemonReady { daemon });
723 }
724 if attempt > 0 && self.state_file.lock().await.disabled.contains(id) {
728 info!(
729 "daemon {id} was disabled while waiting to retry; abandoning its retries"
730 );
731 return Ok(IpcResponse::DaemonFailed {
732 error: "disabled while retrying".to_string(),
733 });
734 }
735 if retrying_claim.is_cancelled() {
740 info!("daemon {id} was stopped while waiting to retry; abandoning its retries");
741 return Ok(IpcResponse::DaemonFailed {
742 error: "stopped while retrying".to_string(),
743 });
744 }
745 if let Some(response) = self
751 .claim_or_defer(&retry_opts, &mut guard, restart_mark)
752 .await?
753 {
754 return Ok(response);
755 }
756 let Some(guard) = guard else {
757 return Ok(IpcResponse::DaemonAlreadyRunning);
760 };
761 let result = self.run_once(retry_opts, guard).await?;
762
763 match result {
764 IpcResponse::DaemonReady { daemon } => {
765 return Ok(IpcResponse::DaemonReady { daemon });
766 }
767 IpcResponse::DaemonFailedWithCode {
768 exit_code,
769 resolved_ports,
770 } => {
771 if attempt < opts.retry.count() {
772 let attempt_pid = self.get_daemon(id).await.and_then(|d| d.pid);
780 self.wait_for_exit_finalized(id, attempt_pid).await;
781 let backoff_secs = 2u64.saturating_pow(attempt).min(3600);
782 info!(
783 "daemon {id} failed (attempt {}/{}), retrying in {}s",
784 attempt + 1,
785 max_attempts,
786 backoff_secs
787 );
788 fire_hook(
789 HookType::OnRetry,
790 id.clone(),
791 super::hooks::HookDirs::new(
792 opts.dir.0.clone(),
793 opts.watch_base_dir.clone(),
794 ),
795 attempt + 1,
796 opts.env.clone(),
797 resolved_ports,
798 vec![],
799 )
800 .await;
801 let backoff_deadline =
806 tokio::time::Instant::now() + Duration::from_secs(backoff_secs);
807 while tokio::time::Instant::now() < backoff_deadline
808 && !retrying_claim.is_cancelled()
809 {
810 let remaining = backoff_deadline - tokio::time::Instant::now();
811 time::sleep(remaining.min(Duration::from_millis(200))).await;
812 }
813 continue;
814 } else {
815 info!("daemon {id} failed after {max_attempts} attempts");
816 return Ok(IpcResponse::DaemonFailedWithCode {
817 exit_code,
818 resolved_ports,
819 });
820 }
821 }
822 other => return Ok(other),
823 }
824 }
825 }
826
827 let guard = match stop_guard.take() {
829 Some(guard) => guard,
830 None => self.stop_lock(id).await.lock_owned().await,
831 };
832 self.run_once(opts, guard).await
833 }
834
835 async fn wait_for_exit_finalized(&self, id: &DaemonId, pid: Option<u32>) {
846 let deadline = tokio::time::Instant::now() + Duration::from_secs(8);
847 loop {
848 match self.get_daemon(id).await {
849 Some(daemon) if pid.map_or(daemon.pid.is_some(), |pid| daemon.pid == Some(pid)) => {
850 }
851 _ => return,
852 }
853 if tokio::time::Instant::now() >= deadline {
854 debug!("daemon {id}: previous attempt has not finalized yet; continuing anyway");
855 return;
856 }
857 time::sleep(Duration::from_millis(50)).await;
858 }
859 }
860
861 async fn claim_or_defer(
876 &self,
877 opts: &RunOptions,
878 stop_guard: &mut Option<tokio::sync::OwnedMutexGuard<()>>,
879 restart_mark: &mut Option<u64>,
880 ) -> Result<Option<IpcResponse>> {
881 let id = &opts.id;
882 #[cfg(windows)]
883 if let Some(response) = self.reject_unsupported_windows_options(opts).await? {
884 return Ok(Some(response));
885 }
886 let Some(daemon) = self.get_daemon(id).await else {
887 return Ok(None);
888 };
889 if opts.on_directory_enter && opts.oneshot && daemon.status.is_completed() {
900 debug!("daemon {id} already completed; directory entry leaves it alone");
901 return Ok(Some(IpcResponse::DaemonReady { daemon }));
902 }
903 if daemon.status.is_stopping_or_restarting()
907 || daemon.status.is_stopped()
908 || daemon.status.is_completed()
909 {
910 return Ok(None);
911 }
912 let Some(pid) = daemon.pid else {
913 return Ok(None);
914 };
915 if opts.force {
916 self.stop_locked_with(id, true).await?;
920 *restart_mark = Some(self.stop_epoch(id));
923 info!("run: stop completed for daemon {id}");
924 return Ok(None);
925 }
926 if daemon.oneshot && opts.wait_ready {
927 info!("daemon {id} is an in-flight oneshot (pid {pid}); waiting for it to finish");
932 drop(stop_guard.take());
933 return Ok(Some(
934 self.await_running_oneshot(id, opts.oneshot_wait, pid).await,
935 ));
936 }
937 PROCS.refresh_pids(&[pid]);
946 if !PROCS.is_running(pid) {
947 debug!(
948 "daemon {id}: record still names pid {pid}, which has exited; its monitor has not finalized yet"
949 );
950 return Ok(None);
951 }
952 warn!("daemon {id} already running with pid {pid}");
953 Ok(Some(IpcResponse::DaemonAlreadyRunning))
954 }
955
956 async fn await_running_oneshot(
963 &self,
964 id: &DaemonId,
965 wait: Option<OneshotWait>,
966 watched_pid: u32,
967 ) -> IpcResponse {
968 let interval = settings().supervisor_ready_check_interval();
969 let deadline = wait
985 .unwrap_or_else(|| settings().supervisor_oneshot_wait())
986 .duration()
987 .map(|d| tokio::time::Instant::now() + d);
988 let mut watched_pid = watched_pid;
996 loop {
997 let Some(daemon) = self.get_daemon(id).await else {
998 return IpcResponse::DaemonNotFound;
999 };
1000 if let Some(current) = daemon.pid
1001 && current != watched_pid
1002 {
1003 info!(
1004 "daemon {id}: the run being waited on (pid {watched_pid}) was replaced by pid {current}; following it"
1005 );
1006 watched_pid = current;
1007 }
1008 match &daemon.status {
1009 DaemonStatus::Completed => {
1010 info!("daemon {id}: the in-flight oneshot completed");
1011 return IpcResponse::DaemonReady { daemon };
1012 }
1013 DaemonStatus::Errored(code) => {
1014 if daemon.retry.count() > 0
1022 && daemon.retry_count < daemon.retry.count()
1023 && !self.state_file.lock().await.disabled.contains(id)
1024 {
1025 debug!(
1026 "daemon {id}: in-flight oneshot failed attempt {} of {}; still waiting",
1027 daemon.retry_count + 1,
1028 daemon.retry.count() + 1
1029 );
1030 } else {
1031 let exit_code = Some(*code).filter(|c| *c != -1);
1035 return IpcResponse::DaemonFailedWithCode {
1036 exit_code,
1037 resolved_ports: daemon.resolved_port.clone(),
1038 };
1039 }
1040 }
1041 DaemonStatus::Failed(error) => {
1042 return IpcResponse::DaemonFailed {
1043 error: error.clone(),
1044 };
1045 }
1046 DaemonStatus::Stopped => {
1047 warn!("daemon {id}: the in-flight oneshot was stopped before completing");
1050 return IpcResponse::DaemonFailedWithCode {
1051 exit_code: None,
1052 resolved_ports: daemon.resolved_port.clone(),
1053 };
1054 }
1055 DaemonStatus::Running
1056 | DaemonStatus::Waiting
1057 | DaemonStatus::Stopping
1058 | DaemonStatus::Restarting => {}
1059 }
1060 if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
1061 warn!("daemon {id}: gave up waiting for the in-flight oneshot to finish");
1062 return IpcResponse::DaemonFailedWithCode {
1068 exit_code: Some(124),
1069 resolved_ports: Vec::new(),
1070 };
1071 }
1072 time::sleep(interval).await;
1073 }
1074 }
1075
1076 pub(crate) async fn run_once(
1083 &self,
1084 opts: RunOptions,
1085 stop_guard: tokio::sync::OwnedMutexGuard<()>,
1086 ) -> Result<IpcResponse> {
1087 let id = &opts.id;
1088 if self
1095 .shutting_down
1096 .load(std::sync::atomic::Ordering::Acquire)
1097 {
1098 info!("not starting daemon {id}: the supervisor is shutting down");
1099 return Ok(IpcResponse::DaemonFailed {
1100 error: "the supervisor is shutting down".to_string(),
1101 });
1102 }
1103 #[cfg(windows)]
1105 if let Some(response) = self.reject_unsupported_windows_options(&opts).await? {
1106 return Ok(response);
1107 }
1108 let original_cmd = opts.cmd.clone(); let (ready_tx, ready_rx) = if opts.wait_ready {
1112 let (tx, rx) = oneshot::channel();
1113 (Some(tx), Some(rx))
1114 } else {
1115 (None, None)
1116 };
1117
1118 let expected_ports = opts
1120 .port
1121 .as_ref()
1122 .map(|p| p.expect.clone())
1123 .unwrap_or_default();
1124 let (resolved_ports, effective_ready_port) = if !expected_ports.is_empty() {
1125 let port_cfg = opts.port.as_ref().unwrap();
1126 match check_ports_available(
1127 &expected_ports,
1128 port_cfg.auto_bump(),
1129 port_cfg.max_bump_attempts(),
1130 )
1131 .await
1132 {
1133 Ok(resolved) => {
1134 let ready_port = if let Some(configured_port) =
1135 opts.ready_port.as_ref().and_then(|p| p.as_port())
1136 {
1137 Some(resolve_configured_ready_port(
1138 configured_port,
1139 &expected_ports,
1140 &resolved,
1141 ))
1142 } else if opts.ready_output.is_none()
1143 && opts.ready_http.is_none()
1144 && opts.ready_cmd.is_none()
1145 && opts.ready_delay.is_none()
1146 {
1147 resolved.first().copied().filter(|&p| p != 0)
1151 } else {
1152 None
1156 };
1157 info!("daemon {id}: ports {expected_ports:?} resolved to {resolved:?}");
1158 (resolved, ready_port)
1159 }
1160 Err(e) => {
1161 error!("daemon {id}: port check failed: {e}");
1162 if let Some(port_error) = e.downcast_ref::<PortError>() {
1164 match port_error {
1165 PortError::InUse {
1166 port,
1167 address,
1168 process,
1169 pid,
1170 } => {
1171 return Ok(IpcResponse::PortConflict {
1172 port: *port,
1173 process: process.clone(),
1174 pid: *pid,
1175 address: address.clone(),
1176 });
1177 }
1178 PortError::NoAvailablePort {
1179 start_port,
1180 attempts,
1181 } => {
1182 return Ok(IpcResponse::NoAvailablePort {
1183 start_port: *start_port,
1184 attempts: *attempts,
1185 });
1186 }
1187 }
1188 }
1189 return Ok(IpcResponse::DaemonFailed {
1190 error: e.to_string(),
1191 });
1192 }
1193 }
1194 } else {
1195 if let Some(port) = opts.ready_port.as_ref().and_then(|p| p.as_port())
1201 && port > 0
1202 && let Some((address, pid, process)) = detect_port_conflict(port).await
1203 {
1204 return Ok(IpcResponse::PortConflict {
1205 port,
1206 process,
1207 pid,
1208 address: Some(address),
1209 });
1210 }
1211 (
1212 Vec::new(),
1213 opts.ready_port.as_ref().and_then(|p| p.as_port()),
1214 )
1215 };
1216
1217 if let Some(error) = invalid_probe_program(
1222 id,
1223 "ready_cmd",
1224 opts.ready_cmd.as_ref().map(|c| &c.run),
1225 )
1226 .or_else(|| {
1227 invalid_probe_program(id, "health_cmd", opts.health_cmd.as_ref().map(|c| &c.run))
1228 }) {
1229 return Ok(IpcResponse::DaemonFailed { error });
1230 }
1231
1232 let (mut words, script) = if opts.no_shell {
1233 if let Some(error) = invalid_argv_program(id, &original_cmd) {
1236 return Ok(IpcResponse::DaemonFailed { error });
1237 }
1238 (original_cmd.clone(), None)
1239 } else {
1240 let words = match resolve_shell() {
1244 Ok(parts) => parts,
1245 Err(error) => return Ok(IpcResponse::DaemonFailed { error }),
1246 };
1247 let script = opts
1252 .run
1253 .clone()
1254 .unwrap_or_else(|| shell_words::join(&original_cmd));
1255 (words, Some(script))
1256 };
1257
1258 let mise_bin = if opts.mise.unwrap_or(settings().general.mise) {
1259 let mise_bin = settings().resolve_daemon_mise_bin(opts.mise_bin.as_deref());
1260 if mise_bin.is_none() {
1261 warn!("daemon {id}: mise=true but mise binary not found, running without mise");
1262 }
1263 mise_bin
1264 } else {
1265 None
1266 };
1267 if mise_bin.is_none() && opts.deferred_template_context.is_some() {
1271 return Ok(IpcResponse::DaemonFailed {
1272 error: format!(
1273 "daemon {id}: the command uses template variables only mise can render, but mise is not enabled or its binary was not found"
1274 ),
1275 });
1276 }
1277 let script = match &mise_bin {
1282 Some(mise_bin) => {
1283 info!(
1284 "daemon {id}: wrapping command with mise ({})",
1285 mise_bin.display()
1286 );
1287 if let Some(script) = script {
1288 words =
1289 mise_shell_words(words, script, opts.deferred_template_context.is_some());
1290 }
1291 None
1292 }
1293 None => script,
1294 };
1295 let (program, args) = launch_command(words, mise_bin.as_deref());
1296 #[cfg(unix)]
1297 let run_identity = match resolve_effective_run_identity(opts.user.as_deref()) {
1298 Ok(identity) => identity,
1299 Err(e) => {
1300 return Ok(IpcResponse::DaemonFailed {
1301 error: e.to_string(),
1302 });
1303 }
1304 };
1305 info!("run: spawning daemon {id} with {program} {args:?} {script:?}");
1306
1307 #[cfg(unix)]
1309 let pty_pair = if opts.pty.unwrap_or(false) {
1310 match super::pty::openpty() {
1311 Ok(pair) => {
1312 info!("daemon {id}: allocated PTY (pty = true)");
1313 Some(pair)
1314 }
1315 Err(e) => {
1316 warn!("daemon {id}: failed to allocate PTY, falling back to pipes: {e}");
1317 None
1318 }
1319 }
1320 } else {
1321 None
1322 };
1323
1324 let (output_tx, output_rx) = tokio::sync::mpsc::channel::<super::OutputLine>(256);
1330 let mut output_relay = None;
1331
1332 let mut sink_pipe = None;
1335 let mut sink_writer = None;
1336 let mut sink_child = None;
1337 if super::log_sink::is_supported(&opts) {
1338 let log_format = opts
1339 .log_format
1340 .clone()
1341 .unwrap_or_else(|| settings().logs.log_format.clone());
1342 let watch_for = super::log_sink::WatchFor::from_opts(id, &opts);
1343 let relay_token = if watch_for.is_empty() {
1346 0
1347 } else {
1348 let relay = super::log_sink::OutputRelay::register(id, output_tx.clone());
1349 let token = relay.token();
1350 output_relay = Some(relay);
1351 token
1352 };
1353 match super::log_sink::SinkPipe::new(log_format, watch_for, relay_token) {
1354 Ok((pipe, writer)) => match pipe.start(id) {
1355 Ok(child) => {
1356 sink_child = Some(super::log_sink::PendingSink::new(child));
1357 sink_pipe = Some(pipe);
1358 sink_writer = Some(writer);
1359 }
1360 Err(e) => {
1361 warn!("could not start log sink for {id}, capturing in-process: {e}");
1362 }
1363 },
1364 Err(e) => {
1365 warn!("could not create log pipe for {id}, capturing in-process: {e}");
1368 }
1369 }
1370 }
1371
1372 let mut cmd = tokio::process::Command::new(&program);
1373
1374 #[cfg(unix)]
1375 if let Some(ref pair) = pty_pair {
1376 let slave_file = std::fs::File::from(
1380 pair.slave
1381 .try_clone()
1382 .map_err(|e| miette::miette!("failed to dup slave PTY fd: {e}"))?,
1383 );
1384 cmd.stdin(std::process::Stdio::from(slave_file.try_clone().map_err(
1385 |e| miette::miette!("failed to clone slave PTY fd for stdin: {e}"),
1386 )?));
1387 cmd.stdout(std::process::Stdio::from(slave_file.try_clone().map_err(
1388 |e| miette::miette!("failed to clone slave PTY fd for stdout: {e}"),
1389 )?));
1390 cmd.stderr(std::process::Stdio::from(slave_file));
1391 } else if let Some(writer) = sink_writer.take() {
1392 let dup = writer
1395 .try_clone()
1396 .map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
1397 cmd.stdout(std::process::Stdio::from(writer))
1398 .stderr(std::process::Stdio::from(dup));
1399 } else {
1400 cmd.stdout(std::process::Stdio::piped())
1401 .stderr(std::process::Stdio::piped());
1402 }
1403
1404 #[cfg(not(unix))]
1405 if let Some(writer) = sink_writer.take() {
1406 let dup = writer
1407 .try_clone()
1408 .map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
1409 cmd.stdout(std::process::Stdio::from(writer))
1410 .stderr(std::process::Stdio::from(dup));
1411 } else {
1412 cmd.stdout(std::process::Stdio::piped())
1413 .stderr(std::process::Stdio::piped());
1414 }
1415
1416 match &script {
1417 Some(script) => cmd.shell_script(&program, &args, script),
1418 None => cmd.args(&args),
1419 };
1420 cmd.current_dir(&opts.dir)
1421 .hide_console_window()
1422 .close_inherited_fds();
1423
1424 #[cfg(unix)]
1425 if pty_pair.is_none() {
1426 cmd.stdin(std::process::Stdio::null());
1427 }
1428
1429 #[cfg(not(unix))]
1430 cmd.stdin(std::process::Stdio::null());
1431
1432 #[cfg(unix)]
1434 apply_identity_env(&mut cmd, &run_identity);
1435 apply_runtime_env(
1436 &mut cmd,
1437 id,
1438 opts.retry_count,
1439 opts.env.as_ref(),
1440 &resolved_ports,
1441 );
1442 if let Some(context) = &opts.deferred_template_context {
1444 cmd.env(crate::template::TEMPLATE_CONTEXT_ENV, context);
1445 }
1446
1447 inject_proxy_env(&mut cmd, &daemon_proxy_host(&opts).await);
1449
1450 #[cfg(unix)]
1451 {
1452 let run_identity = run_identity.clone();
1453 let use_pty = pty_pair.is_some();
1454 unsafe {
1455 cmd.pre_exec(move || {
1456 nix::unistd::setsid().map_err(nix_to_io_error)?;
1457
1458 if use_pty {
1462 let ret = libc::ioctl(0, libc::TIOCSCTTY as _, 0);
1463 if ret < 0 {
1464 #[cfg(target_os = "linux")]
1467 eprintln!(
1468 "pitchfork: TIOCSCTTY failed: {}",
1469 std::io::Error::last_os_error()
1470 );
1471 }
1472 }
1473
1474 apply_run_identity(&run_identity)?;
1475 Ok(())
1476 });
1477 }
1478 }
1479
1480 let spawn_time = chrono::Local::now();
1483 let mut child = cmd.spawn().into_diagnostic()?;
1489 #[cfg(windows)]
1492 if let (Some(pid), Some(process)) = (child.id(), child.raw_handle()) {
1493 crate::win_job::contain_spawned(process as _, pid);
1494 }
1495 let spawned_pid = child.id();
1496 let monitored_guard =
1506 spawned_pid.map(|pid| super::adopt::MonitoredGuard::register(id.clone(), pid));
1507 if opts.cron_started {
1523 let mut state_file = self.state_file.lock().await;
1524 if state_file.set_last_cron_run(id, spawn_time)
1525 && let Err(e) = state_file.write()
1526 {
1527 error!("failed to persist last_cron_run for daemon {id}: {e}");
1528 }
1529 }
1530 let (pid, monitored_guard) = match (spawned_pid, monitored_guard) {
1531 (Some(p), Some(guard)) => (p, guard),
1532 _ => {
1533 warn!("Daemon {id} exited before PID could be captured");
1534 if sink_child.is_some() {
1540 super::log_sink::wait_for_output(id, spawn_time, SINK_OUTPUT_TIMEOUT).await;
1541 }
1542 return Ok(IpcResponse::DaemonFailed {
1543 error: "Process exited immediately".to_string(),
1544 });
1545 }
1546 };
1547 info!("started daemon {id} with pid {pid}");
1548 PROCS.refresh_pids(&[pid]);
1549 let monitor_token = monitored_guard.token();
1550
1551 let using_sink = sink_pipe.is_some();
1554 if let Some(pipe) = sink_pipe.take()
1557 && let Some(child) = sink_child.as_mut().and_then(|pending| pending.take())
1558 {
1559 pipe.supervise(id.clone(), monitor_token, child);
1560 }
1561 let attempt_resolved_ports = resolved_ports.clone();
1568 let daemon = self
1569 .upsert_daemon(
1570 UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
1571 .set(|o| {
1572 o.pid = Some(pid);
1573 o.cmd = Some(original_cmd);
1574 o.ready_port = effective_ready_port.map(|p| ReadyPort {
1575 port: Some(p),
1576 template: None,
1577 timeout: opts.ready_port.as_ref().and_then(|rp| rp.timeout),
1578 });
1579 o.port = crate::config_types::PortConfig::from_parts(
1580 expected_ports,
1581 opts.port.as_ref().map(|p| p.bump).unwrap_or_default(),
1582 );
1583 o.resolved_port = Some(resolved_ports);
1584 })
1585 .build(),
1586 )
1587 .await?;
1588
1589 drop(stop_guard);
1594
1595 let id_clone = id.clone();
1596 let ready_delay = (!opts.oneshot).then_some(opts.ready_delay).flatten();
1604 let ready_output = (!opts.oneshot).then(|| opts.ready_output.clone()).flatten();
1605 let ready_http = (!opts.oneshot).then(|| opts.ready_http.clone()).flatten();
1606 let ready_port = (!opts.oneshot).then_some(effective_ready_port).flatten();
1607 let implicit_ready_port = ready_port.map(|p| ReadyPort {
1608 port: Some(p),
1609 template: None,
1610 timeout: None,
1611 });
1612 let ready_port_config = (!opts.oneshot)
1613 .then(|| opts.ready_port.clone())
1614 .flatten()
1615 .or(implicit_ready_port);
1616 let ready_cmd = (!opts.oneshot).then(|| opts.ready_cmd.clone()).flatten();
1617 let daemon_dir = opts.dir.0.clone();
1618 let hook_dirs =
1619 super::hooks::HookDirs::new(daemon_dir.clone(), opts.watch_base_dir.clone());
1620 let hook_retry_count = opts.retry_count;
1621 let hook_retry = opts.retry;
1622 let hook_daemon_env = opts.env.clone();
1623 let hook_resolved_ports = attempt_resolved_ports.clone();
1628 let readiness_daemon_env = opts.env.clone();
1629 let readiness_resolved_ports = attempt_resolved_ports.clone();
1630 let on_output_hook = opts.on_output_hook.clone();
1631 let has_port_config = opts.port.as_ref().is_some_and(|p| !p.expect.is_empty())
1637 || (settings().proxy.enable && is_daemon_slug_target(id));
1638 let daemon_pid = pid;
1644
1645 #[cfg(unix)]
1649 let pty_reader = pty_pair.map(|p| {
1650 tokio::io::BufReader::new(tokio::fs::File::from_std(std::fs::File::from(p.master)))
1651 });
1652 #[cfg(not(unix))]
1653 let pty_reader: Option<tokio::io::BufReader<tokio::fs::File>> = None;
1654 let stdout_reader = if pty_reader.is_none() {
1655 child.stdout.take().map(tokio::io::BufReader::new)
1656 } else {
1657 None
1658 };
1659 let stderr_reader = if pty_reader.is_none() {
1660 child.stderr.take().map(tokio::io::BufReader::new)
1661 } else {
1662 None
1663 };
1664
1665 if !using_sink
1666 && pty_reader.is_none()
1667 && (stdout_reader.is_none() || stderr_reader.is_none())
1668 {
1669 error!("Failed to capture stdout/stderr for daemon {id}");
1670 }
1671
1672 tokio::spawn(async move {
1673 let id = id_clone;
1674 let _monitored_guard = monitored_guard;
1677 let output_relay = output_relay;
1681
1682 let mut output_rx = output_rx;
1685
1686 if let Some(reader) = pty_reader {
1687 tokio::spawn(forward_output_lines(reader, output_tx));
1691 } else {
1692 if let Some(stdout) = stdout_reader {
1697 tokio::spawn(forward_output_lines(stdout, output_tx.clone()));
1698 }
1699 if let Some(stderr) = stderr_reader {
1700 tokio::spawn(forward_output_lines(stderr, output_tx.clone()));
1701 }
1702 drop(output_tx);
1706 }
1707 let log_store = Arc::clone(&LOG_STORE);
1708 let log_format = opts
1709 .log_format
1710 .clone()
1711 .unwrap_or_else(|| crate::settings::settings().logs.log_format.clone());
1712 let parse_line = move |line: &str| crate::log_parse::parse(line, &log_format);
1713
1714 const LOG_BATCH_SIZE: usize = 100;
1715 const LOG_FLUSH_INTERVAL: Duration = Duration::from_millis(100);
1716 let mut log_buffer: Vec<crate::log_parse::ParsedLog> =
1717 Vec::with_capacity(LOG_BATCH_SIZE);
1718 let mut log_flush_interval = tokio::time::interval(LOG_FLUSH_INTERVAL);
1719 log_flush_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
1720
1721 let flush_logs =
1722 |buffer: &mut Vec<crate::log_parse::ParsedLog>| -> Option<tokio::task::JoinHandle<()>> {
1723 if buffer.is_empty() {
1724 return None;
1725 }
1726 let store = Arc::clone(&log_store);
1727 let id = id.clone();
1728 let batch = std::mem::take(buffer);
1729 Some(tokio::task::spawn_blocking(move || {
1730 if let Err(e) = store.append_structured_batch(&id, &batch) {
1731 error!("Failed to write batch to log for daemon {id}: {e}");
1732 }
1733 }))
1734 };
1735
1736 let mut ready_notified = false;
1740 let mut oneshot_completion_pending = false;
1745 let mut ready_tx = ready_tx;
1746 let ready_pattern = ready_output
1747 .as_ref()
1748 .and_then(|o| get_or_compile_regex(&o.pattern));
1749 let mut active_port_spawned = false;
1751
1752 let on_output_hook = match on_output_hook {
1756 Some(ref hook) => match hook.validate(id.name()) {
1757 Ok(()) => on_output_hook,
1758 Err(e) => {
1759 error!("{e}");
1760 None
1761 }
1762 },
1763 None => None,
1764 };
1765
1766 let on_output_pattern: Option<regex::Regex> = on_output_hook
1769 .as_ref()
1770 .and_then(|h| h.regex.as_deref().and_then(get_or_compile_regex));
1771 let on_output_debounce = on_output_hook
1772 .as_ref()
1773 .map(|h| h.debounce_duration())
1774 .unwrap_or(Duration::from_millis(1000));
1775 let mut on_output_last_fired: Option<std::time::Instant> = None;
1777
1778 let mut delay_timer =
1779 ready_delay.map(|secs| Box::pin(time::sleep(Duration::from_secs(secs))));
1780
1781 let mut http_exhausted = false;
1783 let mut cmd_exhausted = false;
1784 let mut port_exhausted = false;
1785 let mut output_exhausted = false;
1786
1787 let s = settings();
1789 let ready_check_interval = s.supervisor_ready_check_interval();
1790 let http_client_timeout = s.supervisor_http_client_timeout();
1791
1792 let mut output_deadline = ready_output
1794 .as_ref()
1795 .and_then(|o| o.timeout)
1796 .map(|d| Box::pin(time::sleep(d)));
1797
1798 let mut http_check_interval = ready_http
1800 .as_ref()
1801 .map(|_| tokio::time::interval(ready_check_interval));
1802 let mut http_deadline = ready_http
1803 .as_ref()
1804 .and_then(|h| h.timeout)
1805 .map(|d| Box::pin(time::sleep(d)));
1806 let http_client = if ready_http.is_some() {
1807 Some(crate::supervisor::health::supervisor_http_client().await)
1808 } else {
1809 None
1810 };
1811
1812 let mut port_check_interval =
1814 ready_port.map(|_| tokio::time::interval(ready_check_interval));
1815 let mut port_deadline = ready_port_config
1816 .as_ref()
1817 .and_then(|p| p.timeout)
1818 .map(|d| Box::pin(time::sleep(d)));
1819
1820 let mut cmd_probe: Option<CmdProbe> = None;
1823 let mut cmd_respawn_delay: Option<_> = None;
1824 let mut cmd_deadline = ready_cmd
1825 .as_ref()
1826 .and_then(|c| c.timeout)
1827 .map(|d| Box::pin(time::sleep(d)));
1828 if let Some(ref cmd) = ready_cmd {
1829 cmd_probe = Some(spawn_cmd_probe(
1830 &id,
1831 &cmd.run,
1832 daemon_dir.as_path(),
1833 hook_retry_count,
1834 readiness_daemon_env.as_ref(),
1835 &readiness_resolved_ports,
1836 ));
1837 }
1838
1839 let (exit_tx, mut exit_rx) =
1841 tokio::sync::mpsc::channel::<std::io::Result<std::process::ExitStatus>>(1);
1842
1843 let child_pid = child.id().unwrap_or(0);
1845 tokio::spawn(async move {
1846 let result = child.wait().await;
1847 #[cfg(all(unix, not(target_os = "linux")))]
1857 let result = match &result {
1858 Err(e) if e.raw_os_error() == Some(nix::libc::ECHILD) => {
1859 if let Some(code) = super::REAPED_STATUSES.lock().await.remove(&child_pid) {
1860 warn!(
1861 "daemon pid {child_pid} wait() got ECHILD; \
1862 recovered exit code {code} from zombie reaper"
1863 );
1864 use std::os::unix::process::ExitStatusExt;
1869 if code >= 0 {
1870 Ok(std::process::ExitStatus::from_raw(code << 8))
1871 } else {
1872 Ok(std::process::ExitStatus::from_raw((-code) & 0x7f))
1874 }
1875 } else {
1876 warn!(
1877 "daemon pid {child_pid} wait() got ECHILD but no \
1878 stashed status found; reporting as error"
1879 );
1880 result
1881 }
1882 }
1883 _ => result,
1884 };
1885 debug!("daemon pid {child_pid} wait() completed with result: {result:?}");
1886 let _ = exit_tx.send(result).await;
1887 });
1888
1889 #[allow(unused_assignments)]
1890 let mut exit_status = None;
1892
1893 if has_port_config
1899 && ready_pattern.is_none()
1900 && ready_http.is_none()
1901 && ready_port.is_none()
1902 && ready_cmd.is_none()
1903 && delay_timer.is_none()
1904 {
1905 active_port_spawned = true;
1906 detect_and_store_active_port(id.clone(), daemon_pid);
1907 }
1908
1909 let mut ready_fail_kill: Option<tokio::task::JoinHandle<()>> = None;
1916
1917 loop {
1918 select! {
1922 biased;
1923 Some(result) = exit_rx.recv() => {
1924 exit_status = Some(result);
1926 debug!("daemon {id} process exited, exit_status: {exit_status:?}");
1927 if !ready_notified {
1928 let is_success = exit_status.as_ref()
1930 .and_then(|r| r.as_ref().ok())
1931 .map(|s| s.success())
1932 .unwrap_or(false);
1933 if is_success && opts.oneshot {
1934 debug!("daemon {id} completed, deferring success notification until the completed state is persisted");
1935 oneshot_completion_pending = true;
1936 } else if let Some(tx) = ready_tx.take() {
1937 if is_success {
1938 debug!("daemon {id} exited successfully before ready check, sending success notification");
1939 let _ = tx.send(Ok(()));
1940 } else {
1941 let exit_code = exit_status.as_ref()
1942 .and_then(|r| r.as_ref().ok())
1943 .and_then(|s| s.code());
1944 debug!("daemon {id} exited with failure before ready check, sending failure notification with exit_code: {exit_code:?}");
1945 let _ = tx.send(Err(exit_code));
1946 }
1947 }
1948 } else {
1949 debug!("daemon {id} was already marked ready, not sending notification");
1950 }
1951 break;
1952 },
1953 Some(super::OutputLine { text: line, source }) = output_rx.recv() => {
1954 if matches!(source, super::OutputSource::Local) {
1958 let parsed = parse_line(&line);
1959 log_buffer.push(parsed);
1960 if log_buffer.len() >= LOG_BATCH_SIZE {
1961 let _ = flush_logs(&mut log_buffer);
1962 }
1963 }
1964 trace!("output: {id} {line}");
1965
1966 let line_clean = console::strip_ansi_codes(&line).to_string();
1969
1970 if !ready_notified
1972 && !output_exhausted
1973 && let Some(ref pattern) = ready_pattern
1974 && pattern.is_match(&line_clean)
1975 {
1976 if let Some(handle) = flush_logs(&mut log_buffer) {
1981 let _ = handle.await;
1982 }
1983 info!("daemon {id} ready: output matched pattern");
1984 ready_notified = true;
1985 if let Some(tx) = ready_tx.take() {
1986 let _ = tx.send(Ok(()));
1987 }
1988 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
1989 stop_cmd_probe_state(&mut cmd_probe);
1990 http_deadline = None;
1991 cmd_deadline = None;
1992 port_deadline = None;
1993 output_deadline = None;
1994 if !active_port_spawned && has_port_config {
1995 active_port_spawned = true;
1996 detect_and_store_active_port(id.clone(), daemon_pid);
1997 }
1998 }
1999
2000 if let Some(ref hook) = on_output_hook {
2005 let matched = match source {
2006 super::OutputSource::Sink { fires_hook } => fires_hook,
2007 super::OutputSource::Local => match (&hook.filter, &on_output_pattern) {
2008 (Some(substr), _) => line_clean.contains(substr.as_str()),
2009 (None, Some(re)) => re.is_match(&line_clean),
2010 (None, None) => true,
2011 },
2012 };
2013 if matched {
2014 let now = std::time::Instant::now();
2019 let elapsed = on_output_last_fired.map(|t| now.duration_since(t));
2020 if elapsed.is_none_or(|e| e >= on_output_debounce) {
2021 on_output_last_fired = Some(now);
2022 hooks::fire_output_hook(id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), hook.run.clone(), line_clean.clone()).await;
2023 }
2024 }
2025 }
2026 tokio::task::yield_now().await;
2029 }
2030 _ = async {
2031 if let Some(ref mut deadline) = http_deadline {
2032 deadline.await;
2033 } else {
2034 std::future::pending::<()>().await;
2035 }
2036 }, if !ready_notified && ready_http.is_some() => {
2037 http_exhausted = true;
2038 http_deadline = None;
2039 http_check_interval = None;
2040 warn!("daemon {id}: HTTP readiness check timed out");
2041 let any_remaining = any_ready_check_remaining(
2042 ready_output.as_ref(),
2043 output_exhausted,
2044 ready_port_config.as_ref(),
2045 port_exhausted,
2046 ready_http.as_ref(),
2047 http_exhausted,
2048 ready_cmd.as_ref(),
2049 cmd_exhausted,
2050 );
2051 if !any_remaining {
2052 error!("daemon {id}: all readiness checks exhausted, failing");
2053 stop_cmd_probe_state(&mut cmd_probe);
2054 ready_fail_kill = Some(spawn_ready_fail_kill(
2055 id.clone(),
2056 daemon_pid,
2057 opts.stop_signal.unwrap_or_default(),
2058 ));
2059 break;
2060 }
2061 }
2062 _ = async {
2063 if let Some(ref mut deadline) = output_deadline {
2064 deadline.await;
2065 } else {
2066 std::future::pending::<()>().await;
2067 }
2068 }, if !ready_notified && ready_output.is_some() => {
2069 output_exhausted = true;
2070 output_deadline = None;
2071 warn!("daemon {id}: output readiness check timed out");
2072 let any_remaining = any_ready_check_remaining(
2073 ready_output.as_ref(),
2074 output_exhausted,
2075 ready_port_config.as_ref(),
2076 port_exhausted,
2077 ready_http.as_ref(),
2078 http_exhausted,
2079 ready_cmd.as_ref(),
2080 cmd_exhausted,
2081 );
2082 if !any_remaining {
2083 error!("daemon {id}: all readiness checks exhausted, failing");
2084 stop_cmd_probe_state(&mut cmd_probe);
2085 ready_fail_kill = Some(spawn_ready_fail_kill(
2086 id.clone(),
2087 daemon_pid,
2088 opts.stop_signal.unwrap_or_default(),
2089 ));
2090 break;
2091 }
2092 }
2093 _ = async {
2094 if let Some(ref mut interval) = http_check_interval {
2095 interval.tick().await;
2096 } else {
2097 std::future::pending::<()>().await;
2098 }
2099 }, if !ready_notified && ready_http.is_some() && !http_exhausted => {
2100 if let (Some(http), Some(client)) = (&ready_http, &http_client) {
2101 match client.get(&http.url).timeout(http_client_timeout).send().await {
2102 Ok(response) if http.accepts_status(response.status().as_u16()) => {
2103 info!("daemon {id} ready: HTTP check passed (status {})", response.status());
2104 ready_notified = true;
2105 if let Some(tx) = ready_tx.take() {
2106 let _ = tx.send(Ok(()));
2107 }
2108 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2109 http_check_interval = None;
2110 http_deadline = None;
2111 stop_cmd_probe_state(&mut cmd_probe);
2112 cmd_deadline = None;
2113 port_deadline = None;
2114 output_deadline = None;
2115 if !active_port_spawned && has_port_config {
2116 active_port_spawned = true;
2117 detect_and_store_active_port(id.clone(), daemon_pid);
2118 }
2119 }
2120 Ok(response) => {
2121 trace!("daemon {id} HTTP check: status {} (not ready)", response.status());
2122 }
2123 Err(e) => {
2124 trace!("daemon {id} HTTP check failed: {e}");
2125 }
2126 }
2127 }
2128 }
2129 _ = async {
2130 if let Some(ref mut deadline) = port_deadline {
2131 deadline.await;
2132 } else {
2133 std::future::pending::<()>().await;
2134 }
2135 }, if !ready_notified && ready_port.is_some() => {
2136 port_exhausted = true;
2137 port_deadline = None;
2138 port_check_interval = None;
2139 warn!("daemon {id}: TCP port readiness check timed out");
2140 let any_remaining = any_ready_check_remaining(
2141 ready_output.as_ref(),
2142 output_exhausted,
2143 ready_port_config.as_ref(),
2144 port_exhausted,
2145 ready_http.as_ref(),
2146 http_exhausted,
2147 ready_cmd.as_ref(),
2148 cmd_exhausted,
2149 );
2150 if !any_remaining {
2151 error!("daemon {id}: all readiness checks exhausted, failing");
2152 stop_cmd_probe_state(&mut cmd_probe);
2153 ready_fail_kill = Some(spawn_ready_fail_kill(
2154 id.clone(),
2155 daemon_pid,
2156 opts.stop_signal.unwrap_or_default(),
2157 ));
2158 break;
2159 }
2160 }
2161 _ = async {
2162 if let Some(ref mut interval) = port_check_interval {
2163 interval.tick().await;
2164 } else {
2165 std::future::pending::<()>().await;
2166 }
2167 }, if !ready_notified && ready_port.is_some() && !port_exhausted => {
2168 if let Some(port) = ready_port {
2169 match tokio::net::TcpStream::connect(("127.0.0.1", port)).await {
2170 Ok(_) => {
2171 info!("daemon {id} ready: TCP port {port} is listening");
2172 ready_notified = true;
2173 if let Some(tx) = ready_tx.take() {
2174 let _ = tx.send(Ok(()));
2175 }
2176 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2177 port_check_interval = None;
2179 port_deadline = None;
2180 stop_cmd_probe_state(&mut cmd_probe);
2181 http_deadline = None;
2182 cmd_deadline = None;
2183 output_deadline = None;
2184 if !active_port_spawned && has_port_config {
2185 active_port_spawned = true;
2186 if let Some(active_port) = active_port_from_ready_port(
2196 port,
2197 &readiness_resolved_ports,
2198 ) {
2199 let mut state_file =
2200 SUPERVISOR.state_file.lock().await;
2201 if let Some(d) = state_file.daemons.get(&id)
2202 && d.pid == Some(daemon_pid)
2203 {
2204 state_file.set_active_port(&id, active_port);
2205 }
2206 } else {
2207 detect_and_store_active_port(
2208 id.clone(),
2209 daemon_pid,
2210 );
2211 }
2212 }
2213 }
2214 Err(_) => {
2215 trace!("daemon {id} port check: port {port} not listening yet");
2216 }
2217 }
2218 }
2219 }
2220 _ = async {
2221 if let Some(ref mut delay) = cmd_respawn_delay {
2222 delay.await;
2223 } else {
2224 std::future::pending::<()>().await;
2225 }
2226 }, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted && cmd_probe.is_none() => {
2227 if let Some(ref cmd) = ready_cmd {
2228 cmd_probe = Some(spawn_cmd_probe(
2229 &id,
2230 &cmd.run,
2231 daemon_dir.as_path(),
2232 hook_retry_count,
2233 readiness_daemon_env.as_ref(),
2234 &readiness_resolved_ports,
2235 ));
2236 }
2237 cmd_respawn_delay = None;
2238 }
2239 result = async {
2240 if let Some(probe) = cmd_probe.as_mut() {
2241 std::pin::Pin::new(&mut probe.result_rx).await
2242 } else {
2243 std::future::pending::<Result<Result<std::process::ExitStatus, std::io::Error>, tokio::sync::oneshot::error::RecvError>>().await
2244 }
2245 }, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted => {
2246 let _ = cmd_probe.take();
2250 match result {
2251 Ok(Ok(status)) if status.success() => {
2252 info!("daemon {id} ready: readiness command succeeded");
2253 ready_notified = true;
2254 if let Some(tx) = ready_tx.take() {
2255 let _ = tx.send(Ok(()));
2256 }
2257 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2258 cmd_respawn_delay = None;
2259 cmd_deadline = None;
2260 http_deadline = None;
2261 port_deadline = None;
2262 output_deadline = None;
2263 if !active_port_spawned && has_port_config {
2264 active_port_spawned = true;
2265 detect_and_store_active_port(id.clone(), daemon_pid);
2266 }
2267 }
2268 Ok(Ok(_)) | Ok(Err(_)) | Err(_) => {
2269 trace!("daemon {id} cmd check: command not ready, will respawn");
2270 cmd_respawn_delay = Some(Box::pin(time::sleep(ready_check_interval)));
2271 }
2272 }
2273 }
2274 _ = async {
2275 if let Some(ref mut deadline) = cmd_deadline {
2276 deadline.await;
2277 } else {
2278 std::future::pending::<()>().await;
2279 }
2280 }, if !ready_notified && ready_cmd.is_some() => {
2281 cmd_exhausted = true;
2282 cmd_deadline = None;
2283 stop_cmd_probe_state(&mut cmd_probe);
2284 cmd_respawn_delay = None;
2285 warn!("daemon {id}: command readiness check timed out");
2286 let any_remaining = any_ready_check_remaining(
2287 ready_output.as_ref(),
2288 output_exhausted,
2289 ready_port_config.as_ref(),
2290 port_exhausted,
2291 ready_http.as_ref(),
2292 http_exhausted,
2293 ready_cmd.as_ref(),
2294 cmd_exhausted,
2295 );
2296 if !any_remaining {
2297 error!("daemon {id}: all readiness checks exhausted, failing");
2298 ready_fail_kill = Some(spawn_ready_fail_kill(
2299 id.clone(),
2300 daemon_pid,
2301 opts.stop_signal.unwrap_or_default(),
2302 ));
2303 break;
2304 }
2305 }
2306 _ = async {
2307 if let Some(ref mut timer) = delay_timer {
2308 timer.await;
2309 } else {
2310 std::future::pending::<()>().await;
2311 }
2312 } => {
2313 let has_other_ready_check = ready_pattern.is_some()
2314 || ready_http.is_some()
2315 || ready_port.is_some()
2316 || ready_cmd.is_some();
2317 let delay_is_only_readiness = !ready_notified && !has_other_ready_check;
2318 let process_exited = exit_status.is_some();
2319 let process_running = if delay_is_only_readiness && !process_exited {
2320 PROCS.refresh_pids(&[daemon_pid]);
2323 PROCS.is_running(daemon_pid)
2324 } else {
2325 false
2326 };
2327
2328 if delay_readiness_succeeded(
2329 ready_notified,
2330 has_other_ready_check,
2331 process_exited,
2332 process_running,
2333 ) {
2334 info!("daemon {id} ready: delay elapsed");
2335 ready_notified = true;
2336 if let Some(tx) = ready_tx.take() {
2337 let _ = tx.send(Ok(()));
2338 }
2339 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2340 if !active_port_spawned && has_port_config {
2341 active_port_spawned = true;
2342 detect_and_store_active_port(id.clone(), daemon_pid);
2343 }
2344 } else if delay_is_only_readiness {
2345 if process_exited {
2346 debug!("daemon {id} exited during ready_delay, not marking as ready");
2347 } else {
2348 debug!("daemon {id} pid {daemon_pid} not running during ready_delay, deferring to exit handler");
2349 }
2350 }
2351
2352 if delay_is_only_readiness {
2353 output_deadline = None;
2356 http_deadline = None;
2357 cmd_deadline = None;
2358 port_deadline = None;
2359 stop_cmd_probe_state(&mut cmd_probe);
2360 }
2361 delay_timer = None;
2363 }
2364 _ = log_flush_interval.tick() => {
2365 let _ = flush_logs(&mut log_buffer);
2366 }
2367 }
2368 }
2369
2370 let pre_drain_daemon = SUPERVISOR.get_daemon(&id).await;
2384 let pre_drain_is_stopping = pre_drain_daemon
2385 .as_ref()
2386 .is_some_and(|d| d.status.is_stopped() || d.status.is_stopping_or_restarting());
2387
2388 drop(output_relay);
2401 let drain_deadline = tokio::time::Instant::now() + super::EXIT_OUTPUT_DRAIN_TIMEOUT;
2402 loop {
2403 let now = tokio::time::Instant::now();
2404 if now >= drain_deadline {
2405 break;
2406 }
2407 let Ok(Some(line)) =
2408 tokio::time::timeout(drain_deadline - now, output_rx.recv()).await
2409 else {
2410 break;
2411 };
2412 if matches!(line.source, super::OutputSource::Local) {
2414 log_buffer.push(parse_line(&line.text));
2415 }
2416 }
2417 if let Some(handle) = flush_logs(&mut log_buffer) {
2420 let _ = handle.await;
2421 }
2422
2423 {
2425 let mut state_file = SUPERVISOR.state_file.lock().await;
2426 state_file.clear_active_port(&id);
2427 }
2428
2429 let exit_status = if let Some(status) = exit_status {
2431 status
2432 } else {
2433 match exit_rx.recv().await {
2435 Some(status) => status,
2436 None => {
2437 warn!("daemon {id} exit channel closed without receiving status");
2438 Err(std::io::Error::other("exit channel closed"))
2439 }
2440 }
2441 };
2442
2443 if let Some(kill) = ready_fail_kill {
2448 let _ = kill.await;
2449 if let Some(tx) = ready_tx.take() {
2450 let _ = tx.send(Err(Some(124)));
2451 }
2452 }
2453
2454 let current_daemon = SUPERVISOR.get_daemon(&id).await;
2455
2456 SUPERVISOR
2461 .active_monitors
2462 .fetch_add(1, atomic::Ordering::Release);
2463 struct MonitorGuard;
2464 impl Drop for MonitorGuard {
2465 fn drop(&mut self) {
2466 SUPERVISOR
2467 .active_monitors
2468 .fetch_sub(1, atomic::Ordering::Release);
2469 SUPERVISOR.monitor_done.notify_waiters();
2470 }
2471 }
2472 let _monitor_guard = MonitorGuard;
2473 if !pre_drain_is_stopping
2478 && (current_daemon.is_none()
2479 || current_daemon.as_ref().is_some_and(|d| {
2480 d.pid != Some(pid)
2481 && !d.status.is_stopped()
2482 && !d.status.is_stopping_or_restarting()
2483 }))
2484 {
2485 if oneshot_completion_pending && let Some(tx) = ready_tx.take() {
2489 let _ = tx.send(Ok(()));
2490 }
2491 return;
2492 }
2493 let already_stopped = current_daemon
2498 .as_ref()
2499 .is_some_and(|d| d.status.is_stopped());
2500 let is_stopping = already_stopped
2501 || pre_drain_is_stopping
2502 || current_daemon
2503 .as_ref()
2504 .is_some_and(|d| d.status.is_stopping_or_restarting());
2505
2506 let (exit_code, exit_reason) = match (&exit_status, is_stopping) {
2508 (Ok(status), true) => {
2509 (status.code().unwrap_or(-1), "stop")
2513 }
2514 (Ok(status), false) if status.success() => (status.code().unwrap_or(-1), "exit"),
2515 (Ok(status), false) => (status.code().unwrap_or(-1), "fail"),
2516 (Err(_), true) => {
2517 (-1, "stop")
2519 }
2520 (Err(_), false) => (-1, "fail"),
2521 };
2522 if !already_stopped && !pre_drain_is_stopping {
2534 if let Ok(status) = &exit_status {
2535 info!("daemon {id} exited with status {status}");
2536 }
2537 let (new_status, last_exit_success) = terminal_exit_state(
2538 exit_reason,
2539 opts.oneshot,
2540 exit_code,
2541 exit_status.as_ref().map(|s| s.success()).unwrap_or(true),
2542 );
2543 if !SUPERVISOR
2549 .finalize_monitored_exit(
2550 &id,
2551 pid,
2552 monitor_token,
2553 new_status,
2554 Some(last_exit_success),
2555 )
2556 .await
2557 {
2558 debug!("daemon {id} exit state was not written; a successor owns the record");
2559 }
2560 }
2561
2562 if oneshot_completion_pending && let Some(tx) = ready_tx.take() {
2567 if exit_reason == "exit" {
2568 let _ = tx.send(Ok(()));
2569 } else {
2570 warn!("daemon {id}: oneshot was stopped before completing");
2571 let _ = tx.send(Err(None));
2572 }
2573 }
2574
2575 let hook_extra_env = vec![
2577 ("PITCHFORK_EXIT_CODE".to_string(), exit_code.to_string()),
2578 ("PITCHFORK_EXIT_REASON".to_string(), exit_reason.to_string()),
2579 ];
2580
2581 let hooks_to_fire: Vec<HookType> = match exit_reason {
2583 "stop" => vec![HookType::OnStop, HookType::OnExit],
2584 "exit" => vec![HookType::OnExit],
2585 _ if hook_retry_count >= hook_retry.count() => {
2587 vec![HookType::OnFail, HookType::OnExit]
2588 }
2589 _ => vec![],
2590 };
2591
2592 for hook_type in hooks_to_fire {
2593 fire_hook(
2594 hook_type,
2595 id.clone(),
2596 hook_dirs.clone(),
2597 hook_retry_count,
2598 hook_daemon_env.clone(),
2599 hook_resolved_ports.clone(),
2600 hook_extra_env.clone(),
2601 )
2602 .await;
2603 }
2604 });
2605
2606 if let Some(ready_rx) = ready_rx {
2608 match ready_rx.await {
2609 Ok(Ok(())) => {
2610 info!("daemon {id} is ready");
2611 let daemon = match self.get_daemon(id).await {
2621 Some(current) if current.pid.is_none() || current.pid == Some(pid) => {
2622 current
2623 }
2624 _ if opts.oneshot => crate::daemon::Daemon {
2631 status: DaemonStatus::Completed,
2632 pid: None,
2633 start_time: None,
2634 boot_time: None,
2635 last_exit_success: Some(true),
2636 ..daemon
2637 },
2638 _ => daemon,
2639 };
2640 Ok(IpcResponse::DaemonReady { daemon })
2641 }
2642 Ok(Err(exit_code)) => {
2643 error!("daemon {id} failed before becoming ready");
2644 let last_attempt = opts.retry_count >= opts.retry.count();
2655 if using_sink && last_attempt {
2656 super::log_sink::wait_for_output(id, spawn_time, SINK_OUTPUT_TIMEOUT).await;
2657 }
2658 Ok(IpcResponse::DaemonFailedWithCode {
2659 exit_code,
2660 resolved_ports: attempt_resolved_ports,
2661 })
2662 }
2663 Err(_) => {
2664 error!("readiness channel closed unexpectedly for daemon {id}");
2665 Ok(IpcResponse::DaemonStart { daemon })
2666 }
2667 }
2668 } else {
2669 Ok(IpcResponse::DaemonStart { daemon })
2670 }
2671 }
2672
2673 pub async fn stop(&self, id: &DaemonId) -> Result<IpcResponse> {
2675 let lock = self.stop_lock(id).await;
2679 let _guard = lock.lock().await;
2680 self.stop_locked(id).await
2681 }
2682
2683 pub(crate) async fn stop_for_restart(&self, id: &DaemonId) -> Result<IpcResponse> {
2690 let lock = self.stop_lock(id).await;
2691 let _guard = lock.lock().await;
2692 self.stop_locked_with(id, true).await
2693 }
2694
2695 pub(super) async fn stop_locked(&self, id: &DaemonId) -> Result<IpcResponse> {
2697 self.stop_locked_with(id, false).await
2698 }
2699
2700 pub(super) async fn stop_locked_with(
2707 &self,
2708 id: &DaemonId,
2709 restarting: bool,
2710 ) -> Result<IpcResponse> {
2711 let (stopping_status, stopped_status) = if restarting {
2712 (DaemonStatus::Restarting, DaemonStatus::Restarting)
2713 } else {
2714 (DaemonStatus::Stopping, DaemonStatus::Stopped)
2715 };
2716 let pitchfork_id = DaemonId::pitchfork();
2717 if *id == pitchfork_id {
2718 return Ok(IpcResponse::Error(
2719 "Cannot stop supervisor via stop command".into(),
2720 ));
2721 }
2722 info!("stopping daemon: {id}");
2723 self.cancel_retrying(id);
2728 let _stop_epoch_bump = StopEpochGuard(id.clone());
2736 if let Some(daemon) = self.get_daemon(id).await {
2737 trace!("daemon to stop: {daemon}");
2738 if let Some(pid) = daemon.pid {
2739 trace!("killing pid: {pid}");
2740 if PROCS.is_running(pid) {
2741 if !super::signalling_pid_is_authorized(
2747 daemon.start_time,
2748 PROCS.start_time(pid),
2749 ) {
2750 warn!(
2751 "pid {pid} recorded for daemon {id} belongs to another process now; not signalling it"
2752 );
2753 self.upsert_daemon(
2754 UpsertDaemonOpts::builder(id.clone())
2755 .set(|o| {
2756 o.pid = None;
2757 o.status = stopped_status.clone();
2758 })
2759 .build(),
2760 )
2761 .await?;
2762 return Ok(IpcResponse::DaemonWasNotRunning);
2763 }
2764
2765 self.upsert_daemon(
2767 UpsertDaemonOpts::builder(id.clone())
2768 .set(|o| {
2769 o.pid = Some(pid);
2770 o.status = stopping_status.clone();
2771 })
2772 .build(),
2773 )
2774 .await?;
2775
2776 let stop_cfg = daemon.stop_signal.unwrap_or_default();
2779 let stop_signal: i32 = stop_cfg.signal.into();
2780 if let Err(e) = PROCS
2781 .kill_process_group_async(pid, stop_signal, stop_cfg.timeout)
2782 .await
2783 {
2784 debug!("failed to kill pid {pid}: {e}");
2785 if PROCS.process_group_alive(pid) {
2791 debug!(
2793 "failed to stop pid {pid}: process group still alive after kill"
2794 );
2795 self.upsert_daemon(
2796 UpsertDaemonOpts::builder(id.clone())
2797 .set(|o| {
2798 o.pid = Some(pid); o.status = DaemonStatus::Running;
2800 })
2801 .build(),
2802 )
2803 .await?;
2804 return Ok(IpcResponse::DaemonStopFailed {
2805 error: format!(
2806 "process group of {pid} still alive after kill attempt: {e}"
2807 ),
2808 });
2809 }
2810 #[cfg(windows)]
2815 {
2816 self.upsert_daemon(
2817 UpsertDaemonOpts::builder(id.clone())
2818 .set(|o| {
2819 o.pid = None;
2820 o.status = stopped_status.clone();
2821 o.last_exit_success = Some(true);
2822 })
2823 .build(),
2824 )
2825 .await?;
2826 return Ok(IpcResponse::DaemonStopFailed {
2827 error: format!("{e}"),
2828 });
2829 }
2830 }
2831
2832 self.upsert_daemon(
2840 UpsertDaemonOpts::builder(id.clone())
2841 .set(|o| {
2842 o.pid = None;
2843 o.status = stopped_status.clone();
2844 o.last_exit_success = Some(true);
2845 })
2846 .build(),
2847 )
2848 .await?;
2849 } else if daemon.oneshot && self.is_monitored(id, pid) {
2850 debug!(
2870 "pid {pid} not running but daemon {id} is still monitored; waiting for its monitor to settle the outcome"
2871 );
2872 self.wait_for_exit_finalized(id, Some(pid)).await;
2873 let finished = self.get_daemon(id).await;
2874 if finished
2875 .as_ref()
2876 .is_some_and(|d| stop_keeps_finalized_status(&d.status))
2877 {
2878 return Ok(IpcResponse::DaemonWasNotRunning);
2879 }
2880 self.upsert_daemon(
2884 UpsertDaemonOpts::builder(id.clone())
2885 .set(|o| {
2886 o.pid = None;
2887 o.status = stopped_status.clone();
2888 })
2889 .build(),
2890 )
2891 .await?;
2892 return Ok(IpcResponse::DaemonWasNotRunning);
2893 } else {
2894 debug!("pid {pid} not running, process may have exited unexpectedly");
2895 self.upsert_daemon(
2902 UpsertDaemonOpts::builder(id.clone())
2903 .set(|o| {
2904 o.pid = None;
2905 o.status = stopped_status.clone();
2906 })
2907 .build(),
2908 )
2909 .await?;
2910 return Ok(IpcResponse::DaemonWasNotRunning);
2911 }
2912 Ok(IpcResponse::Ok)
2913 } else {
2914 debug!("daemon {id} not running");
2915 if !restarting && daemon.status.is_restarting() {
2920 self.upsert_daemon(
2921 UpsertDaemonOpts::builder(id.clone())
2922 .set(|o| {
2923 o.pid = None;
2924 o.status = DaemonStatus::Stopped;
2925 })
2926 .build(),
2927 )
2928 .await?;
2929 return Ok(IpcResponse::Ok);
2930 }
2931 if daemon.status.is_errored() && daemon.retry_count < daemon.retry.count() {
2936 self.upsert_daemon(
2937 UpsertDaemonOpts::builder(id.clone())
2938 .set(|o| {
2939 o.pid = None;
2940 o.status = stopped_status.clone();
2941 })
2942 .build(),
2943 )
2944 .await?;
2945 return Ok(IpcResponse::DaemonWasNotRunning);
2946 }
2947 Ok(IpcResponse::DaemonNotRunning)
2948 }
2949 } else {
2950 debug!("daemon {id} not found");
2951 Ok(IpcResponse::DaemonNotFound)
2952 }
2953 }
2954}
2955
2956#[cfg(unix)]
2957fn resolve_effective_run_identity(daemon_user: Option<&str>) -> Result<RunIdentity> {
2958 let s = settings();
2959 let settings_user = s.supervisor.user.trim();
2960 let daemon_user = daemon_user.map(str::trim).filter(|user| !user.is_empty());
2961 let settings_user = (!settings_user.is_empty()).then_some(settings_user);
2962 let configured = daemon_user.or(settings_user);
2963 let current_uid = nix::unistd::Uid::effective().as_raw();
2964 let current_gid = nix::unistd::Gid::effective().as_raw();
2965 let invoking = env::invoking_user_ids().map(|(uid, gid)| (uid.to_string(), gid.to_string()));
2968 resolve_run_identity(
2969 configured,
2970 current_uid,
2971 current_gid,
2972 invoking.as_ref().map(|(uid, _)| uid.as_str()),
2973 invoking.as_ref().map(|(_, gid)| gid.as_str()),
2974 )
2975}
2976
2977#[cfg(unix)]
2978fn resolve_run_identity(
2979 configured: Option<&str>,
2980 current_uid: u32,
2981 current_gid: u32,
2982 sudo_uid: Option<&str>,
2983 sudo_gid: Option<&str>,
2984) -> Result<RunIdentity> {
2985 let current_uid = nix::unistd::Uid::from_raw(current_uid);
2986 let current_gid = nix::unistd::Gid::from_raw(current_gid);
2987 if let Some(user) = configured {
2988 let identity = resolve_configured_user(user)?;
2989 ensure_can_use_identity(user, &identity, current_uid, current_gid)?;
2990 if identity.matches(current_uid, current_gid) {
2991 return Ok(RunIdentity::Inherit);
2992 }
2993 return Ok(identity);
2994 }
2995
2996 if current_uid.is_root()
2997 && let Some(identity) = resolve_sudo_identity(sudo_uid, sudo_gid)
2998 {
2999 if identity.matches(current_uid, current_gid) {
3000 return Ok(RunIdentity::Inherit);
3001 }
3002 return Ok(identity);
3003 }
3004
3005 Ok(RunIdentity::Inherit)
3006}
3007
3008#[cfg(unix)]
3009fn resolve_configured_user(user: &str) -> Result<RunIdentity> {
3010 if user.chars().all(|c| c.is_ascii_digit()) {
3011 let uid = user
3012 .parse::<u32>()
3013 .map_err(|e| miette::miette!("invalid run user UID '{}': {}", user, e))?;
3014 let user_record = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
3015 .into_diagnostic()?
3016 .ok_or_else(|| miette::miette!("run user UID '{}' does not exist", user))?;
3017 return run_identity_from_user_record(user_record);
3018 }
3019
3020 let user_record = nix::unistd::User::from_name(user)
3021 .into_diagnostic()?
3022 .ok_or_else(|| miette::miette!("run user '{}' does not exist", user))?;
3023 run_identity_from_user_record(user_record)
3024}
3025
3026#[cfg(unix)]
3027fn run_identity_from_user_record(user: nix::unistd::User) -> Result<RunIdentity> {
3028 let username = CString::new(user.name)
3029 .map_err(|e| miette::miette!("run user name contains an interior nul byte: {}", e))?;
3030 Ok(RunIdentity::Switch {
3031 uid: user.uid,
3032 gid: user.gid,
3033 username: Some(username),
3034 home: Some(user.dir),
3035 })
3036}
3037
3038#[cfg(unix)]
3039fn resolve_sudo_identity(sudo_uid: Option<&str>, sudo_gid: Option<&str>) -> Option<RunIdentity> {
3040 let uid = sudo_uid?.parse::<u32>().ok()?;
3041 let gid = sudo_gid?.parse::<u32>().ok()?;
3042 let user = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
3043 .ok()
3044 .flatten();
3045 let (username, home) = match user {
3046 Some(user) => (CString::new(user.name).ok(), Some(user.dir)),
3047 None => (None, None),
3048 };
3049 Some(RunIdentity::Switch {
3050 uid: nix::unistd::Uid::from_raw(uid),
3051 gid: nix::unistd::Gid::from_raw(gid),
3052 username,
3053 home,
3054 })
3055}
3056
3057#[cfg(unix)]
3058fn ensure_can_use_identity(
3059 configured_user: &str,
3060 identity: &RunIdentity,
3061 current_uid: nix::unistd::Uid,
3062 current_gid: nix::unistd::Gid,
3063) -> Result<()> {
3064 let RunIdentity::Switch { uid, gid, .. } = identity else {
3065 return Ok(());
3066 };
3067 if *uid == current_uid && *gid == current_gid {
3068 return Ok(());
3069 }
3070 if current_uid.is_root() {
3071 return Ok(());
3072 }
3073 Err(miette::miette!(
3074 "daemon is configured to run as '{}', but the supervisor is running as uid={} gid={}. Restart the supervisor with sudo to switch to uid={} gid={}, or choose a user matching the supervisor.",
3075 configured_user,
3076 current_uid.as_raw(),
3077 current_gid.as_raw(),
3078 uid.as_raw(),
3079 gid.as_raw()
3080 ))
3081}
3082
3083#[cfg(unix)]
3090fn apply_identity_env(command: &mut tokio::process::Command, identity: &RunIdentity) {
3091 let RunIdentity::Switch { username, home, .. } = identity else {
3092 return;
3093 };
3094 match home.as_ref().filter(|home| !home.as_os_str().is_empty()) {
3095 Some(home) => command.env("HOME", home),
3096 None => command.env_remove("HOME"),
3097 };
3098 match username.as_ref().and_then(|name| name.to_str().ok()) {
3099 Some(name) => command.env("USER", name).env("LOGNAME", name),
3100 None => command.env_remove("USER").env_remove("LOGNAME"),
3101 };
3102}
3103
3104#[cfg(unix)]
3105fn apply_run_identity(identity: &RunIdentity) -> std::io::Result<()> {
3106 let RunIdentity::Switch {
3107 uid, gid, username, ..
3108 } = identity
3109 else {
3110 return Ok(());
3111 };
3112 if let Some(username) = username {
3113 initgroups_for_user(username, *gid)?;
3114 } else {
3115 setgroups_to_primary(*gid)?;
3116 }
3117 nix::unistd::setgid(*gid).map_err(nix_to_io_error)?;
3118 nix::unistd::setuid(*uid).map_err(nix_to_io_error)?;
3119 Ok(())
3120}
3121
3122#[cfg(unix)]
3123impl RunIdentity {
3124 fn matches(&self, uid: nix::unistd::Uid, gid: nix::unistd::Gid) -> bool {
3125 matches!(self, RunIdentity::Switch { uid: u, gid: g, .. } if *u == uid && *g == gid)
3126 }
3127}
3128
3129#[cfg(unix)]
3130fn setgroups_to_primary(gid: nix::unistd::Gid) -> std::io::Result<()> {
3131 let groups = [gid.as_raw() as libc::gid_t];
3132 #[cfg(any(target_os = "linux", target_os = "android"))]
3133 let group_count = groups.len();
3134 #[cfg(not(any(target_os = "linux", target_os = "android")))]
3135 let group_count = groups.len() as libc::c_int;
3136 let rc = unsafe { libc::setgroups(group_count, groups.as_ptr()) };
3137 if rc == -1 {
3138 Err(std::io::Error::last_os_error())
3139 } else {
3140 Ok(())
3141 }
3142}
3143
3144#[cfg(unix)]
3145fn initgroups_for_user(username: &CString, gid: nix::unistd::Gid) -> std::io::Result<()> {
3146 let gid = gid.as_raw();
3147 #[cfg(any(
3148 target_os = "macos",
3149 target_os = "ios",
3150 target_os = "tvos",
3151 target_os = "watchos"
3152 ))]
3153 let base_gid = i32::try_from(gid)
3154 .map_err(|_| std::io::Error::other(format!("gid {gid} is out of range")))?;
3155
3156 #[cfg(not(any(
3157 target_os = "macos",
3158 target_os = "ios",
3159 target_os = "tvos",
3160 target_os = "watchos"
3161 )))]
3162 let base_gid = gid as libc::gid_t;
3163
3164 let rc = unsafe { libc::initgroups(username.as_ptr(), base_gid) };
3167 if rc == -1 {
3168 Err(std::io::Error::last_os_error())
3169 } else {
3170 Ok(())
3171 }
3172}
3173
3174#[cfg(unix)]
3175fn nix_to_io_error(err: nix::errno::Errno) -> std::io::Error {
3176 std::io::Error::from_raw_os_error(err as i32)
3177}
3178
3179async fn check_ports_available(
3186 expected_ports: &[u16],
3187 auto_bump: bool,
3188 max_attempts: u32,
3189) -> Result<Vec<u16>> {
3190 if expected_ports.is_empty() {
3191 return Ok(Vec::new());
3192 }
3193
3194 for bump_offset in 0..=max_attempts {
3195 let candidate_ports: Vec<u16> = expected_ports
3197 .iter()
3198 .map(|&p| p.wrapping_add(bump_offset as u16))
3199 .collect();
3200
3201 let mut all_available = true;
3203 let mut conflicting_port = None;
3204
3205 for &port in &candidate_ports {
3206 if port == 0 {
3209 continue;
3210 }
3211
3212 if let Some(address) = port_bind_conflict(port).await {
3226 all_available = false;
3227 conflicting_port = Some((port, address));
3228 break;
3229 }
3230 }
3231
3232 if all_available {
3233 if candidate_ports.contains(&0) && !expected_ports.contains(&0) {
3237 return Err(PortError::NoAvailablePort {
3238 start_port: expected_ports[0],
3239 attempts: bump_offset + 1,
3240 }
3241 .into());
3242 }
3243 if bump_offset > 0 {
3244 info!("ports {expected_ports:?} bumped by {bump_offset} to {candidate_ports:?}");
3245 }
3246 return Ok(candidate_ports);
3247 }
3248
3249 if bump_offset == 0
3251 && !auto_bump
3252 && let Some((port, address)) = conflicting_port
3253 {
3254 let (pid, process) = identify_port_owner(port, address).await;
3255 return Err(PortError::InUse {
3256 port,
3257 address: Some(shown_address(address)),
3258 process,
3259 pid,
3260 }
3261 .into());
3262 }
3263 }
3264
3265 Err(PortError::NoAvailablePort {
3267 start_port: expected_ports[0],
3268 attempts: max_attempts + 1,
3269 }
3270 .into())
3271}
3272
3273async fn port_bind_conflict(port: u16) -> Option<std::net::IpAddr> {
3279 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
3280 tokio::task::spawn_blocking(move || {
3281 for addr in [
3282 IpAddr::V4(Ipv4Addr::UNSPECIFIED),
3283 IpAddr::V4(Ipv4Addr::LOCALHOST),
3284 IpAddr::V6(Ipv6Addr::LOCALHOST),
3285 ] {
3286 match bind_probe((addr, port).into()) {
3287 Ok(socket) => drop(socket),
3288 Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => return Some(addr),
3289 Err(_) => continue,
3290 }
3291 }
3292 None
3293 })
3294 .await
3295 .unwrap_or(None)
3296}
3297
3298#[cfg(unix)]
3309fn bind_probe(addr: std::net::SocketAddr) -> std::io::Result<tokio::net::TcpSocket> {
3310 let socket = if addr.is_ipv4() {
3311 tokio::net::TcpSocket::new_v4()?
3312 } else {
3313 tokio::net::TcpSocket::new_v6()?
3314 };
3315 socket.set_reuseaddr(true)?;
3316 socket.bind(addr)?;
3317 Ok(socket)
3318}
3319
3320#[cfg(not(unix))]
3326fn bind_probe(addr: std::net::SocketAddr) -> std::io::Result<std::net::TcpListener> {
3327 std::net::TcpListener::bind(addr)
3328}
3329
3330fn shown_address(addr: std::net::IpAddr) -> String {
3332 match addr {
3333 std::net::IpAddr::V4(v4) => v4.to_string(),
3334 std::net::IpAddr::V6(v6) => format!("[{v6}]"),
3335 }
3336}
3337
3338fn listener_match(listening: std::net::IpAddr, conflict: std::net::IpAddr) -> Option<u8> {
3345 use std::net::IpAddr;
3346 let listening = listening.to_canonical();
3347 if listening == conflict {
3348 return Some(0);
3349 }
3350 match (listening, conflict) {
3351 (IpAddr::V4(_), IpAddr::V4(_)) | (IpAddr::V6(_), IpAddr::V6(_))
3352 if listening.is_unspecified() || conflict.is_unspecified() =>
3353 {
3354 Some(1)
3355 }
3356 (IpAddr::V6(v6), IpAddr::V4(_)) if v6.is_unspecified() => Some(2),
3357 _ => None,
3358 }
3359}
3360
3361struct TcpSocket {
3363 addr: std::net::SocketAddr,
3364 listening: bool,
3365 pid: u32,
3366 process: String,
3367}
3368
3369fn pick_port_owner(
3379 sockets: impl IntoIterator<Item = TcpSocket>,
3380 port: u16,
3381 conflict: std::net::IpAddr,
3382) -> Option<(u32, String)> {
3383 sockets
3384 .into_iter()
3385 .filter(|s| s.addr.port() == port)
3386 .filter_map(|s| {
3387 let matched = listener_match(s.addr.ip(), conflict)?;
3388 let rank = (matched == 2, !s.listening, matched);
3389 Some((rank, s.pid, s.process))
3390 })
3391 .min_by_key(|(rank, _, _)| *rank)
3392 .map(|(_, pid, process)| (pid, process))
3393}
3394
3395async fn identify_port_owner(port: u16, conflict: std::net::IpAddr) -> (u32, String) {
3405 tokio::task::spawn_blocking(move || {
3406 listeners::get_all()
3407 .ok()
3408 .and_then(|list| {
3409 let tcp = list
3412 .into_iter()
3413 .filter(|l| l.protocol == listeners::Protocol::TCP)
3414 .map(|l| TcpSocket {
3415 addr: l.socket,
3416 listening: l.state == listeners::SocketState::Listen,
3417 pid: l.process.pid,
3418 process: l.process.name,
3419 });
3420 pick_port_owner(tcp, port, conflict)
3421 })
3422 .unwrap_or((0, "unknown".to_string()))
3423 })
3424 .await
3425 .unwrap_or((0, "unknown".to_string()))
3426}
3427
3428async fn detect_port_conflict(port: u16) -> Option<(String, u32, String)> {
3433 let address = port_bind_conflict(port).await?;
3434 let (pid, process) = identify_port_owner(port, address).await;
3435 Some((shown_address(address), pid, process))
3436}
3437
3438#[derive(Debug, PartialEq, Eq)]
3439enum ActivePortSelection {
3440 NoCandidates,
3441 Selected(u16),
3442 Ambiguous(Vec<u16>),
3443}
3444
3445fn discovery_preferred_port(daemon: &crate::daemon::Daemon) -> Option<u16> {
3446 daemon
3447 .resolved_port
3448 .first()
3449 .copied()
3450 .or_else(|| {
3451 daemon
3452 .port
3453 .as_ref()
3454 .and_then(|port| port.expect.first().copied())
3455 })
3456 .filter(|&port| port > 0)
3457}
3458
3459fn select_active_port(
3460 listeners: impl IntoIterator<Item = listeners::Listener>,
3461 descendant_pids: &std::collections::HashSet<u32>,
3462 preferred_port: Option<u16>,
3463) -> ActivePortSelection {
3464 let process_ports: std::collections::BTreeSet<u16> = listeners
3465 .into_iter()
3466 .filter(|listener| {
3467 listener.protocol == listeners::Protocol::TCP
3468 && listener.state == listeners::SocketState::Listen
3469 && descendant_pids.contains(&listener.process.pid)
3470 })
3471 .map(|listener| listener.socket.port())
3472 .filter(|&port| port > 0)
3473 .collect();
3474
3475 if let Some(port) = preferred_port
3476 && process_ports.contains(&port)
3477 {
3478 return ActivePortSelection::Selected(port);
3479 }
3480
3481 match process_ports.len() {
3482 0 => ActivePortSelection::NoCandidates,
3483 1 => ActivePortSelection::Selected(*process_ports.first().unwrap()),
3484 _ => ActivePortSelection::Ambiguous(process_ports.into_iter().collect()),
3485 }
3486}
3487
3488fn detect_and_store_active_port(id: DaemonId, pid: u32) {
3499 tokio::spawn(async move {
3500 for delay_ms in [500u64, 1000, 2000, 4000] {
3504 tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
3505
3506 let preferred_port: Option<u16> = {
3509 let state_file = SUPERVISOR.state_file.lock().await;
3510 match state_file.daemons.get(&id) {
3511 Some(d) if d.pid.is_none() => {
3512 debug!("daemon {id}: aborting active_port detection — process exited");
3513 return;
3514 }
3515 Some(d) => discovery_preferred_port(d),
3516 None => None,
3517 }
3518 };
3519
3520 let selection = tokio::task::spawn_blocking(move || {
3521 let listeners = listeners::get_all().ok()?;
3522
3523 PROCS.refresh_processes();
3525
3526 let descendant_pids: std::collections::HashSet<u32> = PROCS
3527 .all_children(pid)
3528 .into_iter()
3529 .chain(std::iter::once(pid))
3530 .collect();
3531
3532 Some(select_active_port(
3533 listeners,
3534 &descendant_pids,
3535 preferred_port,
3536 ))
3537 })
3538 .await
3539 .ok()
3540 .flatten()
3541 .unwrap_or(ActivePortSelection::NoCandidates);
3542
3543 let port = match selection {
3544 ActivePortSelection::Selected(port) => port,
3545 ActivePortSelection::Ambiguous(ports) => {
3546 debug!(
3547 "daemon {id}: ambiguous active_port candidates {ports:?} for pid {pid} \
3548 and its descendants; leaving active_port unset (will retry)"
3549 );
3550 continue;
3551 }
3552 ActivePortSelection::NoCandidates => {
3553 debug!(
3554 "daemon {id}: no active port detected for pid {pid} or its descendants \
3555 (will retry)"
3556 );
3557 continue;
3558 }
3559 };
3560
3561 debug!("daemon {id} active_port detected: {port}");
3562 let mut state_file = SUPERVISOR.state_file.lock().await;
3563 if let Some(d) = state_file.daemons.get(&id) {
3564 if d.pid == Some(pid) {
3568 state_file.set_active_port(&id, port);
3569 } else {
3570 debug!(
3571 "daemon {id}: skipping active_port write — PID mismatch \
3572 (expected {pid}, current {:?})",
3573 d.pid
3574 );
3575 }
3576 }
3577 return;
3578 }
3579
3580 debug!(
3581 "daemon {id}: active port detection exhausted all retries for pid {pid} and its descendants"
3582 );
3583 });
3584}
3585
3586#[cfg(test)]
3587mod port_conflict_tests {
3588 use super::{
3589 TcpSocket, check_ports_available, listener_match, pick_port_owner, port_bind_conflict,
3590 shown_address,
3591 };
3592 use crate::error::PortError;
3593 use std::net::{IpAddr, SocketAddr};
3594
3595 static FORKS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
3598
3599 #[tokio::test]
3600 async fn a_taken_port_is_reported_with_its_address_and_holder() {
3601 let _forks = FORKS.lock().await;
3602 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3603 let port = listener.local_addr().unwrap().port();
3604
3605 let address = shown_address(port_bind_conflict(port).await.unwrap());
3608 assert!(
3609 ["0.0.0.0", "127.0.0.1"].contains(&address.as_str()),
3610 "{address}"
3611 );
3612
3613 let err = check_ports_available(&[port], false, 0).await.unwrap_err();
3614 match err.downcast_ref::<PortError>() {
3615 Some(PortError::InUse {
3616 port: p,
3617 address: Some(a),
3618 pid,
3619 ..
3620 }) => {
3621 assert_eq!(*p, port);
3622 assert_eq!(*a, address);
3623 assert_eq!(*pid, std::process::id());
3625 }
3626 other => panic!("unexpected error: {other:?}"),
3627 }
3628 drop(listener);
3629 assert_eq!(port_bind_conflict(port).await, None);
3630 }
3631
3632 #[cfg(unix)]
3633 #[test]
3634 fn a_copy_of_a_probe_socket_does_not_look_like_a_listener() {
3635 use super::bind_probe;
3636 let copy = bind_probe(SocketAddr::from(([0, 0, 0, 0], 0))).unwrap();
3639 let port = copy.local_addr().unwrap().port();
3640 let addr = SocketAddr::from(([127, 0, 0, 1], port));
3641 bind_probe(addr).unwrap();
3642 let timeout = std::time::Duration::from_millis(200);
3645 assert!(std::net::TcpStream::connect_timeout(&addr, timeout).is_err());
3646 drop(copy);
3647 }
3648
3649 #[cfg(target_os = "linux")]
3658 #[tokio::test]
3659 async fn a_free_port_stays_free_while_another_thread_forks() {
3660 use crate::inherited_fds::CloseInheritedFds;
3661 use std::sync::Arc;
3662 use std::sync::atomic::{AtomicBool, Ordering};
3663
3664 let _forks = FORKS.lock().await;
3665 let port = std::net::TcpListener::bind("127.0.0.1:0")
3666 .unwrap()
3667 .local_addr()
3668 .unwrap()
3669 .port();
3670 let stop = Arc::new(AtomicBool::new(false));
3671 let forker = std::thread::spawn({
3672 let stop = stop.clone();
3673 move || {
3674 while !stop.load(Ordering::Relaxed) {
3675 std::process::Command::new("true")
3678 .close_inherited_fds()
3679 .status()
3680 .unwrap();
3681 }
3682 }
3683 });
3684 let mut conflicts = Vec::new();
3685 for _ in 0..500 {
3686 conflicts.extend(port_bind_conflict(port).await);
3687 }
3688 stop.store(true, Ordering::Relaxed);
3689 forker.join().unwrap();
3690 assert!(
3691 conflicts.is_empty(),
3692 "free port looked taken on {conflicts:?}"
3693 );
3694 }
3695
3696 fn ip(s: &str) -> IpAddr {
3697 s.parse().unwrap()
3698 }
3699
3700 fn socket(addr: &str, listening: bool, pid: u32) -> TcpSocket {
3701 TcpSocket {
3702 addr: addr.parse::<SocketAddr>().unwrap(),
3703 listening,
3704 pid,
3705 process: format!("p{pid}"),
3706 }
3707 }
3708
3709 #[test]
3710 fn only_a_listener_whose_address_conflicts_is_named() {
3711 let all = || {
3712 [
3713 socket("192.0.2.1:3000", true, 1),
3714 socket("127.0.0.1:3000", true, 2),
3715 socket("[::1]:3000", true, 3),
3716 socket("127.0.0.1:4000", true, 4),
3717 ]
3718 };
3719 assert_eq!(
3721 pick_port_owner(all(), 3000, ip("127.0.0.1")),
3722 Some((2, "p2".into()))
3723 );
3724 assert_eq!(
3725 pick_port_owner(all(), 3000, ip("::1")),
3726 Some((3, "p3".into()))
3727 );
3728 let v4 = pick_port_owner(all(), 3000, ip("0.0.0.0")).unwrap().0;
3730 assert!([1, 2].contains(&v4));
3731 assert_eq!(
3733 pick_port_owner([socket("[::1]:3000", true, 3)], 3000, ip("127.0.0.1")),
3734 None
3735 );
3736 assert_eq!(pick_port_owner(all(), 5000, ip("127.0.0.1")), None);
3737
3738 let both = [
3741 socket("127.0.0.1:3000", false, 5),
3742 socket("0.0.0.0:3000", true, 6),
3743 ];
3744 assert_eq!(
3745 pick_port_owner(both, 3000, ip("127.0.0.1")),
3746 Some((6, "p6".into()))
3747 );
3748 assert_eq!(
3749 pick_port_owner([socket("127.0.0.1:3000", false, 5)], 3000, ip("127.0.0.1")),
3750 Some((5, "p5".into()))
3751 );
3752
3753 let v6_wildcard = || {
3756 [
3757 socket("[::]:3000", true, 7),
3758 socket("127.0.0.1:3000", false, 8),
3759 ]
3760 };
3761 assert_eq!(
3762 pick_port_owner(v6_wildcard(), 3000, ip("127.0.0.1")),
3763 Some((8, "p8".into()))
3764 );
3765 assert_eq!(
3766 pick_port_owner(v6_wildcard(), 3000, ip("0.0.0.0")),
3767 Some((8, "p8".into()))
3768 );
3769 assert_eq!(
3771 pick_port_owner([socket("[::]:3000", true, 7)], 3000, ip("127.0.0.1")),
3772 Some((7, "p7".into()))
3773 );
3774 assert_eq!(
3776 pick_port_owner(
3777 [socket("[::ffff:127.0.0.1]:3000", false, 9)],
3778 3000,
3779 ip("127.0.0.1")
3780 ),
3781 Some((9, "p9".into()))
3782 );
3783
3784 assert_eq!(listener_match(ip("0.0.0.0"), ip("127.0.0.1")), Some(1));
3785 assert_eq!(listener_match(ip("::"), ip("127.0.0.1")), Some(2));
3786 assert_eq!(listener_match(ip("::1"), ip("127.0.0.1")), None);
3787 assert_eq!(listener_match(ip("192.0.2.1"), ip("127.0.0.1")), None);
3788 assert_eq!(shown_address(ip("::1")), "[::1]");
3789 }
3790}
3791
3792#[cfg(test)]
3793mod active_port_tests {
3794 use super::*;
3795 use crate::config_types::PortConfig;
3796 use listeners::{Listener, Process, Protocol, SocketState};
3797 use std::net::{IpAddr, Ipv4Addr, SocketAddr};
3798
3799 fn listener(pid: u32, port: u16, protocol: Protocol, state: SocketState) -> Listener {
3800 Listener {
3801 process: Process {
3802 pid,
3803 name: "test".to_string(),
3804 path: "/test".to_string(),
3805 },
3806 socket: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
3807 protocol,
3808 state,
3809 }
3810 }
3811
3812 #[test]
3813 fn active_port_candidates_exclude_outbound_tcp_and_udp_sockets() {
3814 let daemon_pid = 100;
3815 let child_pid = 101;
3816 let descendant_pids = [daemon_pid, child_pid].into_iter().collect();
3817 let listeners = vec![
3818 listener(child_pid, 3004, Protocol::TCP, SocketState::Listen),
3819 listener(daemon_pid, 47082, Protocol::TCP, SocketState::Established),
3820 listener(daemon_pid, 5353, Protocol::UDP, SocketState::Unknown),
3821 listener(999, 9000, Protocol::TCP, SocketState::Listen),
3822 ];
3823
3824 assert_eq!(
3825 select_active_port(listeners, &descendant_pids, None),
3826 ActivePortSelection::Selected(3004)
3827 );
3828 }
3829
3830 #[test]
3831 fn bumped_cmd_readiness_prefers_resolved_primary_port() {
3832 let daemon = crate::daemon::Daemon {
3833 resolved_port: vec![3004],
3834 port: Some(PortConfig {
3835 expect: vec![3000],
3836 ..PortConfig::default()
3837 }),
3838 ..crate::daemon::Daemon::default()
3839 };
3840 let descendant_pids = [100].into_iter().collect();
3841 let listeners = vec![
3842 listener(100, 9000, Protocol::TCP, SocketState::Listen),
3843 listener(100, 3004, Protocol::TCP, SocketState::Listen),
3844 ];
3845
3846 assert_eq!(discovery_preferred_port(&daemon), Some(3004));
3847 assert_eq!(
3848 select_active_port(
3849 listeners,
3850 &descendant_pids,
3851 discovery_preferred_port(&daemon),
3852 ),
3853 ActivePortSelection::Selected(3004)
3854 );
3855 }
3856
3857 #[test]
3858 fn legacy_state_uses_expected_primary_port_for_discovery() {
3859 let daemon = crate::daemon::Daemon {
3860 port: Some(PortConfig {
3861 expect: vec![3000],
3862 ..PortConfig::default()
3863 }),
3864 ..crate::daemon::Daemon::default()
3865 };
3866
3867 assert_eq!(discovery_preferred_port(&daemon), Some(3000));
3868 }
3869
3870 #[test]
3871 fn ambiguous_candidates_leave_active_port_unset() {
3872 let descendant_pids = [100].into_iter().collect();
3873 let listeners = vec![
3874 listener(100, 9000, Protocol::TCP, SocketState::Listen),
3875 listener(100, 3000, Protocol::TCP, SocketState::Listen),
3876 ];
3877
3878 assert_eq!(
3879 select_active_port(listeners, &descendant_pids, None),
3880 ActivePortSelection::Ambiguous(vec![3000, 9000])
3881 );
3882 }
3883
3884 #[test]
3885 fn bumped_ready_port_sets_only_the_resolved_primary_without_scanning() {
3886 assert_eq!(active_port_from_ready_port(3004, &[3004]), Some(3004));
3887 assert_eq!(active_port_from_ready_port(4003, &[3003, 4003]), None);
3888 }
3889
3890 #[test]
3891 fn delay_readiness_requires_delay_only_and_a_running_process() {
3892 assert!(delay_readiness_succeeded(false, false, false, true));
3893 assert!(!delay_readiness_succeeded(false, true, false, true));
3894 assert!(!delay_readiness_succeeded(false, false, true, false));
3895 assert!(!delay_readiness_succeeded(false, false, false, false));
3896 assert!(!delay_readiness_succeeded(true, false, false, true));
3897 }
3898}
3899
3900fn is_daemon_slug_target(id: &DaemonId) -> bool {
3908 let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
3912 slugs.iter().any(|(slug, entry)| {
3913 let daemon_name = entry.daemon.as_deref().unwrap_or(slug);
3914 id.name() == daemon_name
3915 })
3916}
3917
3918#[cfg(test)]
3919mod oneshot_tests {
3920 use super::*;
3921
3922 #[test]
3923 fn oneshot_clean_exit_is_completed() {
3924 let (status, success) = terminal_exit_state("exit", true, 0, true);
3925 assert!(matches!(status, DaemonStatus::Completed));
3926 assert!(success);
3927 }
3928
3929 #[test]
3930 fn service_clean_exit_is_still_stopped() {
3931 let (status, success) = terminal_exit_state("exit", false, 0, true);
3932 assert!(matches!(status, DaemonStatus::Stopped));
3933 assert!(success);
3934 }
3935
3936 #[test]
3937 fn oneshot_failure_is_errored_so_retry_applies() {
3938 let (status, success) = terminal_exit_state("fail", true, 3, false);
3941 assert!(matches!(status, DaemonStatus::Errored(3)));
3942 assert!(!success);
3943 }
3944
3945 #[test]
3946 fn a_stop_cancels_the_retry_sequence_it_finds() {
3947 let id = DaemonId::new("retry-cancel-test", "task");
3948 let claim = SUPERVISOR.mark_retrying(&id);
3949 assert!(!claim.is_cancelled());
3950 assert!(SUPERVISOR.is_retrying(&id));
3951 SUPERVISOR.cancel_retrying(&id);
3952 assert!(claim.is_cancelled());
3953 drop(claim);
3954 assert!(!SUPERVISOR.is_retrying(&id));
3955 }
3956
3957 #[test]
3958 fn a_stop_cancels_every_sequence_for_the_daemon() {
3959 let id = DaemonId::new("retry-cancel-test", "concurrent");
3963 let first = SUPERVISOR.mark_retrying(&id);
3964 let second = SUPERVISOR.mark_retrying(&id);
3965 SUPERVISOR.cancel_retrying(&id);
3966 assert!(first.is_cancelled());
3967 assert!(second.is_cancelled());
3968 drop(second);
3969 assert!(SUPERVISOR.is_retrying(&id));
3971 drop(first);
3972 assert!(!SUPERVISOR.is_retrying(&id));
3973 }
3974
3975 #[test]
3976 fn a_stop_invalidates_an_attempt_decided_on_before_it() {
3977 let id = DaemonId::new("stop-epoch-test", "task");
3981 let approved_at = SUPERVISOR.stop_epoch(&id);
3982 assert_eq!(SUPERVISOR.stop_epoch(&id), approved_at);
3983 SUPERVISOR.bump_stop_epoch(&id);
3984 assert_ne!(SUPERVISOR.stop_epoch(&id), approved_at);
3985 let approved_after = SUPERVISOR.stop_epoch(&id);
3987 assert_eq!(SUPERVISOR.stop_epoch(&id), approved_after);
3988 }
3989
3990 #[test]
3991 fn stop_epochs_are_tracked_per_daemon() {
3992 let stopped = DaemonId::new("stop-epoch-test", "stopped");
3993 let untouched = DaemonId::new("stop-epoch-test", "untouched");
3994 let approved_at = SUPERVISOR.stop_epoch(&untouched);
3995 SUPERVISOR.bump_stop_epoch(&stopped);
3996 assert_eq!(SUPERVISOR.stop_epoch(&untouched), approved_at);
3997 }
3998
3999 #[test]
4000 fn a_stop_leaves_a_completed_task_alone() {
4001 assert!(stop_keeps_finalized_status(&DaemonStatus::Completed));
4003 }
4004
4005 #[test]
4006 fn a_stop_replaces_a_failure_so_retries_do_not_resume() {
4007 assert!(!stop_keeps_finalized_status(&DaemonStatus::Errored(1)));
4010 assert!(!stop_keeps_finalized_status(&DaemonStatus::Running));
4011 assert!(!stop_keeps_finalized_status(&DaemonStatus::Stopped));
4012 }
4013
4014 #[test]
4015 fn stopped_oneshot_did_not_complete() {
4016 let (status, _) = terminal_exit_state("stop", true, 0, true);
4017 assert!(matches!(status, DaemonStatus::Stopped));
4018 }
4019}
4020
4021#[cfg(all(test, unix))]
4022mod tests {
4023 use super::*;
4024
4025 #[test]
4026 fn test_resolve_run_identity_empty_without_sudo() {
4027 let identity = resolve_run_identity(None, 501, 20, None, None).unwrap();
4028 assert_eq!(identity, RunIdentity::Inherit);
4029 }
4030
4031 #[test]
4032 fn test_resolve_run_identity_sudo_fallback() {
4033 let identity = resolve_run_identity(None, 0, 0, Some("501"), Some("20")).unwrap();
4034 let RunIdentity::Switch { uid, gid, .. } = identity else {
4035 panic!("expected identity switch");
4036 };
4037 assert_eq!(uid.as_raw(), 501);
4038 assert_eq!(gid.as_raw(), 20);
4039 }
4040
4041 #[test]
4042 fn test_resolve_run_identity_ignores_stale_sudo_when_not_root() {
4043 let identity = resolve_run_identity(None, 501, 20, Some("0"), Some("0")).unwrap();
4044 assert_eq!(identity, RunIdentity::Inherit);
4045 }
4046
4047 #[test]
4048 fn test_resolve_configured_user_root_name() {
4049 let identity = resolve_configured_user("root").unwrap();
4050 let RunIdentity::Switch { uid, username, .. } = identity else {
4051 panic!("expected identity switch");
4052 };
4053 assert_eq!(uid.as_raw(), 0);
4054 assert_eq!(
4055 username.as_deref().and_then(|s| s.to_str().ok()),
4056 Some("root")
4057 );
4058 }
4059
4060 #[test]
4061 fn test_resolve_configured_user_root_uid() {
4062 let identity = resolve_configured_user("0").unwrap();
4063 let RunIdentity::Switch { uid, username, .. } = identity else {
4064 panic!("expected identity switch");
4065 };
4066 assert_eq!(uid.as_raw(), 0);
4067 assert_eq!(
4068 username.as_deref().and_then(|s| s.to_str().ok()),
4069 Some("root")
4070 );
4071 }
4072
4073 #[test]
4074 fn test_resolve_configured_user_missing_user_fails() {
4075 let err = resolve_configured_user("pitchfork-user-that-should-not-exist")
4076 .unwrap_err()
4077 .to_string();
4078 assert!(err.contains("does not exist"));
4079 }
4080
4081 #[test]
4082 fn test_resolve_run_identity_requires_root_for_user_switch() {
4083 let err = resolve_run_identity(Some("root"), 501, 20, None, None)
4084 .unwrap_err()
4085 .to_string();
4086 assert!(err.contains("Restart the supervisor with sudo"));
4087 }
4088
4089 #[test]
4090 fn test_resolve_run_identity_same_user_is_noop() {
4091 let identity = resolve_run_identity(Some("root"), 0, 0, Some("501"), Some("20")).unwrap();
4092 assert_eq!(identity, RunIdentity::Inherit);
4093 }
4094
4095 #[test]
4096 fn test_resolve_configured_user_records_home() {
4097 let identity = resolve_configured_user("root").unwrap();
4098 let RunIdentity::Switch { home, .. } = identity else {
4099 panic!("expected identity switch");
4100 };
4101 let expected = nix::unistd::User::from_name("root").unwrap().unwrap().dir;
4102 assert_eq!(home, Some(expected));
4103 }
4104
4105 fn switch_to(name: Option<&str>, home: Option<&str>) -> RunIdentity {
4106 RunIdentity::Switch {
4107 uid: nix::unistd::Uid::from_raw(501),
4108 gid: nix::unistd::Gid::from_raw(20),
4109 username: name.map(|n| CString::new(n).unwrap()),
4110 home: home.map(std::path::PathBuf::from),
4111 }
4112 }
4113
4114 fn command_env(
4117 command: &tokio::process::Command,
4118 key: &str,
4119 ) -> Option<Option<std::ffi::OsString>> {
4120 command
4121 .as_std()
4122 .get_envs()
4123 .find(|(k, _)| *k == key)
4124 .map(|(_, v)| v.map(ToOwned::to_owned))
4125 }
4126
4127 fn daemon_command(
4129 identity: &RunIdentity,
4130 daemon_env: Option<&IndexMap<String, String>>,
4131 ) -> tokio::process::Command {
4132 let mut command = tokio::process::Command::new("true");
4133 apply_identity_env(&mut command, identity);
4134 apply_runtime_env(
4135 &mut command,
4136 &DaemonId::new("identity-env-test", "api"),
4137 0,
4138 daemon_env,
4139 &[],
4140 );
4141 command
4142 }
4143
4144 #[test]
4145 fn test_identity_env_describes_the_switched_user() {
4146 let command = daemon_command(&switch_to(Some("alice"), Some("/home/alice")), None);
4147 assert_eq!(
4148 command_env(&command, "HOME"),
4149 Some(Some("/home/alice".into()))
4150 );
4151 assert_eq!(command_env(&command, "USER"), Some(Some("alice".into())));
4152 assert_eq!(command_env(&command, "LOGNAME"), Some(Some("alice".into())));
4153 }
4154
4155 #[test]
4156 fn test_identity_env_leaves_inherited_env_alone() {
4157 let command = daemon_command(&RunIdentity::Inherit, None);
4158 assert_eq!(command_env(&command, "HOME"), None);
4159 assert_eq!(command_env(&command, "USER"), None);
4160 assert_eq!(command_env(&command, "LOGNAME"), None);
4161 }
4162
4163 #[test]
4164 fn test_root_sudo_to_root_preserves_environment() {
4165 let identity = resolve_run_identity(None, 0, 0, Some("0"), Some("0")).unwrap();
4166 assert_eq!(identity, RunIdentity::Inherit);
4167 let command = daemon_command(&identity, None);
4168 for key in ["HOME", "USER", "LOGNAME"] {
4169 assert_eq!(command_env(&command, key), None);
4170 }
4171 }
4172
4173 #[test]
4174 fn test_daemon_env_overrides_identity_env() {
4175 let mut env = IndexMap::new();
4176 env.insert("HOME".to_string(), "/srv/app".to_string());
4177 env.insert("USER".to_string(), "app".to_string());
4178 let command = daemon_command(&switch_to(Some("alice"), Some("/home/alice")), Some(&env));
4179 assert_eq!(command_env(&command, "HOME"), Some(Some("/srv/app".into())));
4180 assert_eq!(command_env(&command, "USER"), Some(Some("app".into())));
4181 assert_eq!(command_env(&command, "LOGNAME"), Some(Some("alice".into())));
4182 }
4183
4184 #[test]
4185 fn test_identity_env_drops_values_without_a_passwd_entry() {
4186 let command = daemon_command(&switch_to(None, None), None);
4189 assert_eq!(command_env(&command, "HOME"), Some(None));
4190 assert_eq!(command_env(&command, "USER"), Some(None));
4191 assert_eq!(command_env(&command, "LOGNAME"), Some(None));
4192 }
4193
4194 #[test]
4195 fn test_daemon_env_restores_values_without_a_passwd_entry() {
4196 let mut env = IndexMap::new();
4197 env.insert("HOME".to_string(), "/srv/app".to_string());
4198 let command = daemon_command(&switch_to(None, None), Some(&env));
4199 assert_eq!(command_env(&command, "HOME"), Some(Some("/srv/app".into())));
4200 }
4201}
4202
4203fn inject_proxy_env(cmd: &mut tokio::process::Command, host: &Option<String>) {
4212 let s = crate::settings::settings();
4213 let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
4214
4215 if s.proxy.enable && host.is_some() && !lan_enabled {
4216 cmd.env("HOST", "127.0.0.1");
4219 }
4220
4221 if let Some(url) = build_pitchfork_url(host, &s) {
4223 cmd.env("PITCHFORK_URL", &url);
4224 }
4225
4226 if s.proxy.enable && s.proxy.https {
4232 let ca_path = if s.proxy.tls_cert.is_empty() {
4233 crate::env::PITCHFORK_STATE_DIR.join("proxy").join("ca.pem")
4234 } else {
4235 std::path::PathBuf::from(&s.proxy.tls_cert)
4236 };
4237 if ca_path.exists() {
4238 let ca_path = ca_path.to_string_lossy().to_string();
4239 cmd.env("PITCHFORK_CA_FILE", &ca_path);
4240 cmd.env("NODE_EXTRA_CA_CERTS", &ca_path);
4241 }
4242 }
4243
4244 if s.proxy.enable {
4246 let tld = if lan_enabled { "local" } else { &s.proxy.tld };
4247 cmd.env("__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS", format!(".{tld}"));
4248 }
4249
4250 if lan_enabled {
4252 cmd.env("PITCHFORK_LAN", "1");
4253 }
4254}
4255
4256async fn daemon_proxy_host(opts: &RunOptions) -> Option<String> {
4262 if !crate::settings::settings().proxy.enable {
4265 return None;
4266 }
4267 if let Some(slug) = opts.slug.as_deref()
4271 && crate::proxy::hostname::hostname_fits(slug)
4272 {
4273 return opts.slug.clone();
4274 }
4275 let config_dir = opts
4278 .watch_base_dir
4279 .clone()
4280 .unwrap_or_else(|| opts.dir.0.clone());
4281 let id = opts.id.clone();
4282 tokio::task::spawn_blocking(move || {
4288 let pt = crate::pitchfork_toml::PitchforkToml::all_merged_from(&config_dir).ok()?;
4289 let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
4290 crate::proxy::hostname::host_for_daemon(&id, pt.daemons.get(&id), &slugs)
4291 })
4292 .await
4293 .unwrap_or_default()
4294}
4295
4296fn build_pitchfork_url(host: &Option<String>, s: &crate::settings::Settings) -> Option<String> {
4300 crate::proxy::build_proxy_url(host.as_deref(), s)
4301}
4302
4303#[cfg(test)]
4304mod ready_check_tests {
4305 use super::*;
4306 use std::time::Duration;
4307
4308 #[test]
4309 fn any_ready_check_remaining_prefers_unbounded_checks() {
4310 let http = ReadyHttp::new("http://localhost/health");
4311 let cmd = ReadyCmd::new("true");
4312
4313 assert!(any_ready_check_remaining(
4314 None,
4315 false,
4316 None,
4317 false,
4318 Some(&http),
4319 false,
4320 None,
4321 false
4322 ));
4323 assert!(any_ready_check_remaining(
4324 None,
4325 false,
4326 None,
4327 false,
4328 None,
4329 false,
4330 Some(&cmd),
4331 false
4332 ));
4333 assert!(any_ready_check_remaining(
4334 None,
4335 false,
4336 Some(&ReadyPort::new(8080)),
4337 false,
4338 Some(&http),
4339 true,
4340 Some(&cmd),
4341 true
4342 ));
4343 }
4344
4345 #[test]
4346 fn any_ready_check_remaining_exhausted_timed_checks() {
4347 let http = ReadyHttp {
4348 url: "http://localhost/health".to_string(),
4349 status: vec![],
4350 timeout: Some(Duration::from_secs(5)),
4351 };
4352 let cmd = ReadyCmd {
4353 run: "true".into(),
4354 timeout: Some(Duration::from_secs(5)),
4355 };
4356
4357 assert!(any_ready_check_remaining(
4358 None,
4359 false,
4360 None,
4361 false,
4362 Some(&http),
4363 false,
4364 Some(&cmd),
4365 false
4366 ));
4367 assert!(!any_ready_check_remaining(
4368 None,
4369 false,
4370 None,
4371 false,
4372 Some(&http),
4373 true,
4374 Some(&cmd),
4375 true
4376 ));
4377 }
4378
4379 #[tokio::test]
4380 async fn spawn_cmd_probe_reports_success() {
4381 let id = DaemonId::new("global", "probe-test");
4382 let probe = spawn_cmd_probe(&id, &"true".into(), &std::env::temp_dir(), 0, None, &[]);
4383 let status = probe.result_rx.await.unwrap().unwrap();
4384 assert!(status.success());
4385 }
4386
4387 #[cfg(unix)]
4391 #[tokio::test]
4392 async fn spawn_cmd_probe_runs_an_argv_without_a_shell() {
4393 let id = DaemonId::new("global", "probe-test");
4394 let argv = |arg: &str| -> RunCommand {
4395 RunCommand::Argv(
4396 ["test", arg, "=", "a b $HOME %PATH% &"]
4397 .map(str::to_string)
4398 .to_vec(),
4399 )
4400 };
4401 let probe = spawn_cmd_probe(
4402 &id,
4403 &argv("a b $HOME %PATH% &"),
4404 &std::env::temp_dir(),
4405 0,
4406 None,
4407 &[],
4408 );
4409 assert!(probe.result_rx.await.unwrap().unwrap().success());
4410 let probe = spawn_cmd_probe(
4412 &id,
4413 &"test a b $HOME %PATH% & = 'a b $HOME %PATH% &'".into(),
4414 &std::env::temp_dir(),
4415 0,
4416 None,
4417 &[],
4418 );
4419 assert!(!probe.result_rx.await.unwrap().unwrap().success());
4420 let probe = spawn_cmd_probe(&id, &argv("different"), &std::env::temp_dir(), 0, None, &[]);
4421 assert!(!probe.result_rx.await.unwrap().unwrap().success());
4422 }
4423
4424 #[tokio::test]
4425 async fn spawn_cmd_probe_stops_on_request() {
4426 let id = DaemonId::new("global", "probe-test");
4427 let probe = spawn_cmd_probe(&id, &"sleep 30".into(), &std::env::temp_dir(), 0, None, &[]);
4428 let CmdProbe {
4429 cancel_tx,
4430 result_rx,
4431 } = probe;
4432 let _ = cancel_tx.send(());
4433 let status = result_rx.await.unwrap().unwrap();
4434 assert!(!status.success());
4435 }
4436
4437 #[tokio::test]
4438 async fn spawn_cmd_probe_receives_daemon_and_resolved_port_environment() {
4439 let id = DaemonId::new("worktree", "api");
4440 let daemon_env = IndexMap::from([("CUSTOM_VALUE".to_string(), "yes".to_string())]);
4441 let check = if cfg!(windows) {
4444 r#"(if "%CUSTOM_VALUE%"=="yes" if "%PORT%"=="4100" if "%PORT0%"=="4100" if "%PORT1%"=="5100" if "%PITCHFORK_DAEMON_ID%"=="worktree/api" if "%PITCHFORK_RETRY_COUNT%"=="2" exit 0) & exit 1"#
4445 } else {
4446 r#"test "$CUSTOM_VALUE" = yes && test "$PORT" = 4100 && test "$PORT0" = 4100 && test "$PORT1" = 5100 && test "$PITCHFORK_DAEMON_ID" = worktree/api && test "$PITCHFORK_RETRY_COUNT" = 2"#
4447 };
4448 let probe = spawn_cmd_probe(
4449 &id,
4450 &check.into(),
4451 &std::env::temp_dir(),
4452 2,
4453 Some(&daemon_env),
4454 &[4100, 5100],
4455 );
4456 let status = probe.result_rx.await.unwrap().unwrap();
4457 assert!(status.success());
4458 }
4459
4460 #[test]
4461 fn configured_ready_port_follows_expected_port_bump() {
4462 assert_eq!(resolve_configured_ready_port(3000, &[3000], &[3004]), 3004);
4463 assert_eq!(
4464 resolve_configured_ready_port(4000, &[3000, 4000], &[3003, 4003]),
4465 4003
4466 );
4467 assert_eq!(resolve_configured_ready_port(8080, &[3000], &[3004]), 8080);
4468 }
4469}
4470
4471#[cfg(test)]
4472mod launch_command_tests {
4473 use super::{invalid_argv_program, launch_command};
4474 use crate::daemon_id::DaemonId;
4475
4476 #[test]
4477 fn refuses_an_argv_whose_program_rendered_empty_or_to_exec() {
4478 let id = DaemonId::new("proj", "api");
4479 assert!(invalid_argv_program(&id, &[]).is_some());
4480 assert!(invalid_argv_program(&id, &words(&["", "server.js"])).is_some());
4481 assert!(invalid_argv_program(&id, &words(&["exec", "node"])).is_some());
4482 assert_eq!(invalid_argv_program(&id, &words(&["node", ""])), None);
4483 }
4484
4485 #[test]
4486 fn refuses_a_probe_array_whose_program_rendered_empty_or_to_exec() {
4487 use super::invalid_probe_program;
4488 use crate::pitchfork_toml::RunCommand;
4489 let id = DaemonId::new("proj", "api");
4490 for field in ["ready_cmd", "health_cmd"] {
4491 let check =
4492 |run: Vec<String>| invalid_probe_program(&id, field, Some(&RunCommand::Argv(run)));
4493 assert!(check(vec![]).unwrap().contains(field));
4494 assert!(check(words(&["", "-h"])).is_some());
4495 assert!(check(words(&["exec", "pg_isready"])).is_some());
4496 assert_eq!(check(words(&["pg_isready", ""])), None);
4497 }
4498 assert_eq!(
4500 invalid_probe_program(&id, "health_cmd", Some(&RunCommand::Shell(String::new()))),
4501 None
4502 );
4503 assert_eq!(invalid_probe_program(&id, "health_cmd", None), None);
4504 }
4505
4506 fn words(words: &[&str]) -> Vec<String> {
4507 words.iter().map(|w| w.to_string()).collect()
4508 }
4509
4510 #[test]
4511 fn windows_rejects_only_enabled_unsupported_options() {
4512 let mut opts = crate::daemon::RunOptions::default();
4513 assert_eq!(super::unsupported_windows_options(&opts, ""), None);
4514 opts.pty = Some(false);
4515 opts.user = Some(" \t".into());
4516 assert_eq!(super::unsupported_windows_options(&opts, " \t"), None);
4517 opts.pty = Some(true);
4518 assert!(
4519 super::unsupported_windows_options(&opts, "")
4520 .unwrap()
4521 .contains("pty = true")
4522 );
4523 opts.pty = Some(false);
4524 opts.user = Some("postgres".into());
4525 assert!(
4526 super::unsupported_windows_options(&opts, "")
4527 .unwrap()
4528 .contains("user switching")
4529 );
4530 opts.user = None;
4531 assert!(
4532 super::unsupported_windows_options(&opts, "postgres")
4533 .unwrap()
4534 .contains("settings.supervisor.user")
4535 );
4536 }
4537
4538 #[test]
4539 fn starts_the_first_word_with_the_rest_as_arguments() {
4540 let argv = words(&["node", "my server.js", "--name=\"a b\"", "&", "%PATH%"]);
4541 assert_eq!(
4542 launch_command(argv, None),
4543 (
4544 "node".to_string(),
4545 words(&["my server.js", "--name=\"a b\"", "&", "%PATH%"])
4546 )
4547 );
4548 }
4549
4550 #[test]
4551 fn mise_receives_every_word_after_the_separator() {
4552 let argv = words(&["node", "my server.js", "'single'"]);
4553 let mise = std::path::Path::new("/opt/mise/bin/mise");
4554 let (program, args) = launch_command(argv, Some(mise));
4555 assert_eq!(program, mise.to_string_lossy());
4556 assert_eq!(
4557 args,
4558 words(&["x", "--", "node", "my server.js", "'single'"])
4559 );
4560 }
4561}
4562
4563#[cfg(all(test, windows))]
4564mod windows_retry_tests {
4565 use super::*;
4566 use crate::config_types::{Dir, Retry};
4567 use crate::settings::reload_settings;
4568 use std::process::Stdio;
4569 use tokio::io::AsyncBufReadExt;
4570
4571 #[tokio::test]
4572 async fn forced_retry_claim_revalidates_settings_before_stopping_a_live_instance() {
4573 const CHILD_ENV: &str = "PITCHFORK_TEST_WINDOWS_RETRY_CLAIM";
4574 const CHILD_SENTINEL: &str = "windows-retry-claim-child-ran";
4575 if std::env::var_os(CHILD_ENV).is_none() {
4576 let temp = tempfile::tempdir().unwrap();
4579 std::fs::create_dir(temp.path().join("config")).unwrap();
4580 std::fs::write(
4581 temp.path().join("pitchfork.toml"),
4582 "[settings.supervisor]\nuser = ''\n",
4583 )
4584 .unwrap();
4585 let mut command = tokio::process::Command::new(std::env::current_exe().unwrap());
4586 for (name, _) in std::env::vars_os() {
4587 if name
4588 .to_string_lossy()
4589 .to_ascii_uppercase()
4590 .starts_with("PITCHFORK_")
4591 {
4592 command.env_remove(name);
4593 }
4594 }
4595 command
4596 .args([
4597 "--exact",
4598 "supervisor::lifecycle::windows_retry_tests::forced_retry_claim_revalidates_settings_before_stopping_a_live_instance",
4599 "--nocapture",
4600 ])
4601 .current_dir(temp.path())
4602 .env(CHILD_ENV, "1")
4603 .env("PITCHFORK_CONFIG_DIR", temp.path().join("config"))
4604 .env("PITCHFORK_STATE_DIR", temp.path().join("state"))
4605 .env("PITCHFORK_LOGS_DIR", temp.path().join("logs"))
4606 .env("PITCHFORK_BOOT_EXECUTABLE", temp.path().join("missing.exe"))
4607 .hide_console_window()
4608 .kill_on_drop(true);
4609 let output = time::timeout(Duration::from_secs(30), command.output())
4610 .await
4611 .expect("isolated retry claim test timed out")
4612 .unwrap();
4613 assert!(
4614 output.status.success(),
4615 "isolated retry claim test failed:\nstdout:\n{}\nstderr:\n{}",
4616 String::from_utf8_lossy(&output.stdout),
4617 String::from_utf8_lossy(&output.stderr)
4618 );
4619 assert!(String::from_utf8_lossy(&output.stderr).contains(CHILD_SENTINEL));
4620 return;
4621 }
4622 eprintln!("{CHILD_SENTINEL}");
4623
4624 let mut opts = RunOptions {
4625 id: DaemonId::new("windows-retry", "live"),
4626 force: true,
4627 wait_ready: true,
4628 retry: Retry(2),
4629 dir: Dir(env::CWD.clone()),
4630 ..RunOptions::default()
4631 };
4632 let mut restart_mark = None;
4633 let mut guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
4634 assert!(
4635 SUPERVISOR
4636 .claim_or_defer(&opts, &mut guard, &mut restart_mark)
4637 .await
4638 .unwrap()
4639 .is_none()
4640 );
4641 drop(guard.take());
4642 let retrying_claim = SUPERVISOR.mark_retrying(&opts.id);
4643
4644 let powershell = std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap())
4649 .join("System32/WindowsPowerShell/v1.0/powershell.exe");
4650 let mut child = tokio::process::Command::new(powershell)
4651 .args([
4652 "-NoLogo",
4653 "-NoProfile",
4654 "-NonInteractive",
4655 "-Command",
4656 "[Console]::Out.WriteLine('READY'); [Console]::In.ReadToEnd() | Out-Null",
4657 ])
4658 .current_dir(std::env::var_os("SystemRoot").unwrap())
4659 .stdin(Stdio::piped())
4660 .stdout(Stdio::piped())
4661 .stderr(Stdio::null())
4662 .kill_on_drop(true)
4663 .hide_console_window()
4664 .spawn()
4665 .unwrap();
4666 let mut stdout = tokio::io::BufReader::new(child.stdout.take().unwrap());
4667 let mut ready = String::new();
4668 stdout.read_line(&mut ready).await.unwrap();
4669 assert_eq!(ready.trim_end(), "READY");
4670 let pid = child.id().unwrap();
4671 PROCS.refresh_pids(&[pid]);
4672 assert!(PROCS.is_running(pid));
4673 assert!(child.try_wait().unwrap().is_none());
4674 guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
4675 let running = SUPERVISOR
4676 .upsert_daemon(
4677 UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
4678 .set(|o| o.pid = Some(pid))
4679 .build(),
4680 )
4681 .await
4682 .unwrap();
4683 assert!(running.start_time.is_some());
4684 assert_eq!(running.start_time, PROCS.start_time(pid));
4685 let stop_epoch = SUPERVISOR.stop_epoch(&opts.id);
4686
4687 std::fs::write(
4688 env::CWD.join("pitchfork.toml"),
4689 "[settings.supervisor]\nuser = 'unsupported-account'\n",
4690 )
4691 .unwrap();
4692 reload_settings();
4693 assert_eq!(settings().supervisor.user, "unsupported-account");
4694 opts.retry_count = 1;
4695 let response = SUPERVISOR
4696 .claim_or_defer(&opts, &mut guard, &mut restart_mark)
4697 .await
4698 .unwrap();
4699
4700 assert!(
4702 child.try_wait().unwrap().is_none(),
4703 "the live instance was stopped"
4704 );
4705 let preserved = SUPERVISOR.get_daemon(&opts.id).await.unwrap();
4706 assert_eq!(preserved.pid, Some(pid));
4707 assert!(preserved.status.is_running());
4708 assert_eq!(
4709 serde_json::to_value(&preserved).unwrap(),
4710 serde_json::to_value(&running).unwrap()
4711 );
4712 assert_eq!(SUPERVISOR.stop_epoch(&opts.id), stop_epoch);
4713 assert!(!retrying_claim.is_cancelled());
4714 assert!(restart_mark.is_none());
4715 assert!(matches!(response, Some(IpcResponse::DaemonFailed { .. })));
4716 drop(guard.take());
4717 child.kill().await.unwrap();
4718 child.wait().await.unwrap();
4719
4720 opts.id = DaemonId::new("windows-retry", "pidless");
4723 guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
4724 SUPERVISOR
4725 .upsert_daemon(
4726 UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Errored(7)).build(),
4727 )
4728 .await
4729 .unwrap();
4730 assert!(matches!(
4731 SUPERVISOR
4732 .claim_or_defer(&opts, &mut guard, &mut restart_mark)
4733 .await
4734 .unwrap(),
4735 Some(IpcResponse::DaemonFailed { .. })
4736 ));
4737 let failed = SUPERVISOR.get_daemon(&opts.id).await.unwrap();
4738 assert!(failed.status.is_failed());
4739 assert!(failed.pid.is_none());
4740 assert_eq!(failed.retry_count, 1);
4741 assert_eq!(failed.retry, Retry(2));
4742 }
4743}
4744
4745#[cfg(test)]
4746mod output_reader_tests {
4747 use super::{forward_output_lines, output_line_text};
4748
4749 #[test]
4750 fn line_endings_are_removed() {
4751 assert_eq!(output_line_text(b"ready\n"), "ready");
4752 assert_eq!(output_line_text(b"ready\r\n"), "ready");
4754 assert_eq!(output_line_text(b"ready\r\r\n"), "ready");
4755 assert_eq!(output_line_text(b"ready"), "ready");
4757 }
4758
4759 #[tokio::test]
4760 async fn a_line_that_is_not_utf8_does_not_end_the_read() {
4761 let output: &[u8] = b"before\nbad \xff\xfe bytes\nafter 1\nafter 2\nlast";
4764 let (tx, mut rx) = tokio::sync::mpsc::channel(16);
4765 forward_output_lines(tokio::io::BufReader::new(output), tx).await;
4766
4767 let mut lines = Vec::new();
4768 while let Some(line) = rx.recv().await {
4769 lines.push(line.text);
4770 }
4771 assert_eq!(lines.len(), 5, "{lines:?}");
4772 assert_eq!(lines[0], "before");
4773 assert!(lines[1].starts_with("bad "), "{:?}", lines[1]);
4774 assert_eq!(&lines[2..], ["after 1", "after 2", "last"]);
4775 }
4776}
4777
4778#[cfg(test)]
4779mod output_reader_eio_tests {
4780 use super::forward_output_lines;
4781 use std::pin::Pin;
4782 use std::task::{Context, Poll};
4783
4784 struct EndsWithEio(Option<&'static [u8]>);
4787
4788 impl tokio::io::AsyncRead for EndsWithEio {
4789 fn poll_read(
4790 mut self: Pin<&mut Self>,
4791 _cx: &mut Context<'_>,
4792 buf: &mut tokio::io::ReadBuf<'_>,
4793 ) -> Poll<std::io::Result<()>> {
4794 match self.0.take() {
4795 Some(bytes) => {
4796 buf.put_slice(bytes);
4797 Poll::Ready(Ok(()))
4798 }
4799 None => Poll::Ready(Err(std::io::Error::from_raw_os_error(5))),
4800 }
4801 }
4802 }
4803
4804 #[tokio::test]
4805 async fn a_last_line_cut_off_by_eio_is_still_forwarded() {
4806 let reader = tokio::io::BufReader::new(EndsWithEio(Some(b"first\nlast without newline")));
4807 let (tx, mut rx) = tokio::sync::mpsc::channel(16);
4808 forward_output_lines(reader, tx).await;
4809
4810 let mut lines = Vec::new();
4811 while let Some(line) = rx.recv().await {
4812 lines.push(line.text);
4813 }
4814 assert_eq!(lines, ["first", "last without newline"]);
4815 }
4816}