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
39type HttpProbe = std::pin::Pin<
40 Box<
41 dyn std::future::Future<Output = std::result::Result<reqwest::Response, reqwest::Error>>
42 + Send,
43 >,
44>;
45
46type PortProbe = std::pin::Pin<
47 Box<dyn std::future::Future<Output = std::io::Result<tokio::net::TcpStream>> + Send>,
48>;
49
50enum ReadyFailure {
51 Exit(Option<i32>),
52 Termination(String),
53}
54
55fn resolve_configured_ready_port(
56 configured_port: u16,
57 expected_ports: &[u16],
58 resolved_ports: &[u16],
59) -> u16 {
60 let bump_offset = resolved_ports
61 .first()
62 .unwrap_or(&0)
63 .saturating_sub(*expected_ports.first().unwrap_or(&0));
64 if expected_ports.contains(&configured_port) && bump_offset > 0 {
65 configured_port
66 .checked_add(bump_offset)
67 .unwrap_or(configured_port)
68 } else {
69 configured_port
70 }
71}
72
73fn active_port_from_ready_port(ready_port: u16, resolved_ports: &[u16]) -> Option<u16> {
74 resolved_ports
75 .first()
76 .copied()
77 .filter(|&primary_port| primary_port == ready_port)
78}
79
80#[cfg(unix)]
81#[derive(Clone, Debug, PartialEq, Eq)]
82enum RunIdentity {
83 Inherit,
84 Switch {
85 uid: nix::unistd::Uid,
86 gid: nix::unistd::Gid,
87 username: Option<CString>,
88 home: Option<std::path::PathBuf>,
90 },
91}
92
93pub(crate) fn get_or_compile_regex(pattern: &str) -> Option<Regex> {
95 let mut cache = REGEX_CACHE.lock().unwrap_or_else(|e| e.into_inner());
96 if let Some(re) = cache.get(pattern) {
97 return Some(re.clone());
98 }
99 match Regex::new(pattern) {
100 Ok(re) => {
101 cache.insert(pattern.to_string(), re.clone());
102 Some(re)
103 }
104 Err(e) => {
105 error!("invalid regex pattern '{pattern}': {e}");
106 None
107 }
108 }
109}
110
111pub(crate) struct CmdProbe {
118 pub(crate) cancel_tx: tokio::sync::oneshot::Sender<()>,
119 pub(crate) result_rx: tokio::sync::oneshot::Receiver<std::io::Result<std::process::ExitStatus>>,
120}
121
122fn apply_runtime_env(
127 command: &mut tokio::process::Command,
128 id: &DaemonId,
129 retry_count: u32,
130 daemon_env: Option<&IndexMap<String, String>>,
131 resolved_ports: &[u16],
132) {
133 if let Some(ref path) = *env::ORIGINAL_PATH {
134 command.env("PATH", path);
135 }
136 if let Some(env_vars) = daemon_env {
137 command.envs(env_vars);
138 }
139 command
140 .env("PITCHFORK_DAEMON_ID", id.qualified())
141 .env("PITCHFORK_DAEMON_NAMESPACE", id.namespace())
142 .env("PITCHFORK_RETRY_COUNT", retry_count.to_string());
143 if let Some(port) = resolved_ports.first() {
144 command.env("PORT", port.to_string());
145 for (index, port) in resolved_ports.iter().enumerate() {
146 command.env(format!("PORT{index}"), port.to_string());
147 }
148 }
149}
150
151fn closed_cmd_probe() -> CmdProbe {
155 let (cancel_tx, _) = tokio::sync::oneshot::channel();
156 let (_, result_rx) = tokio::sync::oneshot::channel();
157 CmdProbe {
158 cancel_tx,
159 result_rx,
160 }
161}
162
163pub(crate) fn spawn_cmd_probe(
170 id: &DaemonId,
171 cmd: &RunCommand,
172 dir: &std::path::Path,
173 retry_count: u32,
174 daemon_env: Option<&IndexMap<String, String>>,
175 resolved_ports: &[u16],
176) -> CmdProbe {
177 let mut command = match cmd {
178 RunCommand::Argv(argv) => {
181 let Some((program, args)) = argv.split_first().filter(|(p, _)| !p.is_empty()) else {
182 warn!("daemon {id}: ready_cmd array has no program to run");
183 return closed_cmd_probe();
184 };
185 let mut c = tokio::process::Command::new(program);
186 c.args(args);
187 c
188 }
189 RunCommand::Shell(cmd) => match resolve_shell() {
195 Ok(parts) => {
196 let (program, args) = parts.split_first().unwrap();
197 let mut c = tokio::process::Command::new(program);
198 c.shell_script(program, args, cmd);
199 c
200 }
201 Err(e) => {
202 warn!("daemon {id}: {e}; using the platform shell for this probe");
203 Shell::default_for_platform().command(cmd)
204 }
205 },
206 };
207 command
208 .current_dir(dir)
209 .stdout(std::process::Stdio::null())
210 .stderr(std::process::Stdio::null())
211 .kill_on_drop(true)
212 .hide_console_window()
213 .close_inherited_fds();
214 apply_runtime_env(&mut command, id, retry_count, daemon_env, resolved_ports);
215 let mut child = match command.spawn() {
216 Ok(child) => child,
217 Err(e) => {
218 warn!("daemon {id}: failed to spawn command probe: {e}");
219 return closed_cmd_probe();
220 }
221 };
222
223 let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
224 let (result_tx, result_rx) = tokio::sync::oneshot::channel();
225
226 tokio::spawn(async move {
227 let status = tokio::select! {
228 status = child.wait() => status,
229 _ = &mut cancel_rx => {
230 let mut child = child;
231 let _ = child.kill().await;
232 child.wait().await
233 }
234 };
235 let _ = result_tx.send(status);
236 });
237
238 CmdProbe {
239 cancel_tx,
240 result_rx,
241 }
242}
243
244fn stop_cmd_probe_state(probe: &mut Option<CmdProbe>) {
246 if let Some(p) = probe.take() {
247 let _ = p.cancel_tx.send(());
248 }
249}
250
251fn spawn_ready_fail_kill(
255 id: DaemonId,
256 pid: u32,
257 stop_cfg: crate::config_types::StopConfig,
258) -> tokio::task::JoinHandle<Result<bool>> {
259 tokio::spawn(async move {
260 debug!("daemon {id}: terminating pid {pid} after readiness failure");
261 PROCS
262 .kill_process_group_async(pid, stop_cfg.signal.into(), stop_cfg.timeout)
263 .await
264 })
265}
266
267#[allow(clippy::too_many_arguments)]
272fn any_ready_check_remaining(
273 ready_output: Option<&ReadyOutput>,
274 output_exhausted: bool,
275 ready_port: Option<&ReadyPort>,
276 port_exhausted: bool,
277 ready_http: Option<&ReadyHttp>,
278 http_exhausted: bool,
279 ready_cmd: Option<&ReadyCmd>,
280 cmd_exhausted: bool,
281) -> bool {
282 ready_output.is_some_and(|o| o.timeout.is_none() || !output_exhausted)
283 || ready_port.is_some_and(|p| p.timeout.is_none() || !port_exhausted)
284 || ready_http.is_some_and(|h| h.timeout.is_none() || !http_exhausted)
285 || ready_cmd.is_some_and(|c| c.timeout.is_none() || !cmd_exhausted)
286}
287
288fn delay_readiness_succeeded(
289 ready_notified: bool,
290 has_other_ready_check: bool,
291 process_exited: bool,
292 process_running: bool,
293) -> bool {
294 !ready_notified && !has_other_ready_check && !process_exited && process_running
295}
296
297fn terminal_exit_state(
306 exit_reason: &str,
307 oneshot: bool,
308 exit_code: i32,
309 exited_cleanly: bool,
310) -> (DaemonStatus, bool) {
311 match exit_reason {
312 "exit" if oneshot => (DaemonStatus::Completed, true),
313 "stop" | "exit" => (DaemonStatus::Stopped, exited_cleanly),
314 _ => (DaemonStatus::Errored(exit_code), false),
315 }
316}
317
318fn invalid_probe_program(id: &DaemonId, field: &str, run: Option<&RunCommand>) -> Option<String> {
336 let RunCommand::Argv(argv) = run? else {
337 return None;
338 };
339 match argv.first().map(String::as_str) {
340 None | Some("") => Some(format!(
341 "daemon {id} has no program to run in its {field} array"
342 )),
343 Some("exec") => Some(format!(
344 "daemon {id} starts its {field} array with \"exec\"; a {field} array runs the program directly, so remove \"exec\""
345 )),
346 Some(_) => None,
347 }
348}
349
350fn invalid_argv_program(id: &DaemonId, argv: &[String]) -> Option<String> {
351 match argv.first().map(String::as_str) {
352 None | Some("") => Some(format!(
353 "daemon {id} has no program to run: its run array starts with an empty value"
354 )),
355 Some("exec") => Some(format!(
356 "daemon {id} starts its run array with \"exec\"; a run array starts the program directly, so remove \"exec\""
357 )),
358 Some(_) => None,
359 }
360}
361
362#[cfg(any(windows, test))]
363fn unsupported_windows_options(opts: &RunOptions, supervisor_user: &str) -> Option<String> {
364 if opts.pty == Some(true) {
365 return Some(format!(
366 "daemon {}: pty = true is not supported on Windows; remove pty or set it to false",
367 opts.id
368 ));
369 }
370 let configured_user = opts.user.as_deref().unwrap_or_default().trim();
371 if !configured_user.is_empty() || !supervisor_user.trim().is_empty() {
372 return Some(format!(
373 "daemon {}: user switching is not supported on Windows; remove the daemon's user and settings.supervisor.user, or set them to empty strings",
374 opts.id
375 ));
376 }
377 None
378}
379
380fn launch_command(words: Vec<String>, mise_bin: Option<&std::path::Path>) -> (String, Vec<String>) {
383 match mise_bin {
384 Some(mise_bin) => {
385 let mut args = vec!["x".to_string(), "--".to_string()];
386 args.extend(words);
387 (mise_bin.to_string_lossy().to_string(), args)
388 }
389 None => {
390 let mut words = words.into_iter();
391 let program = words.next().unwrap_or_default();
394 (program, words.collect())
395 }
396 }
397}
398
399fn output_line_text(line: &[u8]) -> String {
405 let line = line.strip_suffix(b"\n").unwrap_or(line);
406 crate::cli::log_sink::decode_line(line)
407 .trim_end_matches('\r')
408 .to_string()
409}
410
411async fn await_start_result(
415 mut start_result: super::StartResult,
416 fallback: Option<super::StartResult>,
417) -> IpcResponse {
418 if let Ok(result) = start_result.wait_for(Option::is_some).await
419 && let Some(result) = result.clone()
420 {
421 return result;
422 }
423 if let Some(mut attempt) = fallback
424 && let Ok(result) = attempt.wait_for(Option::is_some).await
425 && let Some(result) = result.clone()
426 {
427 return result;
428 }
429 IpcResponse::DaemonFailed {
430 error: "start ended without a readiness result".to_string(),
431 }
432}
433
434#[derive(Clone)]
437struct StatusTarget {
438 id: DaemonId,
439 token: u64,
440}
441
442async fn forward_output_lines<R>(
453 mut reader: R,
454 tx: tokio::sync::mpsc::Sender<super::OutputLine>,
455 status: Option<StatusTarget>,
456) where
457 R: tokio::io::AsyncBufRead + Unpin,
458{
459 use tokio::io::AsyncBufReadExt;
460 let mut scanner = crate::program_status::OscScanner::default();
461 let mut line = Vec::new();
462 loop {
463 let (consumed, complete, last) = match reader.fill_buf().await {
468 Ok([]) => (0, false, true),
469 Ok(buf) => {
470 let (consumed, complete) = match buf.iter().position(|b| *b == b'\n') {
471 Some(i) => (i + 1, true),
472 None => (buf.len(), false),
473 };
474 line.extend_from_slice(&buf[..consumed]);
475 if let Some(status) = &status {
479 for update in scanner.feed(&buf[..consumed]) {
480 let update = match update {
481 crate::program_status::StatusUpdate::Set(s) => Some(s),
482 crate::program_status::StatusUpdate::Clear => None,
483 };
484 super::log_sink::deliver_program_status(&status.id, status.token, update)
485 .await;
486 }
487 }
488 (consumed, complete, false)
489 }
490 Err(_) => (0, false, true),
491 };
492 reader.consume(consumed);
493 if complete || (last && !line.is_empty()) {
494 let sent = tx
495 .send(super::OutputLine {
496 text: output_line_text(&line),
497 source: super::OutputSource::Local,
498 })
499 .await;
500 line.clear();
501 if sent.is_err() {
502 break;
503 }
504 }
505 if last {
506 break;
507 }
508 }
509}
510
511fn stop_keeps_finalized_status(status: &DaemonStatus) -> bool {
512 status.is_completed()
513}
514
515const SINK_OUTPUT_TIMEOUT: Duration = Duration::from_millis(400);
520
521struct StopEpochGuard(DaemonId);
528
529impl Drop for StopEpochGuard {
530 fn drop(&mut self) {
531 SUPERVISOR.bump_stop_epoch(&self.0);
532 }
533}
534
535pub(crate) struct RetryingGuard {
536 id: DaemonId,
537 cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
538}
539
540impl RetryingGuard {
541 fn is_cancelled(&self) -> bool {
543 self.cancel.load(std::sync::atomic::Ordering::Acquire)
544 }
545}
546
547impl Drop for RetryingGuard {
548 fn drop(&mut self) {
549 let mut retrying = SUPERVISOR
550 .retrying
551 .lock()
552 .unwrap_or_else(|e| e.into_inner());
553 if let Some(claims) = retrying.get_mut(&self.id) {
557 claims.retain(|claim| !std::sync::Arc::ptr_eq(&claim.cancel, &self.cancel));
558 if claims.is_empty() {
559 retrying.remove(&self.id);
560 }
561 }
562 }
563}
564
565impl Supervisor {
566 pub(crate) fn is_retrying(&self, id: &DaemonId) -> bool {
568 self.retrying
569 .lock()
570 .unwrap_or_else(|e| e.into_inner())
571 .get(id)
572 .is_some_and(|claims| !claims.is_empty())
573 }
574
575 pub(crate) fn stop_epoch(&self, id: &DaemonId) -> u64 {
577 self.stop_epochs
578 .lock()
579 .unwrap_or_else(|e| e.into_inner())
580 .get(id)
581 .copied()
582 .unwrap_or(0)
583 }
584
585 fn bump_stop_epoch(&self, id: &DaemonId) {
586 *self
587 .stop_epochs
588 .lock()
589 .unwrap_or_else(|e| e.into_inner())
590 .entry(id.clone())
591 .or_default() += 1;
592 }
593
594 pub(super) fn mark_retrying(&self, id: &DaemonId) -> RetryingGuard {
595 self.mark_retrying_with_result(id, None)
596 }
597
598 fn mark_retrying_with_result(
599 &self,
600 id: &DaemonId,
601 result: Option<&super::StartResult>,
602 ) -> RetryingGuard {
603 let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
604 self.retrying
605 .lock()
606 .unwrap_or_else(|e| e.into_inner())
607 .entry(id.clone())
608 .or_default()
609 .push(super::RetryClaim {
610 cancel: cancel.clone(),
611 result: result.cloned(),
612 });
613 RetryingGuard {
614 id: id.clone(),
615 cancel,
616 }
617 }
618
619 fn retry_result(
620 &self,
621 id: &DaemonId,
622 own_result: Option<&super::StartResult>,
623 ) -> Option<super::StartResult> {
624 self.retrying
625 .lock()
626 .unwrap_or_else(|e| e.into_inner())
627 .get(id)?
628 .iter()
629 .filter(|claim| !claim.cancel.load(atomic::Ordering::Acquire))
630 .filter_map(|claim| claim.result.as_ref())
631 .find(|result| own_result.is_none_or(|own| !own.same_channel(result)))
632 .cloned()
633 }
634
635 pub(crate) fn cancel_retrying(&self, id: &DaemonId) {
639 if let Some(claims) = self
640 .retrying
641 .lock()
642 .unwrap_or_else(|e| e.into_inner())
643 .get(id)
644 {
645 for claim in claims {
649 claim
650 .cancel
651 .store(true, std::sync::atomic::Ordering::Release);
652 }
653 }
654 }
655
656 pub async fn run(&self, opts: RunOptions) -> Result<IpcResponse> {
658 let id = opts.id.clone();
659 let mut restart_mark = None;
660 let (result_tx, result_rx) = tokio::sync::watch::channel(None);
665 let wait_ready = opts.wait_ready;
666 let result = self
667 .run_inner(
668 opts,
669 None,
670 &mut restart_mark,
671 wait_ready.then_some(&result_rx),
672 )
673 .await;
674 if let Some(mark) = restart_mark {
677 self.settle_restarting(&id, mark).await;
678 }
679 result_tx.send_replace(Some(match &result {
680 Ok(response) => response.clone(),
681 Err(e) => IpcResponse::Error(e.to_string()),
682 }));
683 result
684 }
685
686 pub(crate) async fn settle_restarting(&self, id: &DaemonId, mark: u64) {
695 let lock = self.stop_lock(id).await;
696 let _guard = lock.lock().await;
697 if self.stop_epoch(id) != mark {
698 return;
699 }
700 let mut state_file = self.state_file.lock().await;
701 if state_file
702 .daemons
703 .get(id)
704 .is_some_and(|d| d.pid.is_none() && d.status.is_restarting())
705 {
706 debug!("daemon {id} was not started again after its restart; recording it as stopped");
707 state_file.set_status(id, DaemonStatus::Stopped);
708 }
709 }
710
711 pub(crate) async fn run_retry(
718 &self,
719 opts: RunOptions,
720 approved_at: u64,
721 restart_mark: &mut Option<u64>,
722 ) -> Result<IpcResponse> {
723 let (result_tx, result_rx) = tokio::sync::watch::channel(None);
724 let wait_ready = opts.wait_ready;
725 let result = self
726 .run_inner(
727 opts,
728 Some(approved_at),
729 restart_mark,
730 wait_ready.then_some(&result_rx),
731 )
732 .await;
733 result_tx.send_replace(Some(match &result {
734 Ok(response) => response.clone(),
735 Err(error) => IpcResponse::Error(error.to_string()),
736 }));
737 result
738 }
739
740 #[cfg(windows)]
742 async fn reject_unsupported_windows_options(
743 &self,
744 opts: &RunOptions,
745 ) -> Result<Option<IpcResponse>> {
746 let Some(error) = unsupported_windows_options(opts, &settings().supervisor.user) else {
747 return Ok(None);
748 };
749 if self
753 .get_daemon(&opts.id)
754 .await
755 .is_none_or(|d| d.pid.is_none())
756 {
757 self.upsert_daemon(
758 UpsertDaemonOpts::from_run_options(opts, DaemonStatus::Failed(error.clone()))
759 .build(),
760 )
761 .await?;
762 }
763 Ok(Some(IpcResponse::DaemonFailed { error }))
764 }
765
766 async fn run_inner(
773 &self,
774 opts: RunOptions,
775 approved_at: Option<u64>,
776 restart_mark: &mut Option<u64>,
777 start_result: Option<&super::StartResult>,
778 ) -> Result<IpcResponse> {
779 let id = &opts.id;
780 let cmd = opts.cmd.clone();
781
782 {
784 let mut pending = self.pending_autostops.lock().await;
785 if pending.remove(id).is_some() {
786 info!("cleared pending autostop for {id} (daemon starting)");
787 }
788 }
789
790 let mut stop_guard = Some(self.stop_lock(id).await.lock_owned().await);
801 if let Some(approved_at) = approved_at
806 && self.stop_epoch(id) != approved_at
807 {
808 info!("daemon {id} was stopped after this retry was decided on; not starting it");
809 return Ok(IpcResponse::DaemonNotRunning);
810 }
811 if (approved_at.is_some() || !opts.requested_by_client)
815 && self.state_file.lock().await.disabled.contains(id)
816 {
817 info!("daemon {id} was disabled before this start; not starting it");
818 return Ok(IpcResponse::DaemonNotRunning);
819 }
820 if let Some(response) = self
821 .claim_or_defer(&opts, &mut stop_guard, restart_mark, start_result)
822 .await?
823 {
824 return Ok(response);
825 }
826
827 if opts.wait_ready && opts.retry.count() > 0 {
829 let retrying_claim = self.mark_retrying_with_result(id, start_result);
834 let max_attempts = opts.retry.count().saturating_add(1);
836 let first_attempt = if approved_at.is_some() {
837 opts.retry_count
838 } else {
839 0
840 };
841 for attempt in first_attempt..max_attempts {
842 let mut retry_opts = opts.clone();
843 retry_opts.retry_count = attempt;
844 retry_opts.cmd = cmd.clone();
845
846 let mut guard = Some(match stop_guard.take() {
850 Some(guard) => guard,
851 None => self.stop_lock(id).await.lock_owned().await,
852 });
853 if attempt > 0
863 && let Some(daemon) = self.get_daemon(id).await
864 && daemon.status.is_completed()
865 {
866 info!("daemon {id} completed while waiting to retry; not running it again");
867 return Ok(IpcResponse::DaemonReady { daemon });
868 }
869 if attempt > 0 && self.state_file.lock().await.disabled.contains(id) {
873 info!(
874 "daemon {id} was disabled while waiting to retry; abandoning its retries"
875 );
876 return Ok(IpcResponse::DaemonFailed {
877 error: "disabled while retrying".to_string(),
878 });
879 }
880 if retrying_claim.is_cancelled() {
885 info!("daemon {id} was stopped while waiting to retry; abandoning its retries");
886 return Ok(IpcResponse::DaemonFailed {
887 error: "stopped while retrying".to_string(),
888 });
889 }
890 if let Some(response) = self
896 .claim_or_defer(&retry_opts, &mut guard, restart_mark, start_result)
897 .await?
898 {
899 return Ok(response);
900 }
901 let Some(guard) = guard else {
902 return Ok(IpcResponse::DaemonAlreadyRunning);
905 };
906 let result = self.run_once(retry_opts, guard, start_result).await?;
907
908 match result {
909 IpcResponse::DaemonReady { daemon } => {
910 return Ok(IpcResponse::DaemonReady { daemon });
911 }
912 IpcResponse::DaemonFailedWithCode {
913 exit_code,
914 resolved_ports,
915 } => {
916 if attempt < opts.retry.count() {
917 let attempt_pid = self.get_daemon(id).await.and_then(|d| d.pid);
925 self.wait_for_exit_finalized(id, attempt_pid).await;
926 let backoff_secs = 2u64.saturating_pow(attempt).min(3600);
927 info!(
928 "daemon {id} failed (attempt {}/{}), retrying in {}s",
929 attempt + 1,
930 max_attempts,
931 backoff_secs
932 );
933 fire_hook(
934 HookType::OnRetry,
935 id.clone(),
936 super::hooks::HookDirs::new(
937 opts.dir.0.clone(),
938 opts.watch_base_dir.clone(),
939 ),
940 attempt + 1,
941 opts.env.clone(),
942 resolved_ports,
943 vec![],
944 )
945 .await;
946 let backoff_deadline =
951 tokio::time::Instant::now() + Duration::from_secs(backoff_secs);
952 while tokio::time::Instant::now() < backoff_deadline
953 && !retrying_claim.is_cancelled()
954 {
955 let remaining = backoff_deadline - tokio::time::Instant::now();
956 time::sleep(remaining.min(Duration::from_millis(200))).await;
957 }
958 continue;
959 } else {
960 info!("daemon {id} failed after {max_attempts} attempts");
961 return Ok(IpcResponse::DaemonFailedWithCode {
962 exit_code,
963 resolved_ports,
964 });
965 }
966 }
967 other => return Ok(other),
968 }
969 }
970 }
971
972 let guard = match stop_guard.take() {
974 Some(guard) => guard,
975 None => self.stop_lock(id).await.lock_owned().await,
976 };
977 self.run_once(opts, guard, start_result).await
978 }
979
980 async fn wait_for_exit_finalized(&self, id: &DaemonId, pid: Option<u32>) {
991 let deadline = tokio::time::Instant::now() + Duration::from_secs(8);
992 loop {
993 match self.get_daemon(id).await {
994 Some(daemon) if pid.map_or(daemon.pid.is_some(), |pid| daemon.pid == Some(pid)) => {
995 }
996 _ => return,
997 }
998 if tokio::time::Instant::now() >= deadline {
999 debug!("daemon {id}: previous attempt has not finalized yet; continuing anyway");
1000 return;
1001 }
1002 time::sleep(Duration::from_millis(50)).await;
1003 }
1004 }
1005
1006 async fn claim_or_defer(
1021 &self,
1022 opts: &RunOptions,
1023 stop_guard: &mut Option<tokio::sync::OwnedMutexGuard<()>>,
1024 restart_mark: &mut Option<u64>,
1025 own_result: Option<&super::StartResult>,
1026 ) -> Result<Option<IpcResponse>> {
1027 let id = &opts.id;
1028 #[cfg(windows)]
1029 if let Some(response) = self.reject_unsupported_windows_options(opts).await? {
1030 return Ok(Some(response));
1031 }
1032 if !opts.force
1033 && let Some(result) = self.retry_result(id, own_result)
1034 {
1035 if !opts.wait_ready {
1036 return Ok(Some(IpcResponse::DaemonAlreadyRunning));
1037 }
1038 info!("daemon {id} has a start sequence in progress; waiting for it");
1039 let fallback = self
1040 .ready_check(id)
1041 .filter(|check| check.result.same_channel(&result))
1042 .map(|check| check.attempt);
1043 let oneshot = self
1044 .get_daemon(id)
1045 .await
1046 .filter(|daemon| daemon.oneshot)
1047 .map(|daemon| daemon.pid.unwrap_or(0));
1048 drop(stop_guard.take());
1049 if let Some(pid) = oneshot {
1050 return Ok(Some(
1052 self.await_running_oneshot(id, opts.oneshot_wait, pid).await,
1053 ));
1054 }
1055 return Ok(Some(await_start_result(result, fallback).await));
1056 }
1057 let Some(daemon) = self.get_daemon(id).await else {
1058 return Ok(None);
1059 };
1060 if opts.on_directory_enter && opts.oneshot && daemon.status.is_completed() {
1071 debug!("daemon {id} already completed; directory entry leaves it alone");
1072 return Ok(Some(IpcResponse::DaemonReady { daemon }));
1073 }
1074 if daemon.status.is_stopping_or_restarting()
1078 || daemon.status.is_stopped()
1079 || daemon.status.is_completed()
1080 {
1081 return Ok(None);
1082 }
1083 let Some(pid) = daemon.pid else {
1084 return Ok(None);
1085 };
1086 if opts.force {
1087 self.stop_locked_with(id, true).await?;
1091 *restart_mark = Some(self.stop_epoch(id));
1094 info!("run: stop completed for daemon {id}");
1095 return Ok(None);
1096 }
1097 if daemon.oneshot && opts.wait_ready {
1098 info!("daemon {id} is an in-flight oneshot (pid {pid}); waiting for it to finish");
1103 drop(stop_guard.take());
1104 return Ok(Some(
1105 self.await_running_oneshot(id, opts.oneshot_wait, pid).await,
1106 ));
1107 }
1108 if opts.wait_ready
1109 && let Some(check) = self.ready_check(id)
1110 && check.pid == pid
1111 {
1112 info!("daemon {id} (pid {pid}) has not passed its ready check; waiting for it");
1118 drop(stop_guard.take());
1119 return Ok(Some(
1120 await_start_result(check.result, Some(check.attempt)).await,
1121 ));
1122 }
1123 if let DaemonStatus::Failed(error) = &daemon.status
1124 && PROCS.process_group_alive(pid)
1125 {
1126 return Ok(Some(IpcResponse::DaemonFailed {
1127 error: error.clone(),
1128 }));
1129 }
1130 PROCS.refresh_pids(&[pid]);
1141 if !PROCS.is_running(pid) {
1142 debug!(
1143 "daemon {id}: record still names pid {pid}, which has exited; its monitor has not finalized yet"
1144 );
1145 return Ok(None);
1146 }
1147 warn!("daemon {id} already running with pid {pid}");
1148 Ok(Some(IpcResponse::DaemonAlreadyRunning))
1149 }
1150
1151 async fn await_running_oneshot(
1158 &self,
1159 id: &DaemonId,
1160 wait: Option<OneshotWait>,
1161 watched_pid: u32,
1162 ) -> IpcResponse {
1163 let interval = settings().supervisor_ready_check_interval();
1164 let deadline = wait
1180 .unwrap_or_else(|| settings().supervisor_oneshot_wait())
1181 .duration()
1182 .map(|d| tokio::time::Instant::now() + d);
1183 let mut watched_pid = watched_pid;
1191 loop {
1192 let Some(daemon) = self.get_daemon(id).await else {
1193 return IpcResponse::DaemonNotFound;
1194 };
1195 if let Some(current) = daemon.pid
1196 && current != watched_pid
1197 {
1198 info!(
1199 "daemon {id}: the run being waited on (pid {watched_pid}) was replaced by pid {current}; following it"
1200 );
1201 watched_pid = current;
1202 }
1203 match &daemon.status {
1204 DaemonStatus::Completed => {
1205 info!("daemon {id}: the in-flight oneshot completed");
1206 return IpcResponse::DaemonReady { daemon };
1207 }
1208 DaemonStatus::Errored(code) => {
1209 if daemon.retry.count() > 0
1217 && daemon.retry_count < daemon.retry.count()
1218 && !self.state_file.lock().await.disabled.contains(id)
1219 {
1220 debug!(
1221 "daemon {id}: in-flight oneshot failed attempt {} of {}; still waiting",
1222 daemon.retry_count + 1,
1223 daemon.retry.count() + 1
1224 );
1225 } else {
1226 let exit_code = Some(*code).filter(|c| *c != -1);
1230 return IpcResponse::DaemonFailedWithCode {
1231 exit_code,
1232 resolved_ports: daemon.resolved_port.clone(),
1233 };
1234 }
1235 }
1236 DaemonStatus::Failed(error) => {
1237 return IpcResponse::DaemonFailed {
1238 error: error.clone(),
1239 };
1240 }
1241 DaemonStatus::Stopped => {
1242 warn!("daemon {id}: the in-flight oneshot was stopped before completing");
1245 return IpcResponse::DaemonFailedWithCode {
1246 exit_code: None,
1247 resolved_ports: daemon.resolved_port.clone(),
1248 };
1249 }
1250 DaemonStatus::Running
1251 | DaemonStatus::Waiting
1252 | DaemonStatus::Stopping
1253 | DaemonStatus::Restarting => {}
1254 }
1255 if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
1256 warn!("daemon {id}: gave up waiting for the in-flight oneshot to finish");
1257 return IpcResponse::DaemonFailedWithCode {
1263 exit_code: Some(124),
1264 resolved_ports: Vec::new(),
1265 };
1266 }
1267 time::sleep(interval).await;
1268 }
1269 }
1270
1271 fn register_ready_check(
1273 &self,
1274 id: &DaemonId,
1275 pid: u32,
1276 start_result: &super::StartResult,
1277 attempt: &super::StartResult,
1278 ) {
1279 self.ready_checks
1280 .lock()
1281 .unwrap_or_else(|e| e.into_inner())
1282 .insert(
1283 id.clone(),
1284 super::ReadyCheck {
1285 pid,
1286 result: start_result.clone(),
1287 attempt: attempt.clone(),
1288 },
1289 );
1290 }
1291
1292 fn ready_check(&self, id: &DaemonId) -> Option<super::ReadyCheck> {
1294 self.ready_checks
1295 .lock()
1296 .unwrap_or_else(|e| e.into_inner())
1297 .get(id)
1298 .cloned()
1299 }
1300
1301 fn end_ready_check(&self, id: &DaemonId, attempt: &super::StartResult) {
1306 let mut ready_checks = self.ready_checks.lock().unwrap_or_else(|e| e.into_inner());
1307 if ready_checks
1308 .get(id)
1309 .is_some_and(|check| check.attempt.same_channel(attempt))
1310 {
1311 ready_checks.remove(id);
1312 }
1313 }
1314
1315 pub(crate) async fn run_once(
1322 &self,
1323 opts: RunOptions,
1324 stop_guard: tokio::sync::OwnedMutexGuard<()>,
1325 start_result: Option<&super::StartResult>,
1326 ) -> Result<IpcResponse> {
1327 let id = &opts.id;
1328 if self
1335 .shutting_down
1336 .load(std::sync::atomic::Ordering::Acquire)
1337 {
1338 info!("not starting daemon {id}: the supervisor is shutting down");
1339 return Ok(IpcResponse::DaemonFailed {
1340 error: "the supervisor is shutting down".to_string(),
1341 });
1342 }
1343 #[cfg(windows)]
1345 if let Some(response) = self.reject_unsupported_windows_options(&opts).await? {
1346 return Ok(response);
1347 }
1348 let original_cmd = opts.cmd.clone(); let (ready_tx, ready_rx) = if opts.wait_ready || !opts.oneshot {
1352 let (tx, rx) = oneshot::channel::<std::result::Result<(), ReadyFailure>>();
1353 (Some(tx), Some(rx))
1354 } else {
1355 (None, None)
1356 };
1357
1358 let expected_ports = opts
1360 .port
1361 .as_ref()
1362 .map(|p| p.expect.clone())
1363 .unwrap_or_default();
1364 let mut port_claim: Option<PortClaim> = None;
1367 let (resolved_ports, effective_ready_port) = if !expected_ports.is_empty() {
1368 let port_cfg = opts.port.as_ref().unwrap();
1369 match claim_ports(
1370 id,
1371 &expected_ports,
1372 port_cfg.auto_bump(),
1373 port_cfg.max_bump_attempts(),
1374 )
1375 .await
1376 {
1377 Ok((resolved, claim)) => {
1378 port_claim = Some(claim);
1379 let ready_port = if let Some(configured_port) =
1380 opts.ready_port.as_ref().and_then(|p| p.as_port())
1381 {
1382 Some(resolve_configured_ready_port(
1383 configured_port,
1384 &expected_ports,
1385 &resolved,
1386 ))
1387 } else if opts.ready_output.is_none()
1388 && opts.ready_http.is_none()
1389 && opts.ready_cmd.is_none()
1390 && opts.ready_delay.is_none()
1391 {
1392 resolved.first().copied().filter(|&p| p != 0)
1396 } else {
1397 None
1401 };
1402 info!("daemon {id}: ports {expected_ports:?} resolved to {resolved:?}");
1403 (resolved, ready_port)
1404 }
1405 Err(e) => {
1406 error!("daemon {id}: port check failed: {e}");
1407 if let Some(port_error) = e.downcast_ref::<PortError>() {
1409 match port_error {
1410 PortError::Claimed { .. } => {
1411 return Ok(IpcResponse::DaemonFailed {
1412 error: e.to_string(),
1413 });
1414 }
1415 PortError::InUse {
1416 port,
1417 address,
1418 process,
1419 pid,
1420 } => {
1421 return Ok(IpcResponse::PortConflict {
1422 port: *port,
1423 process: process.clone(),
1424 pid: *pid,
1425 address: address.clone(),
1426 });
1427 }
1428 PortError::NoAvailablePort {
1429 start_port,
1430 attempts,
1431 } => {
1432 return Ok(IpcResponse::NoAvailablePort {
1433 start_port: *start_port,
1434 attempts: *attempts,
1435 });
1436 }
1437 }
1438 }
1439 return Ok(IpcResponse::DaemonFailed {
1440 error: e.to_string(),
1441 });
1442 }
1443 }
1444 } else {
1445 if let Some(port) = opts.ready_port.as_ref().and_then(|p| p.as_port())
1451 && port > 0
1452 {
1453 match claim_ports(id, &[port], false, 0).await {
1454 Ok((_, claim)) => port_claim = Some(claim),
1455 Err(e)
1456 if matches!(
1457 e.downcast_ref::<PortError>(),
1458 Some(PortError::Claimed { .. })
1459 ) =>
1460 {
1461 return Ok(IpcResponse::DaemonFailed {
1462 error: e.to_string(),
1463 });
1464 }
1465 Err(_) => {}
1467 }
1468 }
1469 if let Some(port) = opts.ready_port.as_ref().and_then(|p| p.as_port())
1470 && port > 0
1471 && let Some((address, pid, process)) = detect_port_conflict(port).await
1472 {
1473 return Ok(IpcResponse::PortConflict {
1474 port,
1475 process,
1476 pid,
1477 address: Some(address),
1478 });
1479 }
1480 (
1481 Vec::new(),
1482 opts.ready_port.as_ref().and_then(|p| p.as_port()),
1483 )
1484 };
1485
1486 if let Some(error) = invalid_probe_program(
1491 id,
1492 "ready_cmd",
1493 opts.ready_cmd.as_ref().map(|c| &c.run),
1494 )
1495 .or_else(|| {
1496 invalid_probe_program(id, "health_cmd", opts.health_cmd.as_ref().map(|c| &c.run))
1497 }) {
1498 return Ok(IpcResponse::DaemonFailed { error });
1499 }
1500
1501 let (mut words, script) = if opts.no_shell {
1502 if let Some(error) = invalid_argv_program(id, &original_cmd) {
1505 return Ok(IpcResponse::DaemonFailed { error });
1506 }
1507 (original_cmd.clone(), None)
1508 } else {
1509 let words = match resolve_shell() {
1513 Ok(parts) => parts,
1514 Err(error) => return Ok(IpcResponse::DaemonFailed { error }),
1515 };
1516 let script = opts
1521 .run
1522 .clone()
1523 .unwrap_or_else(|| shell_words::join(&original_cmd));
1524 (words, Some(script))
1525 };
1526
1527 let mise_bin = if opts.mise.unwrap_or(settings().general.mise) {
1528 let mise_bin = settings().resolve_daemon_mise_bin(opts.mise_bin.as_deref());
1529 if mise_bin.is_none() {
1530 warn!("daemon {id}: mise=true but mise binary not found, running without mise");
1531 }
1532 mise_bin
1533 } else {
1534 None
1535 };
1536 if mise_bin.is_none() && opts.deferred_template_context.is_some() {
1540 return Ok(IpcResponse::DaemonFailed {
1541 error: format!(
1542 "daemon {id}: the command uses template variables only mise can render, but mise is not enabled or its binary was not found"
1543 ),
1544 });
1545 }
1546 let script = match &mise_bin {
1551 Some(mise_bin) => {
1552 info!(
1553 "daemon {id}: wrapping command with mise ({})",
1554 mise_bin.display()
1555 );
1556 if let Some(script) = script {
1557 words =
1558 mise_shell_words(words, script, opts.deferred_template_context.is_some());
1559 }
1560 None
1561 }
1562 None => script,
1563 };
1564 let (program, args) = launch_command(words, mise_bin.as_deref());
1565 #[cfg(unix)]
1566 let run_identity = match resolve_effective_run_identity(opts.user.as_deref()) {
1567 Ok(identity) => identity,
1568 Err(e) => {
1569 return Ok(IpcResponse::DaemonFailed {
1570 error: e.to_string(),
1571 });
1572 }
1573 };
1574 info!("run: spawning daemon {id} with {program} {args:?} {script:?}");
1575
1576 #[cfg(unix)]
1578 let pty_pair = if opts.pty.unwrap_or(false) {
1579 match super::pty::openpty() {
1580 Ok(pair) => {
1581 info!("daemon {id}: allocated PTY (pty = true)");
1582 Some(pair)
1583 }
1584 Err(e) => {
1585 warn!("daemon {id}: failed to allocate PTY, falling back to pipes: {e}");
1586 None
1587 }
1588 }
1589 } else {
1590 None
1591 };
1592
1593 let (output_tx, output_rx) = tokio::sync::mpsc::channel::<super::OutputLine>(256);
1599 let output_relay = super::log_sink::OutputRelay::register(id, output_tx.clone());
1603 let status_token = output_relay.token();
1604
1605 let mut sink_pipe = None;
1608 let mut sink_writer = None;
1609 let mut sink_child = None;
1610 if super::log_sink::is_supported(&opts) {
1611 let log_format = opts
1612 .log_format
1613 .clone()
1614 .unwrap_or_else(|| settings().logs.log_format.clone());
1615 let watch_for = super::log_sink::WatchFor::from_opts(id, &opts);
1616 let relay_token = status_token;
1619 match super::log_sink::SinkPipe::new(log_format, watch_for, relay_token) {
1620 Ok((pipe, writer)) => match pipe.start(id) {
1621 Ok(child) => {
1622 sink_child = Some(super::log_sink::PendingSink::new(child));
1623 sink_pipe = Some(pipe);
1624 sink_writer = Some(writer);
1625 }
1626 Err(e) => {
1627 warn!("could not start log sink for {id}, capturing in-process: {e}");
1628 }
1629 },
1630 Err(e) => {
1631 warn!("could not create log pipe for {id}, capturing in-process: {e}");
1634 }
1635 }
1636 }
1637
1638 let mut cmd = tokio::process::Command::new(&program);
1639
1640 #[cfg(unix)]
1641 if let Some(ref pair) = pty_pair {
1642 let slave_file = std::fs::File::from(
1646 pair.slave
1647 .try_clone()
1648 .map_err(|e| miette::miette!("failed to dup slave PTY fd: {e}"))?,
1649 );
1650 cmd.stdin(std::process::Stdio::from(slave_file.try_clone().map_err(
1651 |e| miette::miette!("failed to clone slave PTY fd for stdin: {e}"),
1652 )?));
1653 cmd.stdout(std::process::Stdio::from(slave_file.try_clone().map_err(
1654 |e| miette::miette!("failed to clone slave PTY fd for stdout: {e}"),
1655 )?));
1656 cmd.stderr(std::process::Stdio::from(slave_file));
1657 } else if let Some(writer) = sink_writer.take() {
1658 let dup = writer
1661 .try_clone()
1662 .map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
1663 cmd.stdout(std::process::Stdio::from(writer))
1664 .stderr(std::process::Stdio::from(dup));
1665 } else {
1666 cmd.stdout(std::process::Stdio::piped())
1667 .stderr(std::process::Stdio::piped());
1668 }
1669
1670 #[cfg(not(unix))]
1671 if let Some(writer) = sink_writer.take() {
1672 let dup = writer
1673 .try_clone()
1674 .map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
1675 cmd.stdout(std::process::Stdio::from(writer))
1676 .stderr(std::process::Stdio::from(dup));
1677 } else {
1678 cmd.stdout(std::process::Stdio::piped())
1679 .stderr(std::process::Stdio::piped());
1680 }
1681
1682 match &script {
1683 Some(script) => cmd.shell_script(&program, &args, script),
1684 None => cmd.args(&args),
1685 };
1686 cmd.current_dir(&opts.dir)
1687 .hide_console_window()
1688 .close_inherited_fds();
1689
1690 #[cfg(unix)]
1691 if pty_pair.is_none() {
1692 cmd.stdin(std::process::Stdio::null());
1693 }
1694
1695 #[cfg(not(unix))]
1696 cmd.stdin(std::process::Stdio::null());
1697
1698 #[cfg(unix)]
1700 apply_identity_env(&mut cmd, &run_identity);
1701 apply_runtime_env(
1702 &mut cmd,
1703 id,
1704 opts.retry_count,
1705 opts.env.as_ref(),
1706 &resolved_ports,
1707 );
1708 if let Some(context) = &opts.deferred_template_context {
1710 cmd.env(crate::template::TEMPLATE_CONTEXT_ENV, context);
1711 }
1712
1713 inject_proxy_env(&mut cmd, &daemon_proxy_host(&opts).await);
1715
1716 #[cfg(unix)]
1717 {
1718 let run_identity = run_identity.clone();
1719 let use_pty = pty_pair.is_some();
1720 unsafe {
1721 cmd.pre_exec(move || {
1722 nix::unistd::setsid().map_err(nix_to_io_error)?;
1723
1724 if use_pty {
1728 let ret = libc::ioctl(0, libc::TIOCSCTTY as _, 0);
1729 if ret < 0 {
1730 #[cfg(target_os = "linux")]
1733 eprintln!(
1734 "pitchfork: TIOCSCTTY failed: {}",
1735 std::io::Error::last_os_error()
1736 );
1737 }
1738 }
1739
1740 apply_run_identity(&run_identity)?;
1741 Ok(())
1742 });
1743 }
1744 }
1745
1746 let spawn_time = chrono::Local::now();
1749 let mut child = cmd.spawn().into_diagnostic()?;
1755 #[cfg(windows)]
1758 if let (Some(pid), Some(process)) = (child.id(), child.raw_handle()) {
1759 crate::win_job::contain_spawned(process as _, pid);
1760 }
1761 let spawned_pid = child.id();
1762 let monitored_guard =
1772 spawned_pid.map(|pid| super::adopt::MonitoredGuard::register(id.clone(), pid));
1773 if opts.cron_started {
1789 let mut state_file = self.state_file.lock().await;
1790 if state_file.set_last_cron_run(id, spawn_time)
1791 && let Err(e) = state_file.write()
1792 {
1793 error!("failed to persist last_cron_run for daemon {id}: {e}");
1794 }
1795 }
1796 let (pid, monitored_guard) = match (spawned_pid, monitored_guard) {
1797 (Some(p), Some(guard)) => (p, guard),
1798 _ => {
1799 warn!("Daemon {id} exited before PID could be captured");
1800 if sink_child.is_some() {
1806 super::log_sink::wait_for_output(id, spawn_time, SINK_OUTPUT_TIMEOUT).await;
1807 }
1808 return Ok(IpcResponse::DaemonFailed {
1809 error: "Process exited immediately".to_string(),
1810 });
1811 }
1812 };
1813 info!("started daemon {id} with pid {pid}");
1814 PROCS.refresh_pids(&[pid]);
1815 let monitor_token = monitored_guard.token();
1816
1817 let using_sink = sink_pipe.is_some();
1820 if let Some(pipe) = sink_pipe.take()
1823 && let Some(child) = sink_child.as_mut().and_then(|pending| pending.take())
1824 {
1825 pipe.supervise(id.clone(), monitor_token, child);
1826 }
1827 let attempt_resolved_ports = resolved_ports.clone();
1834 let daemon = self
1835 .upsert_daemon(
1836 UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
1837 .set(|o| {
1838 o.pid = Some(pid);
1839 o.cmd = Some(original_cmd);
1840 o.ready_port = effective_ready_port.map(|p| ReadyPort {
1841 port: Some(p),
1842 template: None,
1843 timeout: opts.ready_port.as_ref().and_then(|rp| rp.timeout),
1844 });
1845 o.port = crate::config_types::PortConfig::from_parts(
1846 expected_ports,
1847 opts.port.as_ref().map(|p| p.bump).unwrap_or_default(),
1848 );
1849 o.resolved_port = Some(resolved_ports);
1850 })
1851 .build(),
1852 )
1853 .await?;
1854
1855 let (attempt_tx, attempt_rx) = tokio::sync::watch::channel(None);
1858 if ready_rx.is_some() {
1859 self.register_ready_check(id, pid, start_result.unwrap_or(&attempt_rx), &attempt_rx);
1860 }
1861
1862 drop(stop_guard);
1867
1868 let id_clone = id.clone();
1869 let ready_delay = (!opts.oneshot).then_some(opts.ready_delay).flatten();
1877 let ready_output = (!opts.oneshot).then(|| opts.ready_output.clone()).flatten();
1878 let ready_http = (!opts.oneshot).then(|| opts.ready_http.clone()).flatten();
1879 let ready_port = (!opts.oneshot).then_some(effective_ready_port).flatten();
1880 let implicit_ready_port = ready_port.map(|p| ReadyPort {
1881 port: Some(p),
1882 template: None,
1883 timeout: None,
1884 });
1885 let ready_port_config = (!opts.oneshot)
1886 .then(|| opts.ready_port.clone())
1887 .flatten()
1888 .or(implicit_ready_port);
1889 let ready_cmd = (!opts.oneshot).then(|| opts.ready_cmd.clone()).flatten();
1890 let daemon_dir = opts.dir.0.clone();
1891 let hook_dirs =
1892 super::hooks::HookDirs::new(daemon_dir.clone(), opts.watch_base_dir.clone());
1893 let hook_retry_count = opts.retry_count;
1894 let hook_retry = opts.retry;
1895 let hook_daemon_env = opts.env.clone();
1896 let hook_resolved_ports = attempt_resolved_ports.clone();
1901 let readiness_daemon_env = opts.env.clone();
1902 let readiness_resolved_ports = attempt_resolved_ports.clone();
1903 let on_output_hook = opts.on_output_hook.clone();
1904 let has_port_config = opts.port.as_ref().is_some_and(|p| !p.expect.is_empty())
1910 || (settings().proxy.enable && is_daemon_slug_target(id));
1911 let daemon_pid = pid;
1917
1918 #[cfg(unix)]
1922 let pty_reader = pty_pair.map(|p| {
1923 tokio::io::BufReader::new(tokio::fs::File::from_std(std::fs::File::from(p.master)))
1924 });
1925 #[cfg(not(unix))]
1926 let pty_reader: Option<tokio::io::BufReader<tokio::fs::File>> = None;
1927 let stdout_reader = if pty_reader.is_none() {
1928 child.stdout.take().map(tokio::io::BufReader::new)
1929 } else {
1930 None
1931 };
1932 let stderr_reader = if pty_reader.is_none() {
1933 child.stderr.take().map(tokio::io::BufReader::new)
1934 } else {
1935 None
1936 };
1937
1938 if !using_sink
1939 && pty_reader.is_none()
1940 && (stdout_reader.is_none() || stderr_reader.is_none())
1941 {
1942 error!("Failed to capture stdout/stderr for daemon {id}");
1943 }
1944
1945 tokio::spawn(async move {
1946 let id = id_clone;
1947 let _monitored_guard = monitored_guard;
1950 let output_relay = output_relay;
1954 let mut port_claim = port_claim;
1958
1959 let mut output_rx = output_rx;
1962 let status_target = StatusTarget {
1963 id: id.clone(),
1964 token: status_token,
1965 };
1966 let status_target = Some(status_target);
1967
1968 if let Some(reader) = pty_reader {
1969 tokio::spawn(forward_output_lines(
1973 reader,
1974 output_tx,
1975 status_target.clone(),
1976 ));
1977 } else {
1978 if let Some(stdout) = stdout_reader {
1983 tokio::spawn(forward_output_lines(
1984 stdout,
1985 output_tx.clone(),
1986 status_target.clone(),
1987 ));
1988 }
1989 if let Some(stderr) = stderr_reader {
1990 tokio::spawn(forward_output_lines(
1991 stderr,
1992 output_tx.clone(),
1993 status_target.clone(),
1994 ));
1995 }
1996 drop(output_tx);
2000 }
2001 let log_store = Arc::clone(&LOG_STORE);
2002 let log_format = opts
2003 .log_format
2004 .clone()
2005 .unwrap_or_else(|| crate::settings::settings().logs.log_format.clone());
2006 let parse_line = move |line: &str| crate::log_parse::parse(line, &log_format);
2007
2008 const LOG_BATCH_SIZE: usize = 100;
2009 const LOG_FLUSH_INTERVAL: Duration = Duration::from_millis(100);
2010 let mut log_buffer: Vec<crate::log_parse::ParsedLog> =
2011 Vec::with_capacity(LOG_BATCH_SIZE);
2012 let mut pending_log_writes: Vec<tokio::task::JoinHandle<()>> = Vec::new();
2013 let mut log_flush_interval = tokio::time::interval(LOG_FLUSH_INTERVAL);
2014 log_flush_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2015
2016 let flush_logs =
2017 |buffer: &mut Vec<crate::log_parse::ParsedLog>,
2018 pending: &mut Vec<tokio::task::JoinHandle<()>>| {
2019 pending.retain(|handle| !handle.is_finished());
2020 if buffer.is_empty() {
2021 return;
2022 }
2023 let store = Arc::clone(&log_store);
2024 let id = id.clone();
2025 let batch = std::mem::take(buffer);
2026 pending.push(tokio::task::spawn_blocking(move || {
2027 if let Err(e) = store.append_structured_batch(&id, &batch) {
2028 error!("Failed to write batch to log for daemon {id}: {e}");
2029 }
2030 }))
2031 };
2032
2033 let mut ready_notified = false;
2037 let mut oneshot_completion_pending = false;
2042 let mut ready_tx = ready_tx;
2043 let ready_pattern = ready_output
2044 .as_ref()
2045 .and_then(|o| get_or_compile_regex(&o.pattern));
2046 let mut active_port_spawned = false;
2048
2049 let on_output_hook = match on_output_hook {
2053 Some(ref hook) => match hook.validate(id.name()) {
2054 Ok(()) => on_output_hook,
2055 Err(e) => {
2056 error!("{e}");
2057 None
2058 }
2059 },
2060 None => None,
2061 };
2062
2063 let on_output_pattern: Option<regex::Regex> = on_output_hook
2066 .as_ref()
2067 .and_then(|h| h.regex.as_deref().and_then(get_or_compile_regex));
2068 let on_output_debounce = on_output_hook
2069 .as_ref()
2070 .map(|h| h.debounce_duration())
2071 .unwrap_or(Duration::from_millis(1000));
2072 let mut on_output_last_fired: Option<std::time::Instant> = None;
2074
2075 let ready_delay = ready_delay.or_else(|| {
2077 (!opts.oneshot
2078 && ready_output.is_none()
2079 && ready_http.is_none()
2080 && ready_port.is_none()
2081 && ready_cmd.is_none())
2082 .then_some(0)
2083 });
2084 let mut delay_timer =
2085 ready_delay.map(|secs| Box::pin(time::sleep(Duration::from_secs(secs))));
2086
2087 let mut http_exhausted = false;
2089 let mut cmd_exhausted = false;
2090 let mut port_exhausted = false;
2091 let mut output_exhausted = false;
2092
2093 let s = settings();
2095 let ready_check_interval = s.supervisor_ready_check_interval();
2096 let http_client_timeout = s.supervisor_http_client_timeout();
2097
2098 let mut output_deadline = ready_output
2100 .as_ref()
2101 .and_then(|o| o.timeout)
2102 .map(|d| Box::pin(time::sleep(d)));
2103
2104 let mut http_check_interval = ready_http
2106 .as_ref()
2107 .map(|_| tokio::time::interval(ready_check_interval));
2108 let mut http_deadline = ready_http
2109 .as_ref()
2110 .and_then(|h| h.timeout)
2111 .map(|d| Box::pin(time::sleep(d)));
2112 let http_client = if ready_http.is_some() {
2113 Some(crate::supervisor::health::supervisor_http_client().await)
2114 } else {
2115 None
2116 };
2117 let mut http_probe: Option<HttpProbe> = None;
2118
2119 let mut port_check_interval =
2121 ready_port.map(|_| tokio::time::interval(ready_check_interval));
2122 let mut port_deadline = ready_port_config
2123 .as_ref()
2124 .and_then(|p| p.timeout)
2125 .map(|d| Box::pin(time::sleep(d)));
2126 let mut port_probe: Option<PortProbe> = None;
2127
2128 let mut cmd_probe: Option<CmdProbe> = None;
2131 let mut cmd_respawn_delay: Option<_> = None;
2132 let mut cmd_deadline = ready_cmd
2133 .as_ref()
2134 .and_then(|c| c.timeout)
2135 .map(|d| Box::pin(time::sleep(d)));
2136 if let Some(ref cmd) = ready_cmd {
2137 cmd_probe = Some(spawn_cmd_probe(
2138 &id,
2139 &cmd.run,
2140 daemon_dir.as_path(),
2141 hook_retry_count,
2142 readiness_daemon_env.as_ref(),
2143 &readiness_resolved_ports,
2144 ));
2145 }
2146
2147 let (exit_tx, mut exit_rx) =
2149 tokio::sync::mpsc::channel::<std::io::Result<std::process::ExitStatus>>(1);
2150
2151 let child_pid = child.id().unwrap_or(0);
2153 tokio::spawn(async move {
2154 let result = child.wait().await;
2155 #[cfg(all(unix, not(target_os = "linux")))]
2165 let result = match &result {
2166 Err(e) if e.raw_os_error() == Some(nix::libc::ECHILD) => {
2167 if let Some(code) = super::REAPED_STATUSES.lock().await.remove(&child_pid) {
2168 warn!(
2169 "daemon pid {child_pid} wait() got ECHILD; \
2170 recovered exit code {code} from zombie reaper"
2171 );
2172 use std::os::unix::process::ExitStatusExt;
2177 if code >= 0 {
2178 Ok(std::process::ExitStatus::from_raw(code << 8))
2179 } else {
2180 Ok(std::process::ExitStatus::from_raw((-code) & 0x7f))
2182 }
2183 } else {
2184 warn!(
2185 "daemon pid {child_pid} wait() got ECHILD but no \
2186 stashed status found; reporting as error"
2187 );
2188 result
2189 }
2190 }
2191 _ => result,
2192 };
2193 debug!("daemon pid {child_pid} wait() completed with result: {result:?}");
2194 let _ = exit_tx.send(result).await;
2195 });
2196
2197 #[allow(unused_assignments)]
2198 let mut exit_status = None;
2200
2201 if has_port_config
2207 && ready_pattern.is_none()
2208 && ready_http.is_none()
2209 && ready_port.is_none()
2210 && ready_cmd.is_none()
2211 && delay_timer.is_none()
2212 {
2213 active_port_spawned = true;
2214 detect_and_store_active_port(id.clone(), daemon_pid);
2215 }
2216
2217 let mut ready_fail_kill: Option<tokio::task::JoinHandle<Result<bool>>> = None;
2224
2225 loop {
2226 select! {
2228 biased;
2229 Some(result) = exit_rx.recv() => {
2230 exit_status = Some(result);
2232 port_claim.take();
2233 debug!("daemon {id} process exited, exit_status: {exit_status:?}");
2234 if !ready_notified {
2235 let is_success = exit_status.as_ref()
2237 .and_then(|r| r.as_ref().ok())
2238 .map(|s| s.success())
2239 .unwrap_or(false);
2240 if is_success && opts.oneshot {
2241 debug!("daemon {id} completed, deferring success notification until the completed state is persisted");
2242 oneshot_completion_pending = true;
2243 } else if let Some(tx) = ready_tx.take() {
2244 if is_success {
2245 debug!("daemon {id} exited successfully before ready check, sending success notification");
2246 let _ = tx.send(Ok(()));
2247 } else {
2248 let exit_code = exit_status.as_ref()
2249 .and_then(|r| r.as_ref().ok())
2250 .and_then(|s| s.code());
2251 debug!("daemon {id} exited with failure before ready check, sending failure notification with exit_code: {exit_code:?}");
2252 let _ = tx.send(Err(ReadyFailure::Exit(exit_code)));
2253 }
2254 }
2255 } else {
2256 debug!("daemon {id} was already marked ready, not sending notification");
2257 }
2258 break;
2259 },
2260 _ = async {
2261 if let Some(ref mut deadline) = http_deadline {
2262 deadline.await;
2263 } else {
2264 std::future::pending::<()>().await;
2265 }
2266 }, if !ready_notified && ready_http.is_some() => {
2267 http_exhausted = true;
2268 http_deadline = None;
2269 http_check_interval = None;
2270 http_probe = None;
2271 warn!("daemon {id}: HTTP readiness check timed out");
2272 let any_remaining = any_ready_check_remaining(
2273 ready_output.as_ref(),
2274 output_exhausted,
2275 ready_port_config.as_ref(),
2276 port_exhausted,
2277 ready_http.as_ref(),
2278 http_exhausted,
2279 ready_cmd.as_ref(),
2280 cmd_exhausted,
2281 );
2282 if !any_remaining {
2283 error!("daemon {id}: all readiness checks exhausted, failing");
2284 stop_cmd_probe_state(&mut cmd_probe);
2285 ready_fail_kill = Some(spawn_ready_fail_kill(
2286 id.clone(),
2287 daemon_pid,
2288 opts.stop_signal.unwrap_or_default(),
2289 ));
2290 break;
2291 }
2292 }
2293 _ = async {
2294 if let Some(ref mut deadline) = output_deadline {
2295 deadline.await;
2296 } else {
2297 std::future::pending::<()>().await;
2298 }
2299 }, if !ready_notified && ready_output.is_some() => {
2300 output_exhausted = true;
2301 output_deadline = None;
2302 warn!("daemon {id}: output readiness check timed out");
2303 let any_remaining = any_ready_check_remaining(
2304 ready_output.as_ref(),
2305 output_exhausted,
2306 ready_port_config.as_ref(),
2307 port_exhausted,
2308 ready_http.as_ref(),
2309 http_exhausted,
2310 ready_cmd.as_ref(),
2311 cmd_exhausted,
2312 );
2313 if !any_remaining {
2314 error!("daemon {id}: all readiness checks exhausted, failing");
2315 stop_cmd_probe_state(&mut cmd_probe);
2316 ready_fail_kill = Some(spawn_ready_fail_kill(
2317 id.clone(),
2318 daemon_pid,
2319 opts.stop_signal.unwrap_or_default(),
2320 ));
2321 break;
2322 }
2323 }
2324 _ = async {
2325 if let Some(ref mut deadline) = port_deadline {
2326 deadline.await;
2327 } else {
2328 std::future::pending::<()>().await;
2329 }
2330 }, if !ready_notified && ready_port.is_some() => {
2331 port_exhausted = true;
2332 port_deadline = None;
2333 port_check_interval = None;
2334 port_probe = None;
2335 warn!("daemon {id}: TCP port readiness check timed out");
2336 let any_remaining = any_ready_check_remaining(
2337 ready_output.as_ref(),
2338 output_exhausted,
2339 ready_port_config.as_ref(),
2340 port_exhausted,
2341 ready_http.as_ref(),
2342 http_exhausted,
2343 ready_cmd.as_ref(),
2344 cmd_exhausted,
2345 );
2346 if !any_remaining {
2347 error!("daemon {id}: all readiness checks exhausted, failing");
2348 stop_cmd_probe_state(&mut cmd_probe);
2349 ready_fail_kill = Some(spawn_ready_fail_kill(
2350 id.clone(),
2351 daemon_pid,
2352 opts.stop_signal.unwrap_or_default(),
2353 ));
2354 break;
2355 }
2356 }
2357 _ = async {
2358 if let Some(ref mut deadline) = cmd_deadline {
2359 deadline.await;
2360 } else {
2361 std::future::pending::<()>().await;
2362 }
2363 }, if !ready_notified && ready_cmd.is_some() => {
2364 cmd_exhausted = true;
2365 cmd_deadline = None;
2366 stop_cmd_probe_state(&mut cmd_probe);
2367 cmd_respawn_delay = None;
2368 warn!("daemon {id}: command readiness check timed out");
2369 let any_remaining = any_ready_check_remaining(
2370 ready_output.as_ref(),
2371 output_exhausted,
2372 ready_port_config.as_ref(),
2373 port_exhausted,
2374 ready_http.as_ref(),
2375 http_exhausted,
2376 ready_cmd.as_ref(),
2377 cmd_exhausted,
2378 );
2379 if !any_remaining {
2380 error!("daemon {id}: all readiness checks exhausted, failing");
2381 ready_fail_kill = Some(spawn_ready_fail_kill(
2382 id.clone(),
2383 daemon_pid,
2384 opts.stop_signal.unwrap_or_default(),
2385 ));
2386 break;
2387 }
2388 }
2389 _ = async {
2390 if let Some(ref mut timer) = delay_timer {
2391 timer.await;
2392 } else {
2393 std::future::pending::<()>().await;
2394 }
2395 } => {
2396 let has_other_ready_check = ready_pattern.is_some()
2397 || ready_http.is_some()
2398 || ready_port.is_some()
2399 || ready_cmd.is_some();
2400 let delay_is_only_readiness = !ready_notified && !has_other_ready_check;
2401 let process_exited = exit_status.is_some();
2402 let process_running = if delay_is_only_readiness && !process_exited {
2403 PROCS.is_live(daemon_pid)
2406 } else {
2407 false
2408 };
2409
2410 if delay_readiness_succeeded(
2411 ready_notified,
2412 has_other_ready_check,
2413 process_exited,
2414 process_running,
2415 ) {
2416 info!("daemon {id} ready: delay elapsed");
2417 ready_notified = true;
2418 if let Some(tx) = ready_tx.take() {
2419 let _ = tx.send(Ok(()));
2420 }
2421 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2422 if !active_port_spawned && has_port_config {
2423 active_port_spawned = true;
2424 detect_and_store_active_port(id.clone(), daemon_pid);
2425 }
2426 } else if delay_is_only_readiness {
2427 if process_exited {
2428 debug!("daemon {id} exited during ready_delay, not marking as ready");
2429 } else {
2430 debug!("daemon {id} pid {daemon_pid} not running during ready_delay, deferring to exit handler");
2431 }
2432 }
2433
2434 if delay_is_only_readiness {
2435 output_deadline = None;
2438 http_deadline = None;
2439 cmd_deadline = None;
2440 port_deadline = None;
2441 stop_cmd_probe_state(&mut cmd_probe);
2442 }
2443 delay_timer = None;
2445 }
2446 _ = async {
2447 if let Some(ref mut interval) = http_check_interval {
2448 interval.tick().await;
2449 } else {
2450 std::future::pending::<()>().await;
2451 }
2452 }, if !ready_notified && ready_http.is_some() && !http_exhausted && http_probe.is_none() => {
2453 if let (Some(http), Some(client)) = (&ready_http, &http_client) {
2454 http_probe = Some(Box::pin(client.get(&http.url).timeout(http_client_timeout).send()));
2455 }
2456 }
2457 result = async {
2458 if let Some(probe) = http_probe.as_mut() {
2459 probe.as_mut().await
2460 } else {
2461 std::future::pending::<std::result::Result<reqwest::Response, reqwest::Error>>().await
2462 }
2463 }, if !ready_notified && http_probe.is_some() => {
2464 http_probe = None;
2465 if let Some(http) = &ready_http {
2466 match result {
2467 Ok(response) if http.accepts_status(response.status().as_u16()) => {
2468 info!("daemon {id} ready: HTTP check passed (status {})", response.status());
2469 ready_notified = true;
2470 if let Some(tx) = ready_tx.take() {
2471 let _ = tx.send(Ok(()));
2472 }
2473 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2474 http_check_interval = None;
2475 http_deadline = None;
2476 stop_cmd_probe_state(&mut cmd_probe);
2477 cmd_deadline = None;
2478 port_deadline = None;
2479 output_deadline = None;
2480 if !active_port_spawned && has_port_config {
2481 active_port_spawned = true;
2482 detect_and_store_active_port(id.clone(), daemon_pid);
2483 }
2484 }
2485 Ok(response) => {
2486 trace!("daemon {id} HTTP check: status {} (not ready)", response.status());
2487 }
2488 Err(e) => {
2489 trace!("daemon {id} HTTP check failed: {e}");
2490 }
2491 }
2492 }
2493 }
2494 _ = async {
2495 if let Some(ref mut interval) = port_check_interval {
2496 interval.tick().await;
2497 } else {
2498 std::future::pending::<()>().await;
2499 }
2500 }, if !ready_notified && ready_port.is_some() && !port_exhausted && port_probe.is_none() => {
2501 if let Some(port) = ready_port {
2502 port_probe = Some(Box::pin(tokio::net::TcpStream::connect(("127.0.0.1", port))));
2503 }
2504 }
2505 result = async {
2506 if let Some(probe) = port_probe.as_mut() {
2507 probe.as_mut().await
2508 } else {
2509 std::future::pending::<std::io::Result<tokio::net::TcpStream>>().await
2510 }
2511 }, if !ready_notified && port_probe.is_some() => {
2512 port_probe = None;
2513 if let Some(port) = ready_port {
2514 match result {
2515 Ok(_) => {
2516 info!("daemon {id} ready: TCP port {port} is listening");
2517 ready_notified = true;
2518 if let Some(tx) = ready_tx.take() {
2519 let _ = tx.send(Ok(()));
2520 }
2521 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2522 port_check_interval = None;
2524 port_deadline = None;
2525 stop_cmd_probe_state(&mut cmd_probe);
2526 http_deadline = None;
2527 cmd_deadline = None;
2528 output_deadline = None;
2529 if !active_port_spawned && has_port_config {
2530 active_port_spawned = true;
2531 if let Some(active_port) = active_port_from_ready_port(
2541 port,
2542 &readiness_resolved_ports,
2543 ) {
2544 let mut state_file =
2545 SUPERVISOR.state_file.lock().await;
2546 if let Some(d) = state_file.daemons.get(&id)
2547 && d.pid == Some(daemon_pid)
2548 {
2549 state_file.set_active_port(&id, active_port);
2550 }
2551 } else {
2552 detect_and_store_active_port(
2553 id.clone(),
2554 daemon_pid,
2555 );
2556 }
2557 }
2558 }
2559 Err(_) => {
2560 trace!("daemon {id} port check: port {port} not listening yet");
2561 }
2562 }
2563 }
2564 }
2565 _ = async {
2566 if let Some(ref mut delay) = cmd_respawn_delay {
2567 delay.await;
2568 } else {
2569 std::future::pending::<()>().await;
2570 }
2571 }, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted && cmd_probe.is_none() => {
2572 if let Some(ref cmd) = ready_cmd {
2573 cmd_probe = Some(spawn_cmd_probe(
2574 &id,
2575 &cmd.run,
2576 daemon_dir.as_path(),
2577 hook_retry_count,
2578 readiness_daemon_env.as_ref(),
2579 &readiness_resolved_ports,
2580 ));
2581 }
2582 cmd_respawn_delay = None;
2583 }
2584 result = async {
2585 if let Some(probe) = cmd_probe.as_mut() {
2586 std::pin::Pin::new(&mut probe.result_rx).await
2587 } else {
2588 std::future::pending::<Result<Result<std::process::ExitStatus, std::io::Error>, tokio::sync::oneshot::error::RecvError>>().await
2589 }
2590 }, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted => {
2591 let _ = cmd_probe.take();
2595 match result {
2596 Ok(Ok(status)) if status.success() => {
2597 info!("daemon {id} ready: readiness command succeeded");
2598 ready_notified = true;
2599 if let Some(tx) = ready_tx.take() {
2600 let _ = tx.send(Ok(()));
2601 }
2602 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2603 cmd_respawn_delay = None;
2604 cmd_deadline = None;
2605 http_deadline = None;
2606 port_deadline = None;
2607 output_deadline = None;
2608 if !active_port_spawned && has_port_config {
2609 active_port_spawned = true;
2610 detect_and_store_active_port(id.clone(), daemon_pid);
2611 }
2612 }
2613 Ok(Ok(_)) | Ok(Err(_)) | Err(_) => {
2614 trace!("daemon {id} cmd check: command not ready, will respawn");
2615 cmd_respawn_delay = Some(Box::pin(time::sleep(ready_check_interval)));
2616 }
2617 }
2618 }
2619 Some(super::OutputLine { text: line, source }) = output_rx.recv() => {
2620 if matches!(source, super::OutputSource::Local) {
2624 let parsed = parse_line(&line);
2625 log_buffer.push(parsed);
2626 if log_buffer.len() >= LOG_BATCH_SIZE {
2627 flush_logs(&mut log_buffer, &mut pending_log_writes);
2628 }
2629 }
2630 trace!("output: {id} {line}");
2631
2632 let line_clean = console::strip_ansi_codes(&line).to_string();
2635
2636 if !ready_notified
2638 && !output_exhausted
2639 && let Some(ref pattern) = ready_pattern
2640 && pattern.is_match(&line_clean)
2641 {
2642 flush_logs(&mut log_buffer, &mut pending_log_writes);
2647 for handle in pending_log_writes.drain(..) {
2648 let _ = handle.await;
2649 }
2650 info!("daemon {id} ready: output matched pattern");
2651 ready_notified = true;
2652 if let Some(tx) = ready_tx.take() {
2653 let _ = tx.send(Ok(()));
2654 }
2655 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2656 stop_cmd_probe_state(&mut cmd_probe);
2657 http_deadline = None;
2658 cmd_deadline = None;
2659 port_deadline = None;
2660 output_deadline = None;
2661 if !active_port_spawned && has_port_config {
2662 active_port_spawned = true;
2663 detect_and_store_active_port(id.clone(), daemon_pid);
2664 }
2665 }
2666
2667 if let Some(ref hook) = on_output_hook {
2672 let matched = match source {
2673 super::OutputSource::Sink { fires_hook } => fires_hook,
2674 super::OutputSource::Local => match (&hook.filter, &on_output_pattern) {
2675 (Some(substr), _) => line_clean.contains(substr.as_str()),
2676 (None, Some(re)) => re.is_match(&line_clean),
2677 (None, None) => true,
2678 },
2679 };
2680 if matched {
2681 let now = std::time::Instant::now();
2686 let elapsed = on_output_last_fired.map(|t| now.duration_since(t));
2687 if elapsed.is_none_or(|e| e >= on_output_debounce) {
2688 on_output_last_fired = Some(now);
2689 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;
2690 }
2691 }
2692 }
2693 tokio::task::yield_now().await;
2695 }
2696 _ = log_flush_interval.tick() => {
2697 flush_logs(&mut log_buffer, &mut pending_log_writes);
2698 }
2699 }
2700 if ready_notified {
2701 http_probe = None;
2702 port_probe = None;
2703 }
2704 }
2705 drop(http_probe);
2706 drop(port_probe);
2707
2708 let pre_drain_daemon = SUPERVISOR.get_daemon(&id).await;
2722 let pre_drain_is_stopping = pre_drain_daemon
2723 .as_ref()
2724 .is_some_and(|d| d.status.is_stopped() || d.status.is_stopping_or_restarting());
2725
2726 drop(output_relay);
2739 let drain_deadline = tokio::time::Instant::now() + super::EXIT_OUTPUT_DRAIN_TIMEOUT;
2740 loop {
2741 let now = tokio::time::Instant::now();
2742 if now >= drain_deadline {
2743 break;
2744 }
2745 let Ok(Some(line)) =
2746 tokio::time::timeout(drain_deadline - now, output_rx.recv()).await
2747 else {
2748 break;
2749 };
2750 if matches!(line.source, super::OutputSource::Local) {
2752 log_buffer.push(parse_line(&line.text));
2753 }
2754 }
2755 flush_logs(&mut log_buffer, &mut pending_log_writes);
2758 for handle in pending_log_writes {
2759 let _ = handle.await;
2760 }
2761
2762 {
2764 let mut state_file = SUPERVISOR.state_file.lock().await;
2765 state_file.clear_active_port(&id);
2766 if super::log_sink::is_current_attempt(&id, status_token) {
2767 state_file.drop_live_program_status(&id);
2768 }
2769 }
2770
2771 let readiness_failed = ready_fail_kill.is_some();
2772 let mut termination_error = None;
2773 if let Some(kill) = ready_fail_kill {
2774 let result = kill.await.into_diagnostic().and_then(|result| result);
2775 let failure = match result {
2776 Ok(_) => {
2777 port_claim.take();
2779 ReadyFailure::Exit(Some(124))
2780 }
2781 Err(error) => {
2782 let error = format!(
2783 "failed to terminate daemon {id} after readiness failure: {error}"
2784 );
2785 error!("{error}");
2786 let mut state_file = SUPERVISOR.state_file.lock().await;
2787 if state_file.daemons.get(&id).is_some_and(|daemon| {
2788 daemon.pid == Some(pid)
2789 && !daemon.status.is_stopped()
2790 && !daemon.status.is_stopping_or_restarting()
2791 }) {
2792 state_file.set_status(&id, DaemonStatus::Failed(error.clone()));
2793 }
2794 termination_error = Some(error.clone());
2795 ReadyFailure::Termination(error)
2796 }
2797 };
2798 if let Some(tx) = ready_tx.take() {
2799 let _ = tx.send(Err(failure));
2800 }
2801 }
2802
2803 if termination_error.is_some() {
2807 while PROCS.process_group_alive(daemon_pid) {
2808 time::sleep(Duration::from_millis(100)).await;
2810 }
2811 }
2812
2813 let exit_status = if let Some(status) = exit_status {
2815 status
2816 } else {
2817 match exit_rx.recv().await {
2819 Some(status) => status,
2820 None => {
2821 warn!("daemon {id} exit channel closed without receiving status");
2822 Err(std::io::Error::other("exit channel closed"))
2823 }
2824 }
2825 };
2826
2827 let current_daemon = SUPERVISOR.get_daemon(&id).await;
2828
2829 SUPERVISOR
2834 .active_monitors
2835 .fetch_add(1, atomic::Ordering::Release);
2836 struct MonitorGuard;
2837 impl Drop for MonitorGuard {
2838 fn drop(&mut self) {
2839 SUPERVISOR
2840 .active_monitors
2841 .fetch_sub(1, atomic::Ordering::Release);
2842 SUPERVISOR.monitor_done.notify_waiters();
2843 }
2844 }
2845 let _monitor_guard = MonitorGuard;
2846 if !pre_drain_is_stopping
2851 && (current_daemon.is_none()
2852 || current_daemon.as_ref().is_some_and(|d| {
2853 d.pid != Some(pid)
2854 && !d.status.is_stopped()
2855 && !d.status.is_stopping_or_restarting()
2856 }))
2857 {
2858 if oneshot_completion_pending && let Some(tx) = ready_tx.take() {
2862 let _ = tx.send(Ok(()));
2863 }
2864 return;
2865 }
2866 let already_stopped = current_daemon
2871 .as_ref()
2872 .is_some_and(|d| d.status.is_stopped());
2873 let is_stopping = already_stopped
2874 || pre_drain_is_stopping
2875 || current_daemon
2876 .as_ref()
2877 .is_some_and(|d| d.status.is_stopping_or_restarting());
2878
2879 let (exit_code, exit_reason) = match (&exit_status, is_stopping) {
2881 (Ok(status), true) => {
2882 (status.code().unwrap_or(-1), "stop")
2886 }
2887 (_, false) if readiness_failed => (124, "fail"),
2888 (Ok(status), false) if status.success() => (status.code().unwrap_or(-1), "exit"),
2889 (Ok(status), false) => (status.code().unwrap_or(-1), "fail"),
2890 (Err(_), true) => {
2891 (-1, "stop")
2893 }
2894 (Err(_), false) => (-1, "fail"),
2895 };
2896 if !already_stopped && !pre_drain_is_stopping {
2908 if let Ok(status) = &exit_status {
2909 info!("daemon {id} exited with status {status}");
2910 }
2911 let (mut new_status, last_exit_success) = terminal_exit_state(
2912 exit_reason,
2913 opts.oneshot,
2914 exit_code,
2915 exit_status.as_ref().map(|s| s.success()).unwrap_or(true),
2916 );
2917 if !is_stopping && let Some(error) = &termination_error {
2918 new_status = DaemonStatus::Failed(error.clone());
2919 }
2920 if !SUPERVISOR
2926 .finalize_monitored_exit(
2927 &id,
2928 pid,
2929 monitor_token,
2930 new_status,
2931 Some(last_exit_success),
2932 )
2933 .await
2934 {
2935 debug!("daemon {id} exit state was not written; a successor owns the record");
2936 }
2937 }
2938
2939 if oneshot_completion_pending && let Some(tx) = ready_tx.take() {
2944 if exit_reason == "exit" {
2945 let _ = tx.send(Ok(()));
2946 } else {
2947 warn!("daemon {id}: oneshot was stopped before completing");
2948 let _ = tx.send(Err(ReadyFailure::Exit(None)));
2949 }
2950 }
2951
2952 let hook_extra_env = vec![
2954 ("PITCHFORK_EXIT_CODE".to_string(), exit_code.to_string()),
2955 ("PITCHFORK_EXIT_REASON".to_string(), exit_reason.to_string()),
2956 ];
2957
2958 let hooks_to_fire: Vec<HookType> = match exit_reason {
2960 "stop" => vec![HookType::OnStop, HookType::OnExit],
2961 "exit" => vec![HookType::OnExit],
2962 _ if termination_error.is_some() || hook_retry_count >= hook_retry.count() => {
2964 vec![HookType::OnFail, HookType::OnExit]
2965 }
2966 _ => vec![],
2967 };
2968
2969 for hook_type in hooks_to_fire {
2970 fire_hook(
2971 hook_type,
2972 id.clone(),
2973 hook_dirs.clone(),
2974 hook_retry_count,
2975 hook_daemon_env.clone(),
2976 hook_resolved_ports.clone(),
2977 hook_extra_env.clone(),
2978 )
2979 .await;
2980 }
2981 });
2982
2983 if let Some(ready_rx) = ready_rx {
2984 let wait_ready = opts.wait_ready;
2985 let oneshot = opts.oneshot;
2986 let last_attempt = opts.retry_count >= opts.retry.count();
2987 let started = IpcResponse::DaemonStart {
2988 daemon: daemon.clone(),
2989 };
2990 let ready = async move {
2991 let id = daemon.id.clone();
2992 let ready = ready_rx.await;
2993 SUPERVISOR.end_ready_check(&id, &attempt_rx);
2994 match ready {
2995 Ok(Ok(())) => {
2996 info!("daemon {id} is ready");
2997 let daemon = match SUPERVISOR.get_daemon(&id).await {
3007 Some(current) if current.pid.is_none() || current.pid == Some(pid) => {
3008 current
3009 }
3010 _ if oneshot => crate::daemon::Daemon {
3017 status: DaemonStatus::Completed,
3018 pid: None,
3019 start_time: None,
3020 boot_time: None,
3021 last_exit_success: Some(true),
3022 ..daemon
3023 },
3024 _ => daemon,
3025 };
3026 IpcResponse::DaemonReady { daemon }
3027 }
3028 Ok(Err(ReadyFailure::Exit(exit_code))) => {
3029 error!("daemon {id} failed before becoming ready");
3030 if using_sink && last_attempt {
3041 super::log_sink::wait_for_output(&id, spawn_time, SINK_OUTPUT_TIMEOUT)
3042 .await;
3043 }
3044 IpcResponse::DaemonFailedWithCode {
3045 exit_code,
3046 resolved_ports: attempt_resolved_ports,
3047 }
3048 }
3049 Ok(Err(ReadyFailure::Termination(error))) => {
3050 IpcResponse::DaemonFailed { error }
3051 }
3052 Err(_) => {
3053 error!("readiness channel closed unexpectedly for daemon {id}");
3054 IpcResponse::DaemonStart { daemon }
3055 }
3056 }
3057 };
3058 let completion = tokio::spawn(async move {
3059 let response = ready.await;
3060 attempt_tx.send_replace(Some(response.clone()));
3061 response
3062 });
3063 if wait_ready {
3064 completion.await.into_diagnostic()
3065 } else {
3066 Ok(started)
3067 }
3068 } else {
3069 Ok(IpcResponse::DaemonStart { daemon })
3070 }
3071 }
3072
3073 pub async fn stop(&self, id: &DaemonId) -> Result<IpcResponse> {
3075 let lock = self.stop_lock(id).await;
3079 let _guard = lock.lock().await;
3080 self.stop_locked(id).await
3081 }
3082
3083 pub(crate) async fn stop_for_restart(&self, id: &DaemonId) -> Result<IpcResponse> {
3090 let lock = self.stop_lock(id).await;
3091 let _guard = lock.lock().await;
3092 self.stop_locked_with(id, true).await
3093 }
3094
3095 pub(super) async fn stop_locked(&self, id: &DaemonId) -> Result<IpcResponse> {
3097 self.stop_locked_with(id, false).await
3098 }
3099
3100 pub(super) async fn stop_locked_with(
3107 &self,
3108 id: &DaemonId,
3109 restarting: bool,
3110 ) -> Result<IpcResponse> {
3111 let (stopping_status, stopped_status) = if restarting {
3112 (DaemonStatus::Restarting, DaemonStatus::Restarting)
3113 } else {
3114 (DaemonStatus::Stopping, DaemonStatus::Stopped)
3115 };
3116 let pitchfork_id = DaemonId::pitchfork();
3117 if *id == pitchfork_id {
3118 return Ok(IpcResponse::Error(
3119 "Cannot stop supervisor via stop command".into(),
3120 ));
3121 }
3122 info!("stopping daemon: {id}");
3123 self.cancel_retrying(id);
3128 let _stop_epoch_bump = StopEpochGuard(id.clone());
3136 if let Some(daemon) = self.get_daemon(id).await {
3137 trace!("daemon to stop: {daemon}");
3138 if let Some(pid) = daemon.pid {
3139 trace!("killing pid: {pid}");
3140 if PROCS.is_running(pid) {
3141 if !super::signalling_pid_is_authorized(
3147 daemon.start_time,
3148 PROCS.start_time(pid),
3149 ) {
3150 warn!(
3151 "pid {pid} recorded for daemon {id} belongs to another process now; not signalling it"
3152 );
3153 self.upsert_daemon(
3154 UpsertDaemonOpts::builder(id.clone())
3155 .set(|o| {
3156 o.pid = None;
3157 o.status = stopped_status.clone();
3158 })
3159 .build(),
3160 )
3161 .await?;
3162 return Ok(IpcResponse::DaemonWasNotRunning);
3163 }
3164
3165 self.upsert_daemon(
3167 UpsertDaemonOpts::builder(id.clone())
3168 .set(|o| {
3169 o.pid = Some(pid);
3170 o.status = stopping_status.clone();
3171 })
3172 .build(),
3173 )
3174 .await?;
3175
3176 let stop_cfg = daemon.stop_signal.unwrap_or_default();
3179 let stop_signal: i32 = stop_cfg.signal.into();
3180 if let Err(e) = PROCS
3181 .kill_process_group_async(pid, stop_signal, stop_cfg.timeout)
3182 .await
3183 {
3184 debug!("failed to kill pid {pid}: {e}");
3185 if PROCS.process_group_alive(pid) {
3191 debug!(
3193 "failed to stop pid {pid}: process group still alive after kill"
3194 );
3195 self.upsert_daemon(
3196 UpsertDaemonOpts::builder(id.clone())
3197 .set(|o| {
3198 o.pid = Some(pid); o.status = DaemonStatus::Running;
3200 })
3201 .build(),
3202 )
3203 .await?;
3204 return Ok(IpcResponse::DaemonStopFailed {
3205 error: format!(
3206 "process group of {pid} still alive after kill attempt: {e}"
3207 ),
3208 });
3209 }
3210 #[cfg(windows)]
3215 {
3216 self.upsert_daemon(
3217 UpsertDaemonOpts::builder(id.clone())
3218 .set(|o| {
3219 o.pid = None;
3220 o.status = stopped_status.clone();
3221 o.last_exit_success = Some(true);
3222 })
3223 .build(),
3224 )
3225 .await?;
3226 return Ok(IpcResponse::DaemonStopFailed {
3227 error: format!("{e}"),
3228 });
3229 }
3230 }
3231
3232 self.upsert_daemon(
3240 UpsertDaemonOpts::builder(id.clone())
3241 .set(|o| {
3242 o.pid = None;
3243 o.status = stopped_status.clone();
3244 o.last_exit_success = Some(true);
3245 })
3246 .build(),
3247 )
3248 .await?;
3249 } else if daemon.oneshot && self.is_monitored(id, pid) {
3250 debug!(
3270 "pid {pid} not running but daemon {id} is still monitored; waiting for its monitor to settle the outcome"
3271 );
3272 self.wait_for_exit_finalized(id, Some(pid)).await;
3273 let finished = self.get_daemon(id).await;
3274 if finished
3275 .as_ref()
3276 .is_some_and(|d| stop_keeps_finalized_status(&d.status))
3277 {
3278 return Ok(IpcResponse::DaemonWasNotRunning);
3279 }
3280 self.upsert_daemon(
3284 UpsertDaemonOpts::builder(id.clone())
3285 .set(|o| {
3286 o.pid = None;
3287 o.status = stopped_status.clone();
3288 })
3289 .build(),
3290 )
3291 .await?;
3292 return Ok(IpcResponse::DaemonWasNotRunning);
3293 } else {
3294 debug!("pid {pid} not running, process may have exited unexpectedly");
3295 self.upsert_daemon(
3302 UpsertDaemonOpts::builder(id.clone())
3303 .set(|o| {
3304 o.pid = None;
3305 o.status = stopped_status.clone();
3306 })
3307 .build(),
3308 )
3309 .await?;
3310 return Ok(IpcResponse::DaemonWasNotRunning);
3311 }
3312 Ok(IpcResponse::Ok)
3313 } else {
3314 debug!("daemon {id} not running");
3315 if !restarting && daemon.status.is_restarting() {
3320 self.upsert_daemon(
3321 UpsertDaemonOpts::builder(id.clone())
3322 .set(|o| {
3323 o.pid = None;
3324 o.status = DaemonStatus::Stopped;
3325 })
3326 .build(),
3327 )
3328 .await?;
3329 return Ok(IpcResponse::Ok);
3330 }
3331 if daemon.status.is_errored() && daemon.retry_count < daemon.retry.count() {
3336 self.upsert_daemon(
3337 UpsertDaemonOpts::builder(id.clone())
3338 .set(|o| {
3339 o.pid = None;
3340 o.status = stopped_status.clone();
3341 })
3342 .build(),
3343 )
3344 .await?;
3345 return Ok(IpcResponse::DaemonWasNotRunning);
3346 }
3347 Ok(IpcResponse::DaemonNotRunning)
3348 }
3349 } else {
3350 debug!("daemon {id} not found");
3351 Ok(IpcResponse::DaemonNotFound)
3352 }
3353 }
3354}
3355
3356#[cfg(unix)]
3357fn resolve_effective_run_identity(daemon_user: Option<&str>) -> Result<RunIdentity> {
3358 let s = settings();
3359 let settings_user = s.supervisor.user.trim();
3360 let daemon_user = daemon_user.map(str::trim).filter(|user| !user.is_empty());
3361 let settings_user = (!settings_user.is_empty()).then_some(settings_user);
3362 let configured = daemon_user.or(settings_user);
3363 let current_uid = nix::unistd::Uid::effective().as_raw();
3364 let current_gid = nix::unistd::Gid::effective().as_raw();
3365 let invoking = env::invoking_user_ids().map(|(uid, gid)| (uid.to_string(), gid.to_string()));
3368 resolve_run_identity(
3369 configured,
3370 current_uid,
3371 current_gid,
3372 invoking.as_ref().map(|(uid, _)| uid.as_str()),
3373 invoking.as_ref().map(|(_, gid)| gid.as_str()),
3374 )
3375}
3376
3377#[cfg(unix)]
3378fn resolve_run_identity(
3379 configured: Option<&str>,
3380 current_uid: u32,
3381 current_gid: u32,
3382 sudo_uid: Option<&str>,
3383 sudo_gid: Option<&str>,
3384) -> Result<RunIdentity> {
3385 let current_uid = nix::unistd::Uid::from_raw(current_uid);
3386 let current_gid = nix::unistd::Gid::from_raw(current_gid);
3387 if let Some(user) = configured {
3388 let identity = resolve_configured_user(user)?;
3389 ensure_can_use_identity(user, &identity, current_uid, current_gid)?;
3390 if identity.matches(current_uid, current_gid) {
3391 return Ok(RunIdentity::Inherit);
3392 }
3393 return Ok(identity);
3394 }
3395
3396 if current_uid.is_root()
3397 && let Some(identity) = resolve_sudo_identity(sudo_uid, sudo_gid)
3398 {
3399 if identity.matches(current_uid, current_gid) {
3400 return Ok(RunIdentity::Inherit);
3401 }
3402 return Ok(identity);
3403 }
3404
3405 Ok(RunIdentity::Inherit)
3406}
3407
3408#[cfg(unix)]
3409fn resolve_configured_user(user: &str) -> Result<RunIdentity> {
3410 if user.chars().all(|c| c.is_ascii_digit()) {
3411 let uid = user
3412 .parse::<u32>()
3413 .map_err(|e| miette::miette!("invalid run user UID '{}': {}", user, e))?;
3414 let user_record = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
3415 .into_diagnostic()?
3416 .ok_or_else(|| miette::miette!("run user UID '{}' does not exist", user))?;
3417 return run_identity_from_user_record(user_record);
3418 }
3419
3420 let user_record = nix::unistd::User::from_name(user)
3421 .into_diagnostic()?
3422 .ok_or_else(|| miette::miette!("run user '{}' does not exist", user))?;
3423 run_identity_from_user_record(user_record)
3424}
3425
3426#[cfg(unix)]
3427fn run_identity_from_user_record(user: nix::unistd::User) -> Result<RunIdentity> {
3428 let username = CString::new(user.name)
3429 .map_err(|e| miette::miette!("run user name contains an interior nul byte: {}", e))?;
3430 Ok(RunIdentity::Switch {
3431 uid: user.uid,
3432 gid: user.gid,
3433 username: Some(username),
3434 home: Some(user.dir),
3435 })
3436}
3437
3438#[cfg(unix)]
3439fn resolve_sudo_identity(sudo_uid: Option<&str>, sudo_gid: Option<&str>) -> Option<RunIdentity> {
3440 let uid = sudo_uid?.parse::<u32>().ok()?;
3441 let gid = sudo_gid?.parse::<u32>().ok()?;
3442 let user = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
3443 .ok()
3444 .flatten();
3445 let (username, home) = match user {
3446 Some(user) => (CString::new(user.name).ok(), Some(user.dir)),
3447 None => (None, None),
3448 };
3449 Some(RunIdentity::Switch {
3450 uid: nix::unistd::Uid::from_raw(uid),
3451 gid: nix::unistd::Gid::from_raw(gid),
3452 username,
3453 home,
3454 })
3455}
3456
3457#[cfg(unix)]
3458fn ensure_can_use_identity(
3459 configured_user: &str,
3460 identity: &RunIdentity,
3461 current_uid: nix::unistd::Uid,
3462 current_gid: nix::unistd::Gid,
3463) -> Result<()> {
3464 let RunIdentity::Switch { uid, gid, .. } = identity else {
3465 return Ok(());
3466 };
3467 if *uid == current_uid && *gid == current_gid {
3468 return Ok(());
3469 }
3470 if current_uid.is_root() {
3471 return Ok(());
3472 }
3473 Err(miette::miette!(
3474 "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.",
3475 configured_user,
3476 current_uid.as_raw(),
3477 current_gid.as_raw(),
3478 uid.as_raw(),
3479 gid.as_raw()
3480 ))
3481}
3482
3483#[cfg(unix)]
3490fn apply_identity_env(command: &mut tokio::process::Command, identity: &RunIdentity) {
3491 let RunIdentity::Switch { username, home, .. } = identity else {
3492 return;
3493 };
3494 match home.as_ref().filter(|home| !home.as_os_str().is_empty()) {
3495 Some(home) => command.env("HOME", home),
3496 None => command.env_remove("HOME"),
3497 };
3498 match username.as_ref().and_then(|name| name.to_str().ok()) {
3499 Some(name) => command.env("USER", name).env("LOGNAME", name),
3500 None => command.env_remove("USER").env_remove("LOGNAME"),
3501 };
3502}
3503
3504#[cfg(unix)]
3505fn apply_run_identity(identity: &RunIdentity) -> std::io::Result<()> {
3506 let RunIdentity::Switch {
3507 uid, gid, username, ..
3508 } = identity
3509 else {
3510 return Ok(());
3511 };
3512 if let Some(username) = username {
3513 initgroups_for_user(username, *gid)?;
3514 } else {
3515 setgroups_to_primary(*gid)?;
3516 }
3517 nix::unistd::setgid(*gid).map_err(nix_to_io_error)?;
3518 nix::unistd::setuid(*uid).map_err(nix_to_io_error)?;
3519 Ok(())
3520}
3521
3522#[cfg(unix)]
3523impl RunIdentity {
3524 fn matches(&self, uid: nix::unistd::Uid, gid: nix::unistd::Gid) -> bool {
3525 matches!(self, RunIdentity::Switch { uid: u, gid: g, .. } if *u == uid && *g == gid)
3526 }
3527}
3528
3529#[cfg(unix)]
3530fn setgroups_to_primary(gid: nix::unistd::Gid) -> std::io::Result<()> {
3531 let groups = [gid.as_raw() as libc::gid_t];
3532 #[cfg(any(target_os = "linux", target_os = "android"))]
3533 let group_count = groups.len();
3534 #[cfg(not(any(target_os = "linux", target_os = "android")))]
3535 let group_count = groups.len() as libc::c_int;
3536 let rc = unsafe { libc::setgroups(group_count, groups.as_ptr()) };
3537 if rc == -1 {
3538 Err(std::io::Error::last_os_error())
3539 } else {
3540 Ok(())
3541 }
3542}
3543
3544#[cfg(unix)]
3545fn initgroups_for_user(username: &CString, gid: nix::unistd::Gid) -> std::io::Result<()> {
3546 let gid = gid.as_raw();
3547 #[cfg(any(
3548 target_os = "macos",
3549 target_os = "ios",
3550 target_os = "tvos",
3551 target_os = "watchos"
3552 ))]
3553 let base_gid = i32::try_from(gid)
3554 .map_err(|_| std::io::Error::other(format!("gid {gid} is out of range")))?;
3555
3556 #[cfg(not(any(
3557 target_os = "macos",
3558 target_os = "ios",
3559 target_os = "tvos",
3560 target_os = "watchos"
3561 )))]
3562 let base_gid = gid as libc::gid_t;
3563
3564 let rc = unsafe { libc::initgroups(username.as_ptr(), base_gid) };
3567 if rc == -1 {
3568 Err(std::io::Error::last_os_error())
3569 } else {
3570 Ok(())
3571 }
3572}
3573
3574#[cfg(unix)]
3575fn nix_to_io_error(err: nix::errno::Errno) -> std::io::Error {
3576 std::io::Error::from_raw_os_error(err as i32)
3577}
3578
3579static PORT_CLAIMS: Lazy<std::sync::Mutex<HashMap<u16, (DaemonId, u64)>>> =
3587 Lazy::new(|| std::sync::Mutex::new(HashMap::new()));
3588
3589static PORT_RESOLUTION: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
3591
3592static PORT_CLAIM_GENERATION: atomic::AtomicU64 = atomic::AtomicU64::new(0);
3594
3595#[derive(Debug)]
3597struct PortClaim {
3598 generation: u64,
3599 ports: Vec<u16>,
3600}
3601
3602impl Drop for PortClaim {
3603 fn drop(&mut self) {
3604 let mut claims = PORT_CLAIMS.lock().unwrap_or_else(|e| e.into_inner());
3605 for port in &self.ports {
3606 if claims.get(port).is_some_and(|(_, g)| *g == self.generation) {
3608 claims.remove(port);
3609 }
3610 }
3611 }
3612}
3613
3614async fn claim_ports(
3621 id: &DaemonId,
3622 expected_ports: &[u16],
3623 auto_bump: bool,
3624 max_attempts: u32,
3625) -> Result<(Vec<u16>, PortClaim)> {
3626 let _resolution = PORT_RESOLUTION.lock().await;
3627 let claimed: HashMap<u16, DaemonId> = PORT_CLAIMS
3628 .lock()
3629 .unwrap_or_else(|e| e.into_inner())
3630 .iter()
3631 .filter(|(_, (owner, _))| owner != id)
3632 .map(|(port, (owner, _))| (*port, owner.clone()))
3633 .collect();
3634 let resolved = check_ports_available(expected_ports, auto_bump, max_attempts, &claimed).await?;
3635 let ports: Vec<u16> = resolved.iter().copied().filter(|&p| p != 0).collect();
3636 let generation = PORT_CLAIM_GENERATION.fetch_add(1, atomic::Ordering::Relaxed);
3637 {
3638 let mut claims = PORT_CLAIMS.lock().unwrap_or_else(|e| e.into_inner());
3639 for port in &ports {
3640 claims.insert(*port, (id.clone(), generation));
3641 }
3642 }
3643 Ok((resolved, PortClaim { generation, ports }))
3644}
3645
3646async fn check_ports_available(
3647 expected_ports: &[u16],
3648 auto_bump: bool,
3649 max_attempts: u32,
3650 claimed: &HashMap<u16, DaemonId>,
3651) -> Result<Vec<u16>> {
3652 if expected_ports.is_empty() {
3653 return Ok(Vec::new());
3654 }
3655
3656 for bump_offset in 0..=max_attempts {
3657 let candidate_ports: Vec<u16> = expected_ports
3659 .iter()
3660 .map(|&p| p.wrapping_add(bump_offset as u16))
3661 .collect();
3662
3663 let mut all_available = true;
3665 let mut conflicting_port = None;
3666 let mut conflicting_claim = None;
3667
3668 for &port in &candidate_ports {
3669 if port == 0 {
3672 continue;
3673 }
3674
3675 if let Some(owner) = claimed.get(&port) {
3689 all_available = false;
3690 conflicting_claim = Some((port, owner.clone()));
3691 break;
3692 }
3693 if let Some(address) = port_bind_conflict(port).await {
3694 all_available = false;
3695 conflicting_port = Some((port, address));
3696 break;
3697 }
3698 }
3699
3700 if all_available {
3701 if candidate_ports.contains(&0) && !expected_ports.contains(&0) {
3705 return Err(PortError::NoAvailablePort {
3706 start_port: expected_ports[0],
3707 attempts: bump_offset + 1,
3708 }
3709 .into());
3710 }
3711 if bump_offset > 0 {
3712 info!("ports {expected_ports:?} bumped by {bump_offset} to {candidate_ports:?}");
3713 }
3714 return Ok(candidate_ports);
3715 }
3716
3717 if bump_offset == 0
3719 && !auto_bump
3720 && let Some((port, daemon)) = conflicting_claim
3721 {
3722 return Err(PortError::Claimed {
3723 port,
3724 daemon: daemon.to_string(),
3725 }
3726 .into());
3727 }
3728 if bump_offset == 0
3729 && !auto_bump
3730 && let Some((port, address)) = conflicting_port
3731 {
3732 let (pid, process) = identify_port_owner(port, address).await;
3733 return Err(PortError::InUse {
3734 port,
3735 address: Some(shown_address(address)),
3736 process,
3737 pid,
3738 }
3739 .into());
3740 }
3741 }
3742
3743 Err(PortError::NoAvailablePort {
3745 start_port: expected_ports[0],
3746 attempts: max_attempts + 1,
3747 }
3748 .into())
3749}
3750
3751async fn port_bind_conflict(port: u16) -> Option<std::net::IpAddr> {
3757 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
3758 tokio::task::spawn_blocking(move || {
3759 for addr in [
3760 IpAddr::V4(Ipv4Addr::UNSPECIFIED),
3761 IpAddr::V4(Ipv4Addr::LOCALHOST),
3762 IpAddr::V6(Ipv6Addr::LOCALHOST),
3763 ] {
3764 match bind_probe((addr, port).into()) {
3765 Ok(socket) => drop(socket),
3766 Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => return Some(addr),
3767 Err(_) => continue,
3768 }
3769 }
3770 None
3771 })
3772 .await
3773 .unwrap_or(None)
3774}
3775
3776#[cfg(unix)]
3787fn bind_probe(addr: std::net::SocketAddr) -> std::io::Result<tokio::net::TcpSocket> {
3788 let socket = if addr.is_ipv4() {
3789 tokio::net::TcpSocket::new_v4()?
3790 } else {
3791 tokio::net::TcpSocket::new_v6()?
3792 };
3793 socket.set_reuseaddr(true)?;
3794 socket.bind(addr)?;
3795 Ok(socket)
3796}
3797
3798#[cfg(not(unix))]
3804fn bind_probe(addr: std::net::SocketAddr) -> std::io::Result<std::net::TcpListener> {
3805 std::net::TcpListener::bind(addr)
3806}
3807
3808fn shown_address(addr: std::net::IpAddr) -> String {
3810 match addr {
3811 std::net::IpAddr::V4(v4) => v4.to_string(),
3812 std::net::IpAddr::V6(v6) => format!("[{v6}]"),
3813 }
3814}
3815
3816fn listener_match(listening: std::net::IpAddr, conflict: std::net::IpAddr) -> Option<u8> {
3823 use std::net::IpAddr;
3824 let listening = listening.to_canonical();
3825 if listening == conflict {
3826 return Some(0);
3827 }
3828 match (listening, conflict) {
3829 (IpAddr::V4(_), IpAddr::V4(_)) | (IpAddr::V6(_), IpAddr::V6(_))
3830 if listening.is_unspecified() || conflict.is_unspecified() =>
3831 {
3832 Some(1)
3833 }
3834 (IpAddr::V6(v6), IpAddr::V4(_)) if v6.is_unspecified() => Some(2),
3835 _ => None,
3836 }
3837}
3838
3839struct TcpSocket {
3841 addr: std::net::SocketAddr,
3842 listening: bool,
3843 pid: u32,
3844 process: String,
3845}
3846
3847fn pick_port_owner(
3857 sockets: impl IntoIterator<Item = TcpSocket>,
3858 port: u16,
3859 conflict: std::net::IpAddr,
3860) -> Option<(u32, String)> {
3861 sockets
3862 .into_iter()
3863 .filter(|s| s.addr.port() == port)
3864 .filter_map(|s| {
3865 let matched = listener_match(s.addr.ip(), conflict)?;
3866 let rank = (matched == 2, !s.listening, matched);
3867 Some((rank, s.pid, s.process))
3868 })
3869 .min_by_key(|(rank, _, _)| *rank)
3870 .map(|(_, pid, process)| (pid, process))
3871}
3872
3873async fn identify_port_owner(port: u16, conflict: std::net::IpAddr) -> (u32, String) {
3883 tokio::task::spawn_blocking(move || {
3884 listeners::get_all()
3885 .ok()
3886 .and_then(|list| {
3887 let tcp = list
3890 .into_iter()
3891 .filter(|l| l.protocol == listeners::Protocol::TCP)
3892 .map(|l| TcpSocket {
3893 addr: l.socket,
3894 listening: l.state == listeners::SocketState::Listen,
3895 pid: l.process.pid,
3896 process: l.process.name,
3897 });
3898 pick_port_owner(tcp, port, conflict)
3899 })
3900 .unwrap_or((0, "unknown".to_string()))
3901 })
3902 .await
3903 .unwrap_or((0, "unknown".to_string()))
3904}
3905
3906async fn detect_port_conflict(port: u16) -> Option<(String, u32, String)> {
3911 let address = port_bind_conflict(port).await?;
3912 let (pid, process) = identify_port_owner(port, address).await;
3913 Some((shown_address(address), pid, process))
3914}
3915
3916#[derive(Debug, PartialEq, Eq)]
3917enum ActivePortSelection {
3918 NoCandidates,
3919 Selected(u16),
3920 Ambiguous(Vec<u16>),
3921}
3922
3923fn discovery_preferred_port(daemon: &crate::daemon::Daemon) -> Option<u16> {
3924 daemon
3925 .resolved_port
3926 .first()
3927 .copied()
3928 .or_else(|| {
3929 daemon
3930 .port
3931 .as_ref()
3932 .and_then(|port| port.expect.first().copied())
3933 })
3934 .filter(|&port| port > 0)
3935}
3936
3937fn select_active_port(
3938 listeners: impl IntoIterator<Item = listeners::Listener>,
3939 descendant_pids: &std::collections::HashSet<u32>,
3940 preferred_port: Option<u16>,
3941) -> ActivePortSelection {
3942 let process_ports: std::collections::BTreeSet<u16> = listeners
3943 .into_iter()
3944 .filter(|listener| {
3945 listener.protocol == listeners::Protocol::TCP
3946 && listener.state == listeners::SocketState::Listen
3947 && descendant_pids.contains(&listener.process.pid)
3948 })
3949 .map(|listener| listener.socket.port())
3950 .filter(|&port| port > 0)
3951 .collect();
3952
3953 if let Some(port) = preferred_port
3954 && process_ports.contains(&port)
3955 {
3956 return ActivePortSelection::Selected(port);
3957 }
3958
3959 match process_ports.len() {
3960 0 => ActivePortSelection::NoCandidates,
3961 1 => ActivePortSelection::Selected(*process_ports.first().unwrap()),
3962 _ => ActivePortSelection::Ambiguous(process_ports.into_iter().collect()),
3963 }
3964}
3965
3966fn detect_and_store_active_port(id: DaemonId, pid: u32) {
3977 tokio::spawn(async move {
3978 for delay_ms in [500u64, 1000, 2000, 4000] {
3982 tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
3983
3984 let preferred_port: Option<u16> = {
3987 let state_file = SUPERVISOR.state_file.lock().await;
3988 match state_file.daemons.get(&id) {
3989 Some(d) if d.pid.is_none() => {
3990 debug!("daemon {id}: aborting active_port detection — process exited");
3991 return;
3992 }
3993 Some(d) => discovery_preferred_port(d),
3994 None => None,
3995 }
3996 };
3997
3998 let selection = tokio::task::spawn_blocking(move || {
3999 let listeners = listeners::get_all().ok()?;
4000
4001 PROCS.refresh_processes();
4003
4004 let descendant_pids: std::collections::HashSet<u32> = PROCS
4005 .all_children(pid)
4006 .into_iter()
4007 .chain(std::iter::once(pid))
4008 .collect();
4009
4010 Some(select_active_port(
4011 listeners,
4012 &descendant_pids,
4013 preferred_port,
4014 ))
4015 })
4016 .await
4017 .ok()
4018 .flatten()
4019 .unwrap_or(ActivePortSelection::NoCandidates);
4020
4021 let port = match selection {
4022 ActivePortSelection::Selected(port) => port,
4023 ActivePortSelection::Ambiguous(ports) => {
4024 debug!(
4025 "daemon {id}: ambiguous active_port candidates {ports:?} for pid {pid} \
4026 and its descendants; leaving active_port unset (will retry)"
4027 );
4028 continue;
4029 }
4030 ActivePortSelection::NoCandidates => {
4031 debug!(
4032 "daemon {id}: no active port detected for pid {pid} or its descendants \
4033 (will retry)"
4034 );
4035 continue;
4036 }
4037 };
4038
4039 debug!("daemon {id} active_port detected: {port}");
4040 let mut state_file = SUPERVISOR.state_file.lock().await;
4041 if let Some(d) = state_file.daemons.get(&id) {
4042 if d.pid == Some(pid) {
4046 state_file.set_active_port(&id, port);
4047 } else {
4048 debug!(
4049 "daemon {id}: skipping active_port write — PID mismatch \
4050 (expected {pid}, current {:?})",
4051 d.pid
4052 );
4053 }
4054 }
4055 return;
4056 }
4057
4058 debug!(
4059 "daemon {id}: active port detection exhausted all retries for pid {pid} and its descendants"
4060 );
4061 });
4062}
4063
4064#[cfg(test)]
4065mod port_conflict_tests {
4066 use super::{
4067 TcpSocket, check_ports_available, claim_ports, listener_match, pick_port_owner,
4068 port_bind_conflict, shown_address,
4069 };
4070 use crate::error::PortError;
4071 use std::net::{IpAddr, SocketAddr};
4072
4073 static FORKS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
4076
4077 #[tokio::test]
4078 async fn a_taken_port_is_reported_with_its_address_and_holder() {
4079 let _forks = FORKS.lock().await;
4080 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4081 let port = listener.local_addr().unwrap().port();
4082
4083 let address = shown_address(port_bind_conflict(port).await.unwrap());
4086 assert!(
4087 ["0.0.0.0", "127.0.0.1"].contains(&address.as_str()),
4088 "{address}"
4089 );
4090
4091 let err = check_ports_available(&[port], false, 0, &Default::default())
4092 .await
4093 .unwrap_err();
4094 match err.downcast_ref::<PortError>() {
4095 Some(PortError::InUse {
4096 port: p,
4097 address: Some(a),
4098 pid,
4099 ..
4100 }) => {
4101 assert_eq!(*p, port);
4102 assert_eq!(*a, address);
4103 assert_eq!(*pid, std::process::id());
4105 }
4106 other => panic!("unexpected error: {other:?}"),
4107 }
4108 drop(listener);
4109 assert_eq!(port_bind_conflict(port).await, None);
4110 }
4111
4112 #[tokio::test]
4113 async fn a_starting_daemons_ports_are_not_resolved_for_another() {
4114 use crate::daemon_id::DaemonId;
4115 let _forks = FORKS.lock().await;
4116 let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4117 let port = probe.local_addr().unwrap().port();
4118 drop(probe);
4119 let one = DaemonId::new("claim-one", "web");
4120 let two = DaemonId::new("claim-two", "web");
4121
4122 let (resolved, claim) = claim_ports(&one, &[port], false, 0).await.unwrap();
4123 assert_eq!(resolved, vec![port]);
4124
4125 let err = claim_ports(&two, &[port], false, 0).await.unwrap_err();
4128 assert!(
4129 matches!(err.downcast_ref::<PortError>(), Some(PortError::Claimed { port: p, .. }) if *p == port),
4130 "{err:?}"
4131 );
4132 let (bumped, bumped_claim) = claim_ports(&two, &[port], true, 10).await.unwrap();
4133 assert_ne!(bumped, vec![port]);
4134 drop(bumped_claim);
4135
4136 drop(claim);
4138 let (resolved, _claim) = claim_ports(&two, &[port], false, 0).await.unwrap();
4139 assert_eq!(resolved, vec![port]);
4140 }
4141
4142 #[tokio::test]
4143 async fn an_old_attempts_claim_does_not_release_its_replacement() {
4144 use crate::daemon_id::DaemonId;
4145 let _forks = FORKS.lock().await;
4146 let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4147 let port = probe.local_addr().unwrap().port();
4148 drop(probe);
4149 let one = DaemonId::new("claim-restart", "web");
4150 let other = DaemonId::new("claim-other", "web");
4151
4152 let (_, old) = claim_ports(&one, &[port], false, 0).await.unwrap();
4153 let (_, new) = claim_ports(&one, &[port], false, 0).await.unwrap();
4154 drop(old);
4155 assert!(claim_ports(&other, &[port], false, 0).await.is_err());
4156 drop(new);
4157 assert!(claim_ports(&other, &[port], false, 0).await.is_ok());
4158 }
4159
4160 #[cfg(unix)]
4161 #[test]
4162 fn a_copy_of_a_probe_socket_does_not_look_like_a_listener() {
4163 use super::bind_probe;
4164 let copy = bind_probe(SocketAddr::from(([0, 0, 0, 0], 0))).unwrap();
4167 let port = copy.local_addr().unwrap().port();
4168 let addr = SocketAddr::from(([127, 0, 0, 1], port));
4169 bind_probe(addr).unwrap();
4170 let timeout = std::time::Duration::from_millis(200);
4173 assert!(std::net::TcpStream::connect_timeout(&addr, timeout).is_err());
4174 drop(copy);
4175 }
4176
4177 #[cfg(target_os = "linux")]
4186 #[tokio::test]
4187 async fn a_free_port_stays_free_while_another_thread_forks() {
4188 use crate::inherited_fds::CloseInheritedFds;
4189 use std::sync::Arc;
4190 use std::sync::atomic::{AtomicBool, Ordering};
4191
4192 let _forks = FORKS.lock().await;
4193 let port = std::net::TcpListener::bind("127.0.0.1:0")
4194 .unwrap()
4195 .local_addr()
4196 .unwrap()
4197 .port();
4198 let stop = Arc::new(AtomicBool::new(false));
4199 let forker = std::thread::spawn({
4200 let stop = stop.clone();
4201 move || {
4202 while !stop.load(Ordering::Relaxed) {
4203 std::process::Command::new("true")
4206 .close_inherited_fds()
4207 .status()
4208 .unwrap();
4209 }
4210 }
4211 });
4212 let mut conflicts = Vec::new();
4213 for _ in 0..500 {
4214 conflicts.extend(port_bind_conflict(port).await);
4215 }
4216 stop.store(true, Ordering::Relaxed);
4217 forker.join().unwrap();
4218 assert!(
4219 conflicts.is_empty(),
4220 "free port looked taken on {conflicts:?}"
4221 );
4222 }
4223
4224 fn ip(s: &str) -> IpAddr {
4225 s.parse().unwrap()
4226 }
4227
4228 fn socket(addr: &str, listening: bool, pid: u32) -> TcpSocket {
4229 TcpSocket {
4230 addr: addr.parse::<SocketAddr>().unwrap(),
4231 listening,
4232 pid,
4233 process: format!("p{pid}"),
4234 }
4235 }
4236
4237 #[test]
4238 fn only_a_listener_whose_address_conflicts_is_named() {
4239 let all = || {
4240 [
4241 socket("192.0.2.1:3000", true, 1),
4242 socket("127.0.0.1:3000", true, 2),
4243 socket("[::1]:3000", true, 3),
4244 socket("127.0.0.1:4000", true, 4),
4245 ]
4246 };
4247 assert_eq!(
4249 pick_port_owner(all(), 3000, ip("127.0.0.1")),
4250 Some((2, "p2".into()))
4251 );
4252 assert_eq!(
4253 pick_port_owner(all(), 3000, ip("::1")),
4254 Some((3, "p3".into()))
4255 );
4256 let v4 = pick_port_owner(all(), 3000, ip("0.0.0.0")).unwrap().0;
4258 assert!([1, 2].contains(&v4));
4259 assert_eq!(
4261 pick_port_owner([socket("[::1]:3000", true, 3)], 3000, ip("127.0.0.1")),
4262 None
4263 );
4264 assert_eq!(pick_port_owner(all(), 5000, ip("127.0.0.1")), None);
4265
4266 let both = [
4269 socket("127.0.0.1:3000", false, 5),
4270 socket("0.0.0.0:3000", true, 6),
4271 ];
4272 assert_eq!(
4273 pick_port_owner(both, 3000, ip("127.0.0.1")),
4274 Some((6, "p6".into()))
4275 );
4276 assert_eq!(
4277 pick_port_owner([socket("127.0.0.1:3000", false, 5)], 3000, ip("127.0.0.1")),
4278 Some((5, "p5".into()))
4279 );
4280
4281 let v6_wildcard = || {
4284 [
4285 socket("[::]:3000", true, 7),
4286 socket("127.0.0.1:3000", false, 8),
4287 ]
4288 };
4289 assert_eq!(
4290 pick_port_owner(v6_wildcard(), 3000, ip("127.0.0.1")),
4291 Some((8, "p8".into()))
4292 );
4293 assert_eq!(
4294 pick_port_owner(v6_wildcard(), 3000, ip("0.0.0.0")),
4295 Some((8, "p8".into()))
4296 );
4297 assert_eq!(
4299 pick_port_owner([socket("[::]:3000", true, 7)], 3000, ip("127.0.0.1")),
4300 Some((7, "p7".into()))
4301 );
4302 assert_eq!(
4304 pick_port_owner(
4305 [socket("[::ffff:127.0.0.1]:3000", false, 9)],
4306 3000,
4307 ip("127.0.0.1")
4308 ),
4309 Some((9, "p9".into()))
4310 );
4311
4312 assert_eq!(listener_match(ip("0.0.0.0"), ip("127.0.0.1")), Some(1));
4313 assert_eq!(listener_match(ip("::"), ip("127.0.0.1")), Some(2));
4314 assert_eq!(listener_match(ip("::1"), ip("127.0.0.1")), None);
4315 assert_eq!(listener_match(ip("192.0.2.1"), ip("127.0.0.1")), None);
4316 assert_eq!(shown_address(ip("::1")), "[::1]");
4317 }
4318}
4319
4320#[cfg(test)]
4321mod active_port_tests {
4322 use super::*;
4323 use crate::config_types::PortConfig;
4324 use listeners::{Listener, Process, Protocol, SocketState};
4325 use std::net::{IpAddr, Ipv4Addr, SocketAddr};
4326
4327 fn listener(pid: u32, port: u16, protocol: Protocol, state: SocketState) -> Listener {
4328 Listener {
4329 process: Process {
4330 pid,
4331 name: "test".to_string(),
4332 path: "/test".to_string(),
4333 },
4334 socket: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
4335 protocol,
4336 state,
4337 }
4338 }
4339
4340 #[test]
4341 fn active_port_candidates_exclude_outbound_tcp_and_udp_sockets() {
4342 let daemon_pid = 100;
4343 let child_pid = 101;
4344 let descendant_pids = [daemon_pid, child_pid].into_iter().collect();
4345 let listeners = vec![
4346 listener(child_pid, 3004, Protocol::TCP, SocketState::Listen),
4347 listener(daemon_pid, 47082, Protocol::TCP, SocketState::Established),
4348 listener(daemon_pid, 5353, Protocol::UDP, SocketState::Unknown),
4349 listener(999, 9000, Protocol::TCP, SocketState::Listen),
4350 ];
4351
4352 assert_eq!(
4353 select_active_port(listeners, &descendant_pids, None),
4354 ActivePortSelection::Selected(3004)
4355 );
4356 }
4357
4358 #[test]
4359 fn bumped_cmd_readiness_prefers_resolved_primary_port() {
4360 let daemon = crate::daemon::Daemon {
4361 resolved_port: vec![3004],
4362 port: Some(PortConfig {
4363 expect: vec![3000],
4364 ..PortConfig::default()
4365 }),
4366 ..crate::daemon::Daemon::default()
4367 };
4368 let descendant_pids = [100].into_iter().collect();
4369 let listeners = vec![
4370 listener(100, 9000, Protocol::TCP, SocketState::Listen),
4371 listener(100, 3004, Protocol::TCP, SocketState::Listen),
4372 ];
4373
4374 assert_eq!(discovery_preferred_port(&daemon), Some(3004));
4375 assert_eq!(
4376 select_active_port(
4377 listeners,
4378 &descendant_pids,
4379 discovery_preferred_port(&daemon),
4380 ),
4381 ActivePortSelection::Selected(3004)
4382 );
4383 }
4384
4385 #[test]
4386 fn legacy_state_uses_expected_primary_port_for_discovery() {
4387 let daemon = crate::daemon::Daemon {
4388 port: Some(PortConfig {
4389 expect: vec![3000],
4390 ..PortConfig::default()
4391 }),
4392 ..crate::daemon::Daemon::default()
4393 };
4394
4395 assert_eq!(discovery_preferred_port(&daemon), Some(3000));
4396 }
4397
4398 #[test]
4399 fn ambiguous_candidates_leave_active_port_unset() {
4400 let descendant_pids = [100].into_iter().collect();
4401 let listeners = vec![
4402 listener(100, 9000, Protocol::TCP, SocketState::Listen),
4403 listener(100, 3000, Protocol::TCP, SocketState::Listen),
4404 ];
4405
4406 assert_eq!(
4407 select_active_port(listeners, &descendant_pids, None),
4408 ActivePortSelection::Ambiguous(vec![3000, 9000])
4409 );
4410 }
4411
4412 #[test]
4413 fn bumped_ready_port_sets_only_the_resolved_primary_without_scanning() {
4414 assert_eq!(active_port_from_ready_port(3004, &[3004]), Some(3004));
4415 assert_eq!(active_port_from_ready_port(4003, &[3003, 4003]), None);
4416 }
4417
4418 #[test]
4419 fn delay_readiness_requires_delay_only_and_a_running_process() {
4420 assert!(delay_readiness_succeeded(false, false, false, true));
4421 assert!(!delay_readiness_succeeded(false, true, false, true));
4422 assert!(!delay_readiness_succeeded(false, false, true, false));
4423 assert!(!delay_readiness_succeeded(false, false, false, false));
4424 assert!(!delay_readiness_succeeded(true, false, false, true));
4425 }
4426}
4427
4428fn is_daemon_slug_target(id: &DaemonId) -> bool {
4436 let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
4440 slugs.iter().any(|(slug, entry)| {
4441 let daemon_name = entry.daemon.as_deref().unwrap_or(slug);
4442 id.name() == daemon_name
4443 })
4444}
4445
4446#[cfg(test)]
4447mod oneshot_tests {
4448 use super::*;
4449
4450 #[test]
4451 fn oneshot_clean_exit_is_completed() {
4452 let (status, success) = terminal_exit_state("exit", true, 0, true);
4453 assert!(matches!(status, DaemonStatus::Completed));
4454 assert!(success);
4455 }
4456
4457 #[test]
4458 fn service_clean_exit_is_still_stopped() {
4459 let (status, success) = terminal_exit_state("exit", false, 0, true);
4460 assert!(matches!(status, DaemonStatus::Stopped));
4461 assert!(success);
4462 }
4463
4464 #[test]
4465 fn oneshot_failure_is_errored_so_retry_applies() {
4466 let (status, success) = terminal_exit_state("fail", true, 3, false);
4469 assert!(matches!(status, DaemonStatus::Errored(3)));
4470 assert!(!success);
4471 }
4472
4473 #[test]
4474 fn a_stop_cancels_the_retry_sequence_it_finds() {
4475 let id = DaemonId::new("retry-cancel-test", "task");
4476 let claim = SUPERVISOR.mark_retrying(&id);
4477 assert!(!claim.is_cancelled());
4478 assert!(SUPERVISOR.is_retrying(&id));
4479 SUPERVISOR.cancel_retrying(&id);
4480 assert!(claim.is_cancelled());
4481 drop(claim);
4482 assert!(!SUPERVISOR.is_retrying(&id));
4483 }
4484
4485 #[test]
4486 fn a_stop_cancels_every_sequence_for_the_daemon() {
4487 let id = DaemonId::new("retry-cancel-test", "concurrent");
4491 let first = SUPERVISOR.mark_retrying(&id);
4492 let second = SUPERVISOR.mark_retrying(&id);
4493 SUPERVISOR.cancel_retrying(&id);
4494 assert!(first.is_cancelled());
4495 assert!(second.is_cancelled());
4496 drop(second);
4497 assert!(SUPERVISOR.is_retrying(&id));
4499 drop(first);
4500 assert!(!SUPERVISOR.is_retrying(&id));
4501 }
4502
4503 #[test]
4504 fn a_stop_invalidates_an_attempt_decided_on_before_it() {
4505 let id = DaemonId::new("stop-epoch-test", "task");
4509 let approved_at = SUPERVISOR.stop_epoch(&id);
4510 assert_eq!(SUPERVISOR.stop_epoch(&id), approved_at);
4511 SUPERVISOR.bump_stop_epoch(&id);
4512 assert_ne!(SUPERVISOR.stop_epoch(&id), approved_at);
4513 let approved_after = SUPERVISOR.stop_epoch(&id);
4515 assert_eq!(SUPERVISOR.stop_epoch(&id), approved_after);
4516 }
4517
4518 #[test]
4519 fn stop_epochs_are_tracked_per_daemon() {
4520 let stopped = DaemonId::new("stop-epoch-test", "stopped");
4521 let untouched = DaemonId::new("stop-epoch-test", "untouched");
4522 let approved_at = SUPERVISOR.stop_epoch(&untouched);
4523 SUPERVISOR.bump_stop_epoch(&stopped);
4524 assert_eq!(SUPERVISOR.stop_epoch(&untouched), approved_at);
4525 }
4526
4527 #[test]
4528 fn a_stop_leaves_a_completed_task_alone() {
4529 assert!(stop_keeps_finalized_status(&DaemonStatus::Completed));
4531 }
4532
4533 #[test]
4534 fn a_stop_replaces_a_failure_so_retries_do_not_resume() {
4535 assert!(!stop_keeps_finalized_status(&DaemonStatus::Errored(1)));
4538 assert!(!stop_keeps_finalized_status(&DaemonStatus::Running));
4539 assert!(!stop_keeps_finalized_status(&DaemonStatus::Stopped));
4540 }
4541
4542 #[test]
4543 fn stopped_oneshot_did_not_complete() {
4544 let (status, _) = terminal_exit_state("stop", true, 0, true);
4545 assert!(matches!(status, DaemonStatus::Stopped));
4546 }
4547}
4548
4549#[cfg(all(test, unix))]
4550mod tests {
4551 use super::*;
4552
4553 #[test]
4554 fn test_resolve_run_identity_empty_without_sudo() {
4555 let identity = resolve_run_identity(None, 501, 20, None, None).unwrap();
4556 assert_eq!(identity, RunIdentity::Inherit);
4557 }
4558
4559 #[test]
4560 fn test_resolve_run_identity_sudo_fallback() {
4561 let identity = resolve_run_identity(None, 0, 0, Some("501"), Some("20")).unwrap();
4562 let RunIdentity::Switch { uid, gid, .. } = identity else {
4563 panic!("expected identity switch");
4564 };
4565 assert_eq!(uid.as_raw(), 501);
4566 assert_eq!(gid.as_raw(), 20);
4567 }
4568
4569 #[test]
4570 fn test_resolve_run_identity_ignores_stale_sudo_when_not_root() {
4571 let identity = resolve_run_identity(None, 501, 20, Some("0"), Some("0")).unwrap();
4572 assert_eq!(identity, RunIdentity::Inherit);
4573 }
4574
4575 #[test]
4576 fn test_resolve_configured_user_root_name() {
4577 let identity = resolve_configured_user("root").unwrap();
4578 let RunIdentity::Switch { uid, username, .. } = identity else {
4579 panic!("expected identity switch");
4580 };
4581 assert_eq!(uid.as_raw(), 0);
4582 assert_eq!(
4583 username.as_deref().and_then(|s| s.to_str().ok()),
4584 Some("root")
4585 );
4586 }
4587
4588 #[test]
4589 fn test_resolve_configured_user_root_uid() {
4590 let identity = resolve_configured_user("0").unwrap();
4591 let RunIdentity::Switch { uid, username, .. } = identity else {
4592 panic!("expected identity switch");
4593 };
4594 assert_eq!(uid.as_raw(), 0);
4595 assert_eq!(
4596 username.as_deref().and_then(|s| s.to_str().ok()),
4597 Some("root")
4598 );
4599 }
4600
4601 #[test]
4602 fn test_resolve_configured_user_missing_user_fails() {
4603 let err = resolve_configured_user("pitchfork-user-that-should-not-exist")
4604 .unwrap_err()
4605 .to_string();
4606 assert!(err.contains("does not exist"));
4607 }
4608
4609 #[test]
4610 fn test_resolve_run_identity_requires_root_for_user_switch() {
4611 let err = resolve_run_identity(Some("root"), 501, 20, None, None)
4612 .unwrap_err()
4613 .to_string();
4614 assert!(err.contains("Restart the supervisor with sudo"));
4615 }
4616
4617 #[test]
4618 fn test_resolve_run_identity_same_user_is_noop() {
4619 let identity = resolve_run_identity(Some("root"), 0, 0, Some("501"), Some("20")).unwrap();
4620 assert_eq!(identity, RunIdentity::Inherit);
4621 }
4622
4623 #[test]
4624 fn test_resolve_configured_user_records_home() {
4625 let identity = resolve_configured_user("root").unwrap();
4626 let RunIdentity::Switch { home, .. } = identity else {
4627 panic!("expected identity switch");
4628 };
4629 let expected = nix::unistd::User::from_name("root").unwrap().unwrap().dir;
4630 assert_eq!(home, Some(expected));
4631 }
4632
4633 fn switch_to(name: Option<&str>, home: Option<&str>) -> RunIdentity {
4634 RunIdentity::Switch {
4635 uid: nix::unistd::Uid::from_raw(501),
4636 gid: nix::unistd::Gid::from_raw(20),
4637 username: name.map(|n| CString::new(n).unwrap()),
4638 home: home.map(std::path::PathBuf::from),
4639 }
4640 }
4641
4642 fn command_env(
4645 command: &tokio::process::Command,
4646 key: &str,
4647 ) -> Option<Option<std::ffi::OsString>> {
4648 command
4649 .as_std()
4650 .get_envs()
4651 .find(|(k, _)| *k == key)
4652 .map(|(_, v)| v.map(ToOwned::to_owned))
4653 }
4654
4655 fn daemon_command(
4657 identity: &RunIdentity,
4658 daemon_env: Option<&IndexMap<String, String>>,
4659 ) -> tokio::process::Command {
4660 let mut command = tokio::process::Command::new("true");
4661 apply_identity_env(&mut command, identity);
4662 apply_runtime_env(
4663 &mut command,
4664 &DaemonId::new("identity-env-test", "api"),
4665 0,
4666 daemon_env,
4667 &[],
4668 );
4669 command
4670 }
4671
4672 #[test]
4673 fn test_identity_env_describes_the_switched_user() {
4674 let command = daemon_command(&switch_to(Some("alice"), Some("/home/alice")), None);
4675 assert_eq!(
4676 command_env(&command, "HOME"),
4677 Some(Some("/home/alice".into()))
4678 );
4679 assert_eq!(command_env(&command, "USER"), Some(Some("alice".into())));
4680 assert_eq!(command_env(&command, "LOGNAME"), Some(Some("alice".into())));
4681 }
4682
4683 #[test]
4684 fn test_identity_env_leaves_inherited_env_alone() {
4685 let command = daemon_command(&RunIdentity::Inherit, None);
4686 assert_eq!(command_env(&command, "HOME"), None);
4687 assert_eq!(command_env(&command, "USER"), None);
4688 assert_eq!(command_env(&command, "LOGNAME"), None);
4689 }
4690
4691 #[test]
4692 fn test_root_sudo_to_root_preserves_environment() {
4693 let identity = resolve_run_identity(None, 0, 0, Some("0"), Some("0")).unwrap();
4694 assert_eq!(identity, RunIdentity::Inherit);
4695 let command = daemon_command(&identity, None);
4696 for key in ["HOME", "USER", "LOGNAME"] {
4697 assert_eq!(command_env(&command, key), None);
4698 }
4699 }
4700
4701 #[test]
4702 fn test_daemon_env_overrides_identity_env() {
4703 let mut env = IndexMap::new();
4704 env.insert("HOME".to_string(), "/srv/app".to_string());
4705 env.insert("USER".to_string(), "app".to_string());
4706 let command = daemon_command(&switch_to(Some("alice"), Some("/home/alice")), Some(&env));
4707 assert_eq!(command_env(&command, "HOME"), Some(Some("/srv/app".into())));
4708 assert_eq!(command_env(&command, "USER"), Some(Some("app".into())));
4709 assert_eq!(command_env(&command, "LOGNAME"), Some(Some("alice".into())));
4710 }
4711
4712 #[test]
4713 fn test_identity_env_drops_values_without_a_passwd_entry() {
4714 let command = daemon_command(&switch_to(None, None), None);
4717 assert_eq!(command_env(&command, "HOME"), Some(None));
4718 assert_eq!(command_env(&command, "USER"), Some(None));
4719 assert_eq!(command_env(&command, "LOGNAME"), Some(None));
4720 }
4721
4722 #[test]
4723 fn test_daemon_env_restores_values_without_a_passwd_entry() {
4724 let mut env = IndexMap::new();
4725 env.insert("HOME".to_string(), "/srv/app".to_string());
4726 let command = daemon_command(&switch_to(None, None), Some(&env));
4727 assert_eq!(command_env(&command, "HOME"), Some(Some("/srv/app".into())));
4728 }
4729}
4730
4731fn inject_proxy_env(cmd: &mut tokio::process::Command, host: &Option<String>) {
4740 let s = crate::settings::settings();
4741 let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
4742
4743 if s.proxy.enable && host.is_some() && !lan_enabled {
4744 cmd.env("HOST", "127.0.0.1");
4747 }
4748
4749 if let Some(url) = build_pitchfork_url(host, &s) {
4751 cmd.env("PITCHFORK_URL", &url);
4752 }
4753
4754 if s.proxy.enable && s.proxy.https {
4760 let ca_path = if s.proxy.tls_cert.is_empty() {
4761 crate::env::PITCHFORK_STATE_DIR.join("proxy").join("ca.pem")
4762 } else {
4763 std::path::PathBuf::from(&s.proxy.tls_cert)
4764 };
4765 if ca_path.exists() {
4766 let ca_path = ca_path.to_string_lossy().to_string();
4767 cmd.env("PITCHFORK_CA_FILE", &ca_path);
4768 cmd.env("NODE_EXTRA_CA_CERTS", &ca_path);
4769 }
4770 }
4771
4772 if s.proxy.enable {
4774 let tld = if lan_enabled { "local" } else { &s.proxy.tld };
4775 cmd.env("__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS", format!(".{tld}"));
4776 }
4777
4778 if lan_enabled {
4780 cmd.env("PITCHFORK_LAN", "1");
4781 }
4782}
4783
4784async fn daemon_proxy_host(opts: &RunOptions) -> Option<String> {
4790 if !crate::settings::settings().proxy.enable {
4793 return None;
4794 }
4795 if let Some(slug) = opts.slug.as_deref()
4799 && crate::proxy::hostname::hostname_fits(slug)
4800 {
4801 return opts.slug.clone();
4802 }
4803 let config_dir = opts
4806 .watch_base_dir
4807 .clone()
4808 .unwrap_or_else(|| opts.dir.0.clone());
4809 let id = opts.id.clone();
4810 tokio::task::spawn_blocking(move || {
4816 let pt = crate::pitchfork_toml::PitchforkToml::all_merged_from(&config_dir).ok()?;
4817 let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
4818 crate::proxy::hostname::host_for_daemon(&id, pt.daemons.get(&id), &slugs)
4819 })
4820 .await
4821 .unwrap_or_default()
4822}
4823
4824fn build_pitchfork_url(host: &Option<String>, s: &crate::settings::Settings) -> Option<String> {
4828 crate::proxy::build_proxy_url(host.as_deref(), s)
4829}
4830
4831#[cfg(test)]
4832mod ready_check_tests {
4833 use super::*;
4834 use std::time::Duration;
4835
4836 #[test]
4837 fn any_ready_check_remaining_prefers_unbounded_checks() {
4838 let http = ReadyHttp::new("http://localhost/health");
4839 let cmd = ReadyCmd::new("true");
4840
4841 assert!(any_ready_check_remaining(
4842 None,
4843 false,
4844 None,
4845 false,
4846 Some(&http),
4847 false,
4848 None,
4849 false
4850 ));
4851 assert!(any_ready_check_remaining(
4852 None,
4853 false,
4854 None,
4855 false,
4856 None,
4857 false,
4858 Some(&cmd),
4859 false
4860 ));
4861 assert!(any_ready_check_remaining(
4862 None,
4863 false,
4864 Some(&ReadyPort::new(8080)),
4865 false,
4866 Some(&http),
4867 true,
4868 Some(&cmd),
4869 true
4870 ));
4871 }
4872
4873 #[test]
4874 fn any_ready_check_remaining_exhausted_timed_checks() {
4875 let http = ReadyHttp {
4876 url: "http://localhost/health".to_string(),
4877 status: vec![],
4878 timeout: Some(Duration::from_secs(5)),
4879 };
4880 let cmd = ReadyCmd {
4881 run: "true".into(),
4882 timeout: Some(Duration::from_secs(5)),
4883 };
4884
4885 assert!(any_ready_check_remaining(
4886 None,
4887 false,
4888 None,
4889 false,
4890 Some(&http),
4891 false,
4892 Some(&cmd),
4893 false
4894 ));
4895 assert!(!any_ready_check_remaining(
4896 None,
4897 false,
4898 None,
4899 false,
4900 Some(&http),
4901 true,
4902 Some(&cmd),
4903 true
4904 ));
4905 }
4906
4907 #[tokio::test]
4908 async fn spawn_cmd_probe_reports_success() {
4909 let id = DaemonId::new("global", "probe-test");
4910 let probe = spawn_cmd_probe(&id, &"true".into(), &std::env::temp_dir(), 0, None, &[]);
4911 let status = probe.result_rx.await.unwrap().unwrap();
4912 assert!(status.success());
4913 }
4914
4915 #[cfg(unix)]
4919 #[tokio::test]
4920 async fn spawn_cmd_probe_runs_an_argv_without_a_shell() {
4921 let id = DaemonId::new("global", "probe-test");
4922 let argv = |arg: &str| -> RunCommand {
4923 RunCommand::Argv(
4924 ["test", arg, "=", "a b $HOME %PATH% &"]
4925 .map(str::to_string)
4926 .to_vec(),
4927 )
4928 };
4929 let probe = spawn_cmd_probe(
4930 &id,
4931 &argv("a b $HOME %PATH% &"),
4932 &std::env::temp_dir(),
4933 0,
4934 None,
4935 &[],
4936 );
4937 assert!(probe.result_rx.await.unwrap().unwrap().success());
4938 let probe = spawn_cmd_probe(
4940 &id,
4941 &"test a b $HOME %PATH% & = 'a b $HOME %PATH% &'".into(),
4942 &std::env::temp_dir(),
4943 0,
4944 None,
4945 &[],
4946 );
4947 assert!(!probe.result_rx.await.unwrap().unwrap().success());
4948 let probe = spawn_cmd_probe(&id, &argv("different"), &std::env::temp_dir(), 0, None, &[]);
4949 assert!(!probe.result_rx.await.unwrap().unwrap().success());
4950 }
4951
4952 #[tokio::test]
4953 async fn spawn_cmd_probe_stops_on_request() {
4954 let id = DaemonId::new("global", "probe-test");
4955 let probe = spawn_cmd_probe(&id, &"sleep 30".into(), &std::env::temp_dir(), 0, None, &[]);
4956 let CmdProbe {
4957 cancel_tx,
4958 result_rx,
4959 } = probe;
4960 let _ = cancel_tx.send(());
4961 let status = result_rx.await.unwrap().unwrap();
4962 assert!(!status.success());
4963 }
4964
4965 #[tokio::test]
4966 async fn spawn_cmd_probe_receives_daemon_and_resolved_port_environment() {
4967 let id = DaemonId::new("worktree", "api");
4968 let daemon_env = IndexMap::from([("CUSTOM_VALUE".to_string(), "yes".to_string())]);
4969 let check = if cfg!(windows) {
4972 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"#
4973 } else {
4974 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"#
4975 };
4976 let probe = spawn_cmd_probe(
4977 &id,
4978 &check.into(),
4979 &std::env::temp_dir(),
4980 2,
4981 Some(&daemon_env),
4982 &[4100, 5100],
4983 );
4984 let status = probe.result_rx.await.unwrap().unwrap();
4985 assert!(status.success());
4986 }
4987
4988 #[test]
4989 fn configured_ready_port_follows_expected_port_bump() {
4990 assert_eq!(resolve_configured_ready_port(3000, &[3000], &[3004]), 3004);
4991 assert_eq!(
4992 resolve_configured_ready_port(4000, &[3000, 4000], &[3003, 4003]),
4993 4003
4994 );
4995 assert_eq!(resolve_configured_ready_port(8080, &[3000], &[3004]), 8080);
4996 }
4997}
4998
4999#[cfg(test)]
5000mod launch_command_tests {
5001 use super::{invalid_argv_program, launch_command};
5002 use crate::daemon_id::DaemonId;
5003
5004 #[test]
5005 fn refuses_an_argv_whose_program_rendered_empty_or_to_exec() {
5006 let id = DaemonId::new("proj", "api");
5007 assert!(invalid_argv_program(&id, &[]).is_some());
5008 assert!(invalid_argv_program(&id, &words(&["", "server.js"])).is_some());
5009 assert!(invalid_argv_program(&id, &words(&["exec", "node"])).is_some());
5010 assert_eq!(invalid_argv_program(&id, &words(&["node", ""])), None);
5011 }
5012
5013 #[test]
5014 fn refuses_a_probe_array_whose_program_rendered_empty_or_to_exec() {
5015 use super::invalid_probe_program;
5016 use crate::pitchfork_toml::RunCommand;
5017 let id = DaemonId::new("proj", "api");
5018 for field in ["ready_cmd", "health_cmd"] {
5019 let check =
5020 |run: Vec<String>| invalid_probe_program(&id, field, Some(&RunCommand::Argv(run)));
5021 assert!(check(vec![]).unwrap().contains(field));
5022 assert!(check(words(&["", "-h"])).is_some());
5023 assert!(check(words(&["exec", "pg_isready"])).is_some());
5024 assert_eq!(check(words(&["pg_isready", ""])), None);
5025 }
5026 assert_eq!(
5028 invalid_probe_program(&id, "health_cmd", Some(&RunCommand::Shell(String::new()))),
5029 None
5030 );
5031 assert_eq!(invalid_probe_program(&id, "health_cmd", None), None);
5032 }
5033
5034 fn words(words: &[&str]) -> Vec<String> {
5035 words.iter().map(|w| w.to_string()).collect()
5036 }
5037
5038 #[test]
5039 fn windows_rejects_only_enabled_unsupported_options() {
5040 let mut opts = crate::daemon::RunOptions::default();
5041 assert_eq!(super::unsupported_windows_options(&opts, ""), None);
5042 opts.pty = Some(false);
5043 opts.user = Some(" \t".into());
5044 assert_eq!(super::unsupported_windows_options(&opts, " \t"), None);
5045 opts.pty = Some(true);
5046 assert!(
5047 super::unsupported_windows_options(&opts, "")
5048 .unwrap()
5049 .contains("pty = true")
5050 );
5051 opts.pty = Some(false);
5052 opts.user = Some("postgres".into());
5053 assert!(
5054 super::unsupported_windows_options(&opts, "")
5055 .unwrap()
5056 .contains("user switching")
5057 );
5058 opts.user = None;
5059 assert!(
5060 super::unsupported_windows_options(&opts, "postgres")
5061 .unwrap()
5062 .contains("settings.supervisor.user")
5063 );
5064 }
5065
5066 #[test]
5067 fn starts_the_first_word_with_the_rest_as_arguments() {
5068 let argv = words(&["node", "my server.js", "--name=\"a b\"", "&", "%PATH%"]);
5069 assert_eq!(
5070 launch_command(argv, None),
5071 (
5072 "node".to_string(),
5073 words(&["my server.js", "--name=\"a b\"", "&", "%PATH%"])
5074 )
5075 );
5076 }
5077
5078 #[test]
5079 fn mise_receives_every_word_after_the_separator() {
5080 let argv = words(&["node", "my server.js", "'single'"]);
5081 let mise = std::path::Path::new("/opt/mise/bin/mise");
5082 let (program, args) = launch_command(argv, Some(mise));
5083 assert_eq!(program, mise.to_string_lossy());
5084 assert_eq!(
5085 args,
5086 words(&["x", "--", "node", "my server.js", "'single'"])
5087 );
5088 }
5089}
5090
5091#[cfg(all(test, windows))]
5092mod windows_retry_tests {
5093 use super::*;
5094 use crate::config_types::{Dir, Retry};
5095 use crate::settings::reload_settings;
5096 use std::process::Stdio;
5097 use tokio::io::AsyncBufReadExt;
5098
5099 #[tokio::test]
5100 async fn forced_retry_claim_revalidates_settings_before_stopping_a_live_instance() {
5101 const CHILD_ENV: &str = "PITCHFORK_TEST_WINDOWS_RETRY_CLAIM";
5102 const CHILD_SENTINEL: &str = "windows-retry-claim-child-ran";
5103 if std::env::var_os(CHILD_ENV).is_none() {
5104 let temp = tempfile::tempdir().unwrap();
5107 std::fs::create_dir(temp.path().join("config")).unwrap();
5108 std::fs::write(
5109 temp.path().join("pitchfork.toml"),
5110 "[settings.supervisor]\nuser = ''\n",
5111 )
5112 .unwrap();
5113 let mut command = tokio::process::Command::new(std::env::current_exe().unwrap());
5114 for (name, _) in std::env::vars_os() {
5115 if name
5116 .to_string_lossy()
5117 .to_ascii_uppercase()
5118 .starts_with("PITCHFORK_")
5119 {
5120 command.env_remove(name);
5121 }
5122 }
5123 command
5124 .args([
5125 "--exact",
5126 "supervisor::lifecycle::windows_retry_tests::forced_retry_claim_revalidates_settings_before_stopping_a_live_instance",
5127 "--nocapture",
5128 ])
5129 .current_dir(temp.path())
5130 .env(CHILD_ENV, "1")
5131 .env("PITCHFORK_CONFIG_DIR", temp.path().join("config"))
5132 .env("PITCHFORK_STATE_DIR", temp.path().join("state"))
5133 .env("PITCHFORK_LOGS_DIR", temp.path().join("logs"))
5134 .env("PITCHFORK_BOOT_EXECUTABLE", temp.path().join("missing.exe"))
5135 .hide_console_window()
5136 .kill_on_drop(true);
5137 let output = time::timeout(Duration::from_secs(30), command.output())
5138 .await
5139 .expect("isolated retry claim test timed out")
5140 .unwrap();
5141 assert!(
5142 output.status.success(),
5143 "isolated retry claim test failed:\nstdout:\n{}\nstderr:\n{}",
5144 String::from_utf8_lossy(&output.stdout),
5145 String::from_utf8_lossy(&output.stderr)
5146 );
5147 assert!(String::from_utf8_lossy(&output.stderr).contains(CHILD_SENTINEL));
5148 return;
5149 }
5150 eprintln!("{CHILD_SENTINEL}");
5151
5152 let mut opts = RunOptions {
5153 id: DaemonId::new("windows-retry", "live"),
5154 force: true,
5155 wait_ready: true,
5156 retry: Retry(2),
5157 dir: Dir(env::CWD.clone()),
5158 ..RunOptions::default()
5159 };
5160 let mut restart_mark = None;
5161 let mut guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
5162 assert!(
5163 SUPERVISOR
5164 .claim_or_defer(&opts, &mut guard, &mut restart_mark, None)
5165 .await
5166 .unwrap()
5167 .is_none()
5168 );
5169 drop(guard.take());
5170 let retrying_claim = SUPERVISOR.mark_retrying(&opts.id);
5171
5172 let powershell = std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap())
5177 .join("System32/WindowsPowerShell/v1.0/powershell.exe");
5178 let mut child = tokio::process::Command::new(powershell)
5179 .args([
5180 "-NoLogo",
5181 "-NoProfile",
5182 "-NonInteractive",
5183 "-Command",
5184 "[Console]::Out.WriteLine('READY'); [Console]::In.ReadToEnd() | Out-Null",
5185 ])
5186 .current_dir(std::env::var_os("SystemRoot").unwrap())
5187 .stdin(Stdio::piped())
5188 .stdout(Stdio::piped())
5189 .stderr(Stdio::null())
5190 .kill_on_drop(true)
5191 .hide_console_window()
5192 .spawn()
5193 .unwrap();
5194 let mut stdout = tokio::io::BufReader::new(child.stdout.take().unwrap());
5195 let mut ready = String::new();
5196 stdout.read_line(&mut ready).await.unwrap();
5197 assert_eq!(ready.trim_end(), "READY");
5198 let pid = child.id().unwrap();
5199 PROCS.refresh_pids(&[pid]);
5200 assert!(PROCS.is_running(pid));
5201 assert!(child.try_wait().unwrap().is_none());
5202 guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
5203 let running = SUPERVISOR
5204 .upsert_daemon(
5205 UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
5206 .set(|o| o.pid = Some(pid))
5207 .build(),
5208 )
5209 .await
5210 .unwrap();
5211 assert!(running.start_time.is_some());
5212 assert_eq!(running.start_time, PROCS.start_time(pid));
5213 let stop_epoch = SUPERVISOR.stop_epoch(&opts.id);
5214
5215 std::fs::write(
5216 env::CWD.join("pitchfork.toml"),
5217 "[settings.supervisor]\nuser = 'unsupported-account'\n",
5218 )
5219 .unwrap();
5220 reload_settings();
5221 assert_eq!(settings().supervisor.user, "unsupported-account");
5222 opts.retry_count = 1;
5223 let response = SUPERVISOR
5224 .claim_or_defer(&opts, &mut guard, &mut restart_mark, None)
5225 .await
5226 .unwrap();
5227
5228 assert!(
5230 child.try_wait().unwrap().is_none(),
5231 "the live instance was stopped"
5232 );
5233 let preserved = SUPERVISOR.get_daemon(&opts.id).await.unwrap();
5234 assert_eq!(preserved.pid, Some(pid));
5235 assert!(preserved.status.is_running());
5236 assert_eq!(
5237 serde_json::to_value(&preserved).unwrap(),
5238 serde_json::to_value(&running).unwrap()
5239 );
5240 assert_eq!(SUPERVISOR.stop_epoch(&opts.id), stop_epoch);
5241 assert!(!retrying_claim.is_cancelled());
5242 assert!(restart_mark.is_none());
5243 assert!(matches!(response, Some(IpcResponse::DaemonFailed { .. })));
5244 drop(guard.take());
5245 child.kill().await.unwrap();
5246 child.wait().await.unwrap();
5247
5248 opts.id = DaemonId::new("windows-retry", "pidless");
5251 guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
5252 SUPERVISOR
5253 .upsert_daemon(
5254 UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Errored(7)).build(),
5255 )
5256 .await
5257 .unwrap();
5258 assert!(matches!(
5259 SUPERVISOR
5260 .claim_or_defer(&opts, &mut guard, &mut restart_mark, None)
5261 .await
5262 .unwrap(),
5263 Some(IpcResponse::DaemonFailed { .. })
5264 ));
5265 let failed = SUPERVISOR.get_daemon(&opts.id).await.unwrap();
5266 assert!(failed.status.is_failed());
5267 assert!(failed.pid.is_none());
5268 assert_eq!(failed.retry_count, 1);
5269 assert_eq!(failed.retry, Retry(2));
5270 }
5271}
5272
5273#[cfg(test)]
5274mod output_reader_tests {
5275 use super::{forward_output_lines, output_line_text};
5276
5277 #[test]
5278 fn line_endings_are_removed() {
5279 assert_eq!(output_line_text(b"ready\n"), "ready");
5280 assert_eq!(output_line_text(b"ready\r\n"), "ready");
5282 assert_eq!(output_line_text(b"ready\r\r\n"), "ready");
5283 assert_eq!(output_line_text(b"ready"), "ready");
5285 }
5286
5287 #[tokio::test]
5288 async fn a_line_that_is_not_utf8_does_not_end_the_read() {
5289 let output: &[u8] = b"before\nbad \xff\xfe bytes\nafter 1\nafter 2\nlast";
5292 let (tx, mut rx) = tokio::sync::mpsc::channel(16);
5293 forward_output_lines(tokio::io::BufReader::new(output), tx, None).await;
5294
5295 let mut lines = Vec::new();
5296 while let Some(line) = rx.recv().await {
5297 lines.push(line.text);
5298 }
5299 assert_eq!(lines.len(), 5, "{lines:?}");
5300 assert_eq!(lines[0], "before");
5301 assert!(lines[1].starts_with("bad "), "{:?}", lines[1]);
5302 assert_eq!(&lines[2..], ["after 1", "after 2", "last"]);
5303 }
5304}
5305
5306#[cfg(test)]
5307mod output_reader_eio_tests {
5308 use super::forward_output_lines;
5309 use std::pin::Pin;
5310 use std::task::{Context, Poll};
5311
5312 struct EndsWithEio(Option<&'static [u8]>);
5315
5316 impl tokio::io::AsyncRead for EndsWithEio {
5317 fn poll_read(
5318 mut self: Pin<&mut Self>,
5319 _cx: &mut Context<'_>,
5320 buf: &mut tokio::io::ReadBuf<'_>,
5321 ) -> Poll<std::io::Result<()>> {
5322 match self.0.take() {
5323 Some(bytes) => {
5324 buf.put_slice(bytes);
5325 Poll::Ready(Ok(()))
5326 }
5327 None => Poll::Ready(Err(std::io::Error::from_raw_os_error(5))),
5328 }
5329 }
5330 }
5331
5332 #[tokio::test]
5333 async fn a_last_line_cut_off_by_eio_is_still_forwarded() {
5334 let reader = tokio::io::BufReader::new(EndsWithEio(Some(b"first\nlast without newline")));
5335 let (tx, mut rx) = tokio::sync::mpsc::channel(16);
5336 forward_output_lines(reader, tx, None).await;
5337
5338 let mut lines = Vec::new();
5339 while let Some(line) = rx.recv().await {
5340 lines.push(line.text);
5341 }
5342 assert_eq!(lines, ["first", "last without newline"]);
5343 }
5344}
5345
5346#[cfg(all(test, unix))] mod readiness_tests;