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
434async fn forward_output_lines<R>(mut reader: R, tx: tokio::sync::mpsc::Sender<super::OutputLine>)
441where
442 R: tokio::io::AsyncBufRead + Unpin,
443{
444 use tokio::io::AsyncBufReadExt;
445 let mut line = Vec::new();
446 loop {
447 line.clear();
448 let last = match reader.read_until(b'\n', &mut line).await {
453 Ok(0) => break,
454 Ok(_) => false,
455 Err(_) if line.is_empty() => break,
456 Err(_) => true,
457 };
458 let sent = tx
459 .send(super::OutputLine {
460 text: output_line_text(&line),
461 source: super::OutputSource::Local,
462 })
463 .await;
464 if sent.is_err() || last {
465 break;
466 }
467 }
468}
469
470fn stop_keeps_finalized_status(status: &DaemonStatus) -> bool {
471 status.is_completed()
472}
473
474const SINK_OUTPUT_TIMEOUT: Duration = Duration::from_millis(400);
479
480struct StopEpochGuard(DaemonId);
487
488impl Drop for StopEpochGuard {
489 fn drop(&mut self) {
490 SUPERVISOR.bump_stop_epoch(&self.0);
491 }
492}
493
494pub(crate) struct RetryingGuard {
495 id: DaemonId,
496 cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
497}
498
499impl RetryingGuard {
500 fn is_cancelled(&self) -> bool {
502 self.cancel.load(std::sync::atomic::Ordering::Acquire)
503 }
504}
505
506impl Drop for RetryingGuard {
507 fn drop(&mut self) {
508 let mut retrying = SUPERVISOR
509 .retrying
510 .lock()
511 .unwrap_or_else(|e| e.into_inner());
512 if let Some(claims) = retrying.get_mut(&self.id) {
516 claims.retain(|claim| !std::sync::Arc::ptr_eq(&claim.cancel, &self.cancel));
517 if claims.is_empty() {
518 retrying.remove(&self.id);
519 }
520 }
521 }
522}
523
524impl Supervisor {
525 pub(crate) fn is_retrying(&self, id: &DaemonId) -> bool {
527 self.retrying
528 .lock()
529 .unwrap_or_else(|e| e.into_inner())
530 .get(id)
531 .is_some_and(|claims| !claims.is_empty())
532 }
533
534 pub(crate) fn stop_epoch(&self, id: &DaemonId) -> u64 {
536 self.stop_epochs
537 .lock()
538 .unwrap_or_else(|e| e.into_inner())
539 .get(id)
540 .copied()
541 .unwrap_or(0)
542 }
543
544 fn bump_stop_epoch(&self, id: &DaemonId) {
545 *self
546 .stop_epochs
547 .lock()
548 .unwrap_or_else(|e| e.into_inner())
549 .entry(id.clone())
550 .or_default() += 1;
551 }
552
553 pub(super) fn mark_retrying(&self, id: &DaemonId) -> RetryingGuard {
554 self.mark_retrying_with_result(id, None)
555 }
556
557 fn mark_retrying_with_result(
558 &self,
559 id: &DaemonId,
560 result: Option<&super::StartResult>,
561 ) -> RetryingGuard {
562 let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
563 self.retrying
564 .lock()
565 .unwrap_or_else(|e| e.into_inner())
566 .entry(id.clone())
567 .or_default()
568 .push(super::RetryClaim {
569 cancel: cancel.clone(),
570 result: result.cloned(),
571 });
572 RetryingGuard {
573 id: id.clone(),
574 cancel,
575 }
576 }
577
578 fn retry_result(
579 &self,
580 id: &DaemonId,
581 own_result: Option<&super::StartResult>,
582 ) -> Option<super::StartResult> {
583 self.retrying
584 .lock()
585 .unwrap_or_else(|e| e.into_inner())
586 .get(id)?
587 .iter()
588 .filter(|claim| !claim.cancel.load(atomic::Ordering::Acquire))
589 .filter_map(|claim| claim.result.as_ref())
590 .find(|result| own_result.is_none_or(|own| !own.same_channel(result)))
591 .cloned()
592 }
593
594 pub(crate) fn cancel_retrying(&self, id: &DaemonId) {
598 if let Some(claims) = self
599 .retrying
600 .lock()
601 .unwrap_or_else(|e| e.into_inner())
602 .get(id)
603 {
604 for claim in claims {
608 claim
609 .cancel
610 .store(true, std::sync::atomic::Ordering::Release);
611 }
612 }
613 }
614
615 pub async fn run(&self, opts: RunOptions) -> Result<IpcResponse> {
617 let id = opts.id.clone();
618 let mut restart_mark = None;
619 let (result_tx, result_rx) = tokio::sync::watch::channel(None);
624 let wait_ready = opts.wait_ready;
625 let result = self
626 .run_inner(
627 opts,
628 None,
629 &mut restart_mark,
630 wait_ready.then_some(&result_rx),
631 )
632 .await;
633 if let Some(mark) = restart_mark {
636 self.settle_restarting(&id, mark).await;
637 }
638 result_tx.send_replace(Some(match &result {
639 Ok(response) => response.clone(),
640 Err(e) => IpcResponse::Error(e.to_string()),
641 }));
642 result
643 }
644
645 pub(crate) async fn settle_restarting(&self, id: &DaemonId, mark: u64) {
654 let lock = self.stop_lock(id).await;
655 let _guard = lock.lock().await;
656 if self.stop_epoch(id) != mark {
657 return;
658 }
659 let mut state_file = self.state_file.lock().await;
660 if state_file
661 .daemons
662 .get(id)
663 .is_some_and(|d| d.pid.is_none() && d.status.is_restarting())
664 {
665 debug!("daemon {id} was not started again after its restart; recording it as stopped");
666 state_file.set_status(id, DaemonStatus::Stopped);
667 }
668 }
669
670 pub(crate) async fn run_retry(
677 &self,
678 opts: RunOptions,
679 approved_at: u64,
680 restart_mark: &mut Option<u64>,
681 ) -> Result<IpcResponse> {
682 let (result_tx, result_rx) = tokio::sync::watch::channel(None);
683 let wait_ready = opts.wait_ready;
684 let result = self
685 .run_inner(
686 opts,
687 Some(approved_at),
688 restart_mark,
689 wait_ready.then_some(&result_rx),
690 )
691 .await;
692 result_tx.send_replace(Some(match &result {
693 Ok(response) => response.clone(),
694 Err(error) => IpcResponse::Error(error.to_string()),
695 }));
696 result
697 }
698
699 #[cfg(windows)]
701 async fn reject_unsupported_windows_options(
702 &self,
703 opts: &RunOptions,
704 ) -> Result<Option<IpcResponse>> {
705 let Some(error) = unsupported_windows_options(opts, &settings().supervisor.user) else {
706 return Ok(None);
707 };
708 if self
712 .get_daemon(&opts.id)
713 .await
714 .is_none_or(|d| d.pid.is_none())
715 {
716 self.upsert_daemon(
717 UpsertDaemonOpts::from_run_options(opts, DaemonStatus::Failed(error.clone()))
718 .build(),
719 )
720 .await?;
721 }
722 Ok(Some(IpcResponse::DaemonFailed { error }))
723 }
724
725 async fn run_inner(
732 &self,
733 opts: RunOptions,
734 approved_at: Option<u64>,
735 restart_mark: &mut Option<u64>,
736 start_result: Option<&super::StartResult>,
737 ) -> Result<IpcResponse> {
738 let id = &opts.id;
739 let cmd = opts.cmd.clone();
740
741 {
743 let mut pending = self.pending_autostops.lock().await;
744 if pending.remove(id).is_some() {
745 info!("cleared pending autostop for {id} (daemon starting)");
746 }
747 }
748
749 let mut stop_guard = Some(self.stop_lock(id).await.lock_owned().await);
760 if let Some(approved_at) = approved_at
765 && self.stop_epoch(id) != approved_at
766 {
767 info!("daemon {id} was stopped after this retry was decided on; not starting it");
768 return Ok(IpcResponse::DaemonNotRunning);
769 }
770 if (approved_at.is_some() || !opts.requested_by_client)
774 && self.state_file.lock().await.disabled.contains(id)
775 {
776 info!("daemon {id} was disabled before this start; not starting it");
777 return Ok(IpcResponse::DaemonNotRunning);
778 }
779 if let Some(response) = self
780 .claim_or_defer(&opts, &mut stop_guard, restart_mark, start_result)
781 .await?
782 {
783 return Ok(response);
784 }
785
786 if opts.wait_ready && opts.retry.count() > 0 {
788 let retrying_claim = self.mark_retrying_with_result(id, start_result);
793 let max_attempts = opts.retry.count().saturating_add(1);
795 let first_attempt = if approved_at.is_some() {
796 opts.retry_count
797 } else {
798 0
799 };
800 for attempt in first_attempt..max_attempts {
801 let mut retry_opts = opts.clone();
802 retry_opts.retry_count = attempt;
803 retry_opts.cmd = cmd.clone();
804
805 let mut guard = Some(match stop_guard.take() {
809 Some(guard) => guard,
810 None => self.stop_lock(id).await.lock_owned().await,
811 });
812 if attempt > 0
822 && let Some(daemon) = self.get_daemon(id).await
823 && daemon.status.is_completed()
824 {
825 info!("daemon {id} completed while waiting to retry; not running it again");
826 return Ok(IpcResponse::DaemonReady { daemon });
827 }
828 if attempt > 0 && self.state_file.lock().await.disabled.contains(id) {
832 info!(
833 "daemon {id} was disabled while waiting to retry; abandoning its retries"
834 );
835 return Ok(IpcResponse::DaemonFailed {
836 error: "disabled while retrying".to_string(),
837 });
838 }
839 if retrying_claim.is_cancelled() {
844 info!("daemon {id} was stopped while waiting to retry; abandoning its retries");
845 return Ok(IpcResponse::DaemonFailed {
846 error: "stopped while retrying".to_string(),
847 });
848 }
849 if let Some(response) = self
855 .claim_or_defer(&retry_opts, &mut guard, restart_mark, start_result)
856 .await?
857 {
858 return Ok(response);
859 }
860 let Some(guard) = guard else {
861 return Ok(IpcResponse::DaemonAlreadyRunning);
864 };
865 let result = self.run_once(retry_opts, guard, start_result).await?;
866
867 match result {
868 IpcResponse::DaemonReady { daemon } => {
869 return Ok(IpcResponse::DaemonReady { daemon });
870 }
871 IpcResponse::DaemonFailedWithCode {
872 exit_code,
873 resolved_ports,
874 } => {
875 if attempt < opts.retry.count() {
876 let attempt_pid = self.get_daemon(id).await.and_then(|d| d.pid);
884 self.wait_for_exit_finalized(id, attempt_pid).await;
885 let backoff_secs = 2u64.saturating_pow(attempt).min(3600);
886 info!(
887 "daemon {id} failed (attempt {}/{}), retrying in {}s",
888 attempt + 1,
889 max_attempts,
890 backoff_secs
891 );
892 fire_hook(
893 HookType::OnRetry,
894 id.clone(),
895 super::hooks::HookDirs::new(
896 opts.dir.0.clone(),
897 opts.watch_base_dir.clone(),
898 ),
899 attempt + 1,
900 opts.env.clone(),
901 resolved_ports,
902 vec![],
903 )
904 .await;
905 let backoff_deadline =
910 tokio::time::Instant::now() + Duration::from_secs(backoff_secs);
911 while tokio::time::Instant::now() < backoff_deadline
912 && !retrying_claim.is_cancelled()
913 {
914 let remaining = backoff_deadline - tokio::time::Instant::now();
915 time::sleep(remaining.min(Duration::from_millis(200))).await;
916 }
917 continue;
918 } else {
919 info!("daemon {id} failed after {max_attempts} attempts");
920 return Ok(IpcResponse::DaemonFailedWithCode {
921 exit_code,
922 resolved_ports,
923 });
924 }
925 }
926 other => return Ok(other),
927 }
928 }
929 }
930
931 let guard = match stop_guard.take() {
933 Some(guard) => guard,
934 None => self.stop_lock(id).await.lock_owned().await,
935 };
936 self.run_once(opts, guard, start_result).await
937 }
938
939 async fn wait_for_exit_finalized(&self, id: &DaemonId, pid: Option<u32>) {
950 let deadline = tokio::time::Instant::now() + Duration::from_secs(8);
951 loop {
952 match self.get_daemon(id).await {
953 Some(daemon) if pid.map_or(daemon.pid.is_some(), |pid| daemon.pid == Some(pid)) => {
954 }
955 _ => return,
956 }
957 if tokio::time::Instant::now() >= deadline {
958 debug!("daemon {id}: previous attempt has not finalized yet; continuing anyway");
959 return;
960 }
961 time::sleep(Duration::from_millis(50)).await;
962 }
963 }
964
965 async fn claim_or_defer(
980 &self,
981 opts: &RunOptions,
982 stop_guard: &mut Option<tokio::sync::OwnedMutexGuard<()>>,
983 restart_mark: &mut Option<u64>,
984 own_result: Option<&super::StartResult>,
985 ) -> Result<Option<IpcResponse>> {
986 let id = &opts.id;
987 #[cfg(windows)]
988 if let Some(response) = self.reject_unsupported_windows_options(opts).await? {
989 return Ok(Some(response));
990 }
991 if !opts.force
992 && let Some(result) = self.retry_result(id, own_result)
993 {
994 if !opts.wait_ready {
995 return Ok(Some(IpcResponse::DaemonAlreadyRunning));
996 }
997 info!("daemon {id} has a start sequence in progress; waiting for it");
998 let fallback = self
999 .ready_check(id)
1000 .filter(|check| check.result.same_channel(&result))
1001 .map(|check| check.attempt);
1002 let oneshot = self
1003 .get_daemon(id)
1004 .await
1005 .filter(|daemon| daemon.oneshot)
1006 .map(|daemon| daemon.pid.unwrap_or(0));
1007 drop(stop_guard.take());
1008 if let Some(pid) = oneshot {
1009 return Ok(Some(
1011 self.await_running_oneshot(id, opts.oneshot_wait, pid).await,
1012 ));
1013 }
1014 return Ok(Some(await_start_result(result, fallback).await));
1015 }
1016 let Some(daemon) = self.get_daemon(id).await else {
1017 return Ok(None);
1018 };
1019 if opts.on_directory_enter && opts.oneshot && daemon.status.is_completed() {
1030 debug!("daemon {id} already completed; directory entry leaves it alone");
1031 return Ok(Some(IpcResponse::DaemonReady { daemon }));
1032 }
1033 if daemon.status.is_stopping_or_restarting()
1037 || daemon.status.is_stopped()
1038 || daemon.status.is_completed()
1039 {
1040 return Ok(None);
1041 }
1042 let Some(pid) = daemon.pid else {
1043 return Ok(None);
1044 };
1045 if opts.force {
1046 self.stop_locked_with(id, true).await?;
1050 *restart_mark = Some(self.stop_epoch(id));
1053 info!("run: stop completed for daemon {id}");
1054 return Ok(None);
1055 }
1056 if daemon.oneshot && opts.wait_ready {
1057 info!("daemon {id} is an in-flight oneshot (pid {pid}); waiting for it to finish");
1062 drop(stop_guard.take());
1063 return Ok(Some(
1064 self.await_running_oneshot(id, opts.oneshot_wait, pid).await,
1065 ));
1066 }
1067 if opts.wait_ready
1068 && let Some(check) = self.ready_check(id)
1069 && check.pid == pid
1070 {
1071 info!("daemon {id} (pid {pid}) has not passed its ready check; waiting for it");
1077 drop(stop_guard.take());
1078 return Ok(Some(
1079 await_start_result(check.result, Some(check.attempt)).await,
1080 ));
1081 }
1082 if let DaemonStatus::Failed(error) = &daemon.status
1083 && PROCS.process_group_alive(pid)
1084 {
1085 return Ok(Some(IpcResponse::DaemonFailed {
1086 error: error.clone(),
1087 }));
1088 }
1089 PROCS.refresh_pids(&[pid]);
1100 if !PROCS.is_running(pid) {
1101 debug!(
1102 "daemon {id}: record still names pid {pid}, which has exited; its monitor has not finalized yet"
1103 );
1104 return Ok(None);
1105 }
1106 warn!("daemon {id} already running with pid {pid}");
1107 Ok(Some(IpcResponse::DaemonAlreadyRunning))
1108 }
1109
1110 async fn await_running_oneshot(
1117 &self,
1118 id: &DaemonId,
1119 wait: Option<OneshotWait>,
1120 watched_pid: u32,
1121 ) -> IpcResponse {
1122 let interval = settings().supervisor_ready_check_interval();
1123 let deadline = wait
1139 .unwrap_or_else(|| settings().supervisor_oneshot_wait())
1140 .duration()
1141 .map(|d| tokio::time::Instant::now() + d);
1142 let mut watched_pid = watched_pid;
1150 loop {
1151 let Some(daemon) = self.get_daemon(id).await else {
1152 return IpcResponse::DaemonNotFound;
1153 };
1154 if let Some(current) = daemon.pid
1155 && current != watched_pid
1156 {
1157 info!(
1158 "daemon {id}: the run being waited on (pid {watched_pid}) was replaced by pid {current}; following it"
1159 );
1160 watched_pid = current;
1161 }
1162 match &daemon.status {
1163 DaemonStatus::Completed => {
1164 info!("daemon {id}: the in-flight oneshot completed");
1165 return IpcResponse::DaemonReady { daemon };
1166 }
1167 DaemonStatus::Errored(code) => {
1168 if daemon.retry.count() > 0
1176 && daemon.retry_count < daemon.retry.count()
1177 && !self.state_file.lock().await.disabled.contains(id)
1178 {
1179 debug!(
1180 "daemon {id}: in-flight oneshot failed attempt {} of {}; still waiting",
1181 daemon.retry_count + 1,
1182 daemon.retry.count() + 1
1183 );
1184 } else {
1185 let exit_code = Some(*code).filter(|c| *c != -1);
1189 return IpcResponse::DaemonFailedWithCode {
1190 exit_code,
1191 resolved_ports: daemon.resolved_port.clone(),
1192 };
1193 }
1194 }
1195 DaemonStatus::Failed(error) => {
1196 return IpcResponse::DaemonFailed {
1197 error: error.clone(),
1198 };
1199 }
1200 DaemonStatus::Stopped => {
1201 warn!("daemon {id}: the in-flight oneshot was stopped before completing");
1204 return IpcResponse::DaemonFailedWithCode {
1205 exit_code: None,
1206 resolved_ports: daemon.resolved_port.clone(),
1207 };
1208 }
1209 DaemonStatus::Running
1210 | DaemonStatus::Waiting
1211 | DaemonStatus::Stopping
1212 | DaemonStatus::Restarting => {}
1213 }
1214 if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
1215 warn!("daemon {id}: gave up waiting for the in-flight oneshot to finish");
1216 return IpcResponse::DaemonFailedWithCode {
1222 exit_code: Some(124),
1223 resolved_ports: Vec::new(),
1224 };
1225 }
1226 time::sleep(interval).await;
1227 }
1228 }
1229
1230 fn register_ready_check(
1232 &self,
1233 id: &DaemonId,
1234 pid: u32,
1235 start_result: &super::StartResult,
1236 attempt: &super::StartResult,
1237 ) {
1238 self.ready_checks
1239 .lock()
1240 .unwrap_or_else(|e| e.into_inner())
1241 .insert(
1242 id.clone(),
1243 super::ReadyCheck {
1244 pid,
1245 result: start_result.clone(),
1246 attempt: attempt.clone(),
1247 },
1248 );
1249 }
1250
1251 fn ready_check(&self, id: &DaemonId) -> Option<super::ReadyCheck> {
1253 self.ready_checks
1254 .lock()
1255 .unwrap_or_else(|e| e.into_inner())
1256 .get(id)
1257 .cloned()
1258 }
1259
1260 fn end_ready_check(&self, id: &DaemonId, attempt: &super::StartResult) {
1265 let mut ready_checks = self.ready_checks.lock().unwrap_or_else(|e| e.into_inner());
1266 if ready_checks
1267 .get(id)
1268 .is_some_and(|check| check.attempt.same_channel(attempt))
1269 {
1270 ready_checks.remove(id);
1271 }
1272 }
1273
1274 pub(crate) async fn run_once(
1281 &self,
1282 opts: RunOptions,
1283 stop_guard: tokio::sync::OwnedMutexGuard<()>,
1284 start_result: Option<&super::StartResult>,
1285 ) -> Result<IpcResponse> {
1286 let id = &opts.id;
1287 if self
1294 .shutting_down
1295 .load(std::sync::atomic::Ordering::Acquire)
1296 {
1297 info!("not starting daemon {id}: the supervisor is shutting down");
1298 return Ok(IpcResponse::DaemonFailed {
1299 error: "the supervisor is shutting down".to_string(),
1300 });
1301 }
1302 #[cfg(windows)]
1304 if let Some(response) = self.reject_unsupported_windows_options(&opts).await? {
1305 return Ok(response);
1306 }
1307 let original_cmd = opts.cmd.clone(); let (ready_tx, ready_rx) = if opts.wait_ready || !opts.oneshot {
1311 let (tx, rx) = oneshot::channel::<std::result::Result<(), ReadyFailure>>();
1312 (Some(tx), Some(rx))
1313 } else {
1314 (None, None)
1315 };
1316
1317 let expected_ports = opts
1319 .port
1320 .as_ref()
1321 .map(|p| p.expect.clone())
1322 .unwrap_or_default();
1323 let mut port_claim: Option<PortClaim> = None;
1326 let (resolved_ports, effective_ready_port) = if !expected_ports.is_empty() {
1327 let port_cfg = opts.port.as_ref().unwrap();
1328 match claim_ports(
1329 id,
1330 &expected_ports,
1331 port_cfg.auto_bump(),
1332 port_cfg.max_bump_attempts(),
1333 )
1334 .await
1335 {
1336 Ok((resolved, claim)) => {
1337 port_claim = Some(claim);
1338 let ready_port = if let Some(configured_port) =
1339 opts.ready_port.as_ref().and_then(|p| p.as_port())
1340 {
1341 Some(resolve_configured_ready_port(
1342 configured_port,
1343 &expected_ports,
1344 &resolved,
1345 ))
1346 } else if opts.ready_output.is_none()
1347 && opts.ready_http.is_none()
1348 && opts.ready_cmd.is_none()
1349 && opts.ready_delay.is_none()
1350 {
1351 resolved.first().copied().filter(|&p| p != 0)
1355 } else {
1356 None
1360 };
1361 info!("daemon {id}: ports {expected_ports:?} resolved to {resolved:?}");
1362 (resolved, ready_port)
1363 }
1364 Err(e) => {
1365 error!("daemon {id}: port check failed: {e}");
1366 if let Some(port_error) = e.downcast_ref::<PortError>() {
1368 match port_error {
1369 PortError::Claimed { .. } => {
1370 return Ok(IpcResponse::DaemonFailed {
1371 error: e.to_string(),
1372 });
1373 }
1374 PortError::InUse {
1375 port,
1376 address,
1377 process,
1378 pid,
1379 } => {
1380 return Ok(IpcResponse::PortConflict {
1381 port: *port,
1382 process: process.clone(),
1383 pid: *pid,
1384 address: address.clone(),
1385 });
1386 }
1387 PortError::NoAvailablePort {
1388 start_port,
1389 attempts,
1390 } => {
1391 return Ok(IpcResponse::NoAvailablePort {
1392 start_port: *start_port,
1393 attempts: *attempts,
1394 });
1395 }
1396 }
1397 }
1398 return Ok(IpcResponse::DaemonFailed {
1399 error: e.to_string(),
1400 });
1401 }
1402 }
1403 } else {
1404 if let Some(port) = opts.ready_port.as_ref().and_then(|p| p.as_port())
1410 && port > 0
1411 {
1412 match claim_ports(id, &[port], false, 0).await {
1413 Ok((_, claim)) => port_claim = Some(claim),
1414 Err(e)
1415 if matches!(
1416 e.downcast_ref::<PortError>(),
1417 Some(PortError::Claimed { .. })
1418 ) =>
1419 {
1420 return Ok(IpcResponse::DaemonFailed {
1421 error: e.to_string(),
1422 });
1423 }
1424 Err(_) => {}
1426 }
1427 }
1428 if let Some(port) = opts.ready_port.as_ref().and_then(|p| p.as_port())
1429 && port > 0
1430 && let Some((address, pid, process)) = detect_port_conflict(port).await
1431 {
1432 return Ok(IpcResponse::PortConflict {
1433 port,
1434 process,
1435 pid,
1436 address: Some(address),
1437 });
1438 }
1439 (
1440 Vec::new(),
1441 opts.ready_port.as_ref().and_then(|p| p.as_port()),
1442 )
1443 };
1444
1445 if let Some(error) = invalid_probe_program(
1450 id,
1451 "ready_cmd",
1452 opts.ready_cmd.as_ref().map(|c| &c.run),
1453 )
1454 .or_else(|| {
1455 invalid_probe_program(id, "health_cmd", opts.health_cmd.as_ref().map(|c| &c.run))
1456 }) {
1457 return Ok(IpcResponse::DaemonFailed { error });
1458 }
1459
1460 let (mut words, script) = if opts.no_shell {
1461 if let Some(error) = invalid_argv_program(id, &original_cmd) {
1464 return Ok(IpcResponse::DaemonFailed { error });
1465 }
1466 (original_cmd.clone(), None)
1467 } else {
1468 let words = match resolve_shell() {
1472 Ok(parts) => parts,
1473 Err(error) => return Ok(IpcResponse::DaemonFailed { error }),
1474 };
1475 let script = opts
1480 .run
1481 .clone()
1482 .unwrap_or_else(|| shell_words::join(&original_cmd));
1483 (words, Some(script))
1484 };
1485
1486 let mise_bin = if opts.mise.unwrap_or(settings().general.mise) {
1487 let mise_bin = settings().resolve_daemon_mise_bin(opts.mise_bin.as_deref());
1488 if mise_bin.is_none() {
1489 warn!("daemon {id}: mise=true but mise binary not found, running without mise");
1490 }
1491 mise_bin
1492 } else {
1493 None
1494 };
1495 if mise_bin.is_none() && opts.deferred_template_context.is_some() {
1499 return Ok(IpcResponse::DaemonFailed {
1500 error: format!(
1501 "daemon {id}: the command uses template variables only mise can render, but mise is not enabled or its binary was not found"
1502 ),
1503 });
1504 }
1505 let script = match &mise_bin {
1510 Some(mise_bin) => {
1511 info!(
1512 "daemon {id}: wrapping command with mise ({})",
1513 mise_bin.display()
1514 );
1515 if let Some(script) = script {
1516 words =
1517 mise_shell_words(words, script, opts.deferred_template_context.is_some());
1518 }
1519 None
1520 }
1521 None => script,
1522 };
1523 let (program, args) = launch_command(words, mise_bin.as_deref());
1524 #[cfg(unix)]
1525 let run_identity = match resolve_effective_run_identity(opts.user.as_deref()) {
1526 Ok(identity) => identity,
1527 Err(e) => {
1528 return Ok(IpcResponse::DaemonFailed {
1529 error: e.to_string(),
1530 });
1531 }
1532 };
1533 info!("run: spawning daemon {id} with {program} {args:?} {script:?}");
1534
1535 #[cfg(unix)]
1537 let pty_pair = if opts.pty.unwrap_or(false) {
1538 match super::pty::openpty() {
1539 Ok(pair) => {
1540 info!("daemon {id}: allocated PTY (pty = true)");
1541 Some(pair)
1542 }
1543 Err(e) => {
1544 warn!("daemon {id}: failed to allocate PTY, falling back to pipes: {e}");
1545 None
1546 }
1547 }
1548 } else {
1549 None
1550 };
1551
1552 let (output_tx, output_rx) = tokio::sync::mpsc::channel::<super::OutputLine>(256);
1558 let mut output_relay = None;
1559
1560 let mut sink_pipe = None;
1563 let mut sink_writer = None;
1564 let mut sink_child = None;
1565 if super::log_sink::is_supported(&opts) {
1566 let log_format = opts
1567 .log_format
1568 .clone()
1569 .unwrap_or_else(|| settings().logs.log_format.clone());
1570 let watch_for = super::log_sink::WatchFor::from_opts(id, &opts);
1571 let relay_token = if watch_for.is_empty() {
1574 0
1575 } else {
1576 let relay = super::log_sink::OutputRelay::register(id, output_tx.clone());
1577 let token = relay.token();
1578 output_relay = Some(relay);
1579 token
1580 };
1581 match super::log_sink::SinkPipe::new(log_format, watch_for, relay_token) {
1582 Ok((pipe, writer)) => match pipe.start(id) {
1583 Ok(child) => {
1584 sink_child = Some(super::log_sink::PendingSink::new(child));
1585 sink_pipe = Some(pipe);
1586 sink_writer = Some(writer);
1587 }
1588 Err(e) => {
1589 warn!("could not start log sink for {id}, capturing in-process: {e}");
1590 }
1591 },
1592 Err(e) => {
1593 warn!("could not create log pipe for {id}, capturing in-process: {e}");
1596 }
1597 }
1598 }
1599
1600 let mut cmd = tokio::process::Command::new(&program);
1601
1602 #[cfg(unix)]
1603 if let Some(ref pair) = pty_pair {
1604 let slave_file = std::fs::File::from(
1608 pair.slave
1609 .try_clone()
1610 .map_err(|e| miette::miette!("failed to dup slave PTY fd: {e}"))?,
1611 );
1612 cmd.stdin(std::process::Stdio::from(slave_file.try_clone().map_err(
1613 |e| miette::miette!("failed to clone slave PTY fd for stdin: {e}"),
1614 )?));
1615 cmd.stdout(std::process::Stdio::from(slave_file.try_clone().map_err(
1616 |e| miette::miette!("failed to clone slave PTY fd for stdout: {e}"),
1617 )?));
1618 cmd.stderr(std::process::Stdio::from(slave_file));
1619 } else if let Some(writer) = sink_writer.take() {
1620 let dup = writer
1623 .try_clone()
1624 .map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
1625 cmd.stdout(std::process::Stdio::from(writer))
1626 .stderr(std::process::Stdio::from(dup));
1627 } else {
1628 cmd.stdout(std::process::Stdio::piped())
1629 .stderr(std::process::Stdio::piped());
1630 }
1631
1632 #[cfg(not(unix))]
1633 if let Some(writer) = sink_writer.take() {
1634 let dup = writer
1635 .try_clone()
1636 .map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
1637 cmd.stdout(std::process::Stdio::from(writer))
1638 .stderr(std::process::Stdio::from(dup));
1639 } else {
1640 cmd.stdout(std::process::Stdio::piped())
1641 .stderr(std::process::Stdio::piped());
1642 }
1643
1644 match &script {
1645 Some(script) => cmd.shell_script(&program, &args, script),
1646 None => cmd.args(&args),
1647 };
1648 cmd.current_dir(&opts.dir)
1649 .hide_console_window()
1650 .close_inherited_fds();
1651
1652 #[cfg(unix)]
1653 if pty_pair.is_none() {
1654 cmd.stdin(std::process::Stdio::null());
1655 }
1656
1657 #[cfg(not(unix))]
1658 cmd.stdin(std::process::Stdio::null());
1659
1660 #[cfg(unix)]
1662 apply_identity_env(&mut cmd, &run_identity);
1663 apply_runtime_env(
1664 &mut cmd,
1665 id,
1666 opts.retry_count,
1667 opts.env.as_ref(),
1668 &resolved_ports,
1669 );
1670 if let Some(context) = &opts.deferred_template_context {
1672 cmd.env(crate::template::TEMPLATE_CONTEXT_ENV, context);
1673 }
1674
1675 inject_proxy_env(&mut cmd, &daemon_proxy_host(&opts).await);
1677
1678 #[cfg(unix)]
1679 {
1680 let run_identity = run_identity.clone();
1681 let use_pty = pty_pair.is_some();
1682 unsafe {
1683 cmd.pre_exec(move || {
1684 nix::unistd::setsid().map_err(nix_to_io_error)?;
1685
1686 if use_pty {
1690 let ret = libc::ioctl(0, libc::TIOCSCTTY as _, 0);
1691 if ret < 0 {
1692 #[cfg(target_os = "linux")]
1695 eprintln!(
1696 "pitchfork: TIOCSCTTY failed: {}",
1697 std::io::Error::last_os_error()
1698 );
1699 }
1700 }
1701
1702 apply_run_identity(&run_identity)?;
1703 Ok(())
1704 });
1705 }
1706 }
1707
1708 let spawn_time = chrono::Local::now();
1711 let mut child = cmd.spawn().into_diagnostic()?;
1717 #[cfg(windows)]
1720 if let (Some(pid), Some(process)) = (child.id(), child.raw_handle()) {
1721 crate::win_job::contain_spawned(process as _, pid);
1722 }
1723 let spawned_pid = child.id();
1724 let monitored_guard =
1734 spawned_pid.map(|pid| super::adopt::MonitoredGuard::register(id.clone(), pid));
1735 if opts.cron_started {
1751 let mut state_file = self.state_file.lock().await;
1752 if state_file.set_last_cron_run(id, spawn_time)
1753 && let Err(e) = state_file.write()
1754 {
1755 error!("failed to persist last_cron_run for daemon {id}: {e}");
1756 }
1757 }
1758 let (pid, monitored_guard) = match (spawned_pid, monitored_guard) {
1759 (Some(p), Some(guard)) => (p, guard),
1760 _ => {
1761 warn!("Daemon {id} exited before PID could be captured");
1762 if sink_child.is_some() {
1768 super::log_sink::wait_for_output(id, spawn_time, SINK_OUTPUT_TIMEOUT).await;
1769 }
1770 return Ok(IpcResponse::DaemonFailed {
1771 error: "Process exited immediately".to_string(),
1772 });
1773 }
1774 };
1775 info!("started daemon {id} with pid {pid}");
1776 PROCS.refresh_pids(&[pid]);
1777 let monitor_token = monitored_guard.token();
1778
1779 let using_sink = sink_pipe.is_some();
1782 if let Some(pipe) = sink_pipe.take()
1785 && let Some(child) = sink_child.as_mut().and_then(|pending| pending.take())
1786 {
1787 pipe.supervise(id.clone(), monitor_token, child);
1788 }
1789 let attempt_resolved_ports = resolved_ports.clone();
1796 let daemon = self
1797 .upsert_daemon(
1798 UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
1799 .set(|o| {
1800 o.pid = Some(pid);
1801 o.cmd = Some(original_cmd);
1802 o.ready_port = effective_ready_port.map(|p| ReadyPort {
1803 port: Some(p),
1804 template: None,
1805 timeout: opts.ready_port.as_ref().and_then(|rp| rp.timeout),
1806 });
1807 o.port = crate::config_types::PortConfig::from_parts(
1808 expected_ports,
1809 opts.port.as_ref().map(|p| p.bump).unwrap_or_default(),
1810 );
1811 o.resolved_port = Some(resolved_ports);
1812 })
1813 .build(),
1814 )
1815 .await?;
1816
1817 let (attempt_tx, attempt_rx) = tokio::sync::watch::channel(None);
1820 if ready_rx.is_some() {
1821 self.register_ready_check(id, pid, start_result.unwrap_or(&attempt_rx), &attempt_rx);
1822 }
1823
1824 drop(stop_guard);
1829
1830 let id_clone = id.clone();
1831 let ready_delay = (!opts.oneshot).then_some(opts.ready_delay).flatten();
1839 let ready_output = (!opts.oneshot).then(|| opts.ready_output.clone()).flatten();
1840 let ready_http = (!opts.oneshot).then(|| opts.ready_http.clone()).flatten();
1841 let ready_port = (!opts.oneshot).then_some(effective_ready_port).flatten();
1842 let implicit_ready_port = ready_port.map(|p| ReadyPort {
1843 port: Some(p),
1844 template: None,
1845 timeout: None,
1846 });
1847 let ready_port_config = (!opts.oneshot)
1848 .then(|| opts.ready_port.clone())
1849 .flatten()
1850 .or(implicit_ready_port);
1851 let ready_cmd = (!opts.oneshot).then(|| opts.ready_cmd.clone()).flatten();
1852 let daemon_dir = opts.dir.0.clone();
1853 let hook_dirs =
1854 super::hooks::HookDirs::new(daemon_dir.clone(), opts.watch_base_dir.clone());
1855 let hook_retry_count = opts.retry_count;
1856 let hook_retry = opts.retry;
1857 let hook_daemon_env = opts.env.clone();
1858 let hook_resolved_ports = attempt_resolved_ports.clone();
1863 let readiness_daemon_env = opts.env.clone();
1864 let readiness_resolved_ports = attempt_resolved_ports.clone();
1865 let on_output_hook = opts.on_output_hook.clone();
1866 let has_port_config = opts.port.as_ref().is_some_and(|p| !p.expect.is_empty())
1872 || (settings().proxy.enable && is_daemon_slug_target(id));
1873 let daemon_pid = pid;
1879
1880 #[cfg(unix)]
1884 let pty_reader = pty_pair.map(|p| {
1885 tokio::io::BufReader::new(tokio::fs::File::from_std(std::fs::File::from(p.master)))
1886 });
1887 #[cfg(not(unix))]
1888 let pty_reader: Option<tokio::io::BufReader<tokio::fs::File>> = None;
1889 let stdout_reader = if pty_reader.is_none() {
1890 child.stdout.take().map(tokio::io::BufReader::new)
1891 } else {
1892 None
1893 };
1894 let stderr_reader = if pty_reader.is_none() {
1895 child.stderr.take().map(tokio::io::BufReader::new)
1896 } else {
1897 None
1898 };
1899
1900 if !using_sink
1901 && pty_reader.is_none()
1902 && (stdout_reader.is_none() || stderr_reader.is_none())
1903 {
1904 error!("Failed to capture stdout/stderr for daemon {id}");
1905 }
1906
1907 tokio::spawn(async move {
1908 let id = id_clone;
1909 let _monitored_guard = monitored_guard;
1912 let output_relay = output_relay;
1916 let mut port_claim = port_claim;
1920
1921 let mut output_rx = output_rx;
1924
1925 if let Some(reader) = pty_reader {
1926 tokio::spawn(forward_output_lines(reader, output_tx));
1930 } else {
1931 if let Some(stdout) = stdout_reader {
1936 tokio::spawn(forward_output_lines(stdout, output_tx.clone()));
1937 }
1938 if let Some(stderr) = stderr_reader {
1939 tokio::spawn(forward_output_lines(stderr, output_tx.clone()));
1940 }
1941 drop(output_tx);
1945 }
1946 let log_store = Arc::clone(&LOG_STORE);
1947 let log_format = opts
1948 .log_format
1949 .clone()
1950 .unwrap_or_else(|| crate::settings::settings().logs.log_format.clone());
1951 let parse_line = move |line: &str| crate::log_parse::parse(line, &log_format);
1952
1953 const LOG_BATCH_SIZE: usize = 100;
1954 const LOG_FLUSH_INTERVAL: Duration = Duration::from_millis(100);
1955 let mut log_buffer: Vec<crate::log_parse::ParsedLog> =
1956 Vec::with_capacity(LOG_BATCH_SIZE);
1957 let mut pending_log_writes: Vec<tokio::task::JoinHandle<()>> = Vec::new();
1958 let mut log_flush_interval = tokio::time::interval(LOG_FLUSH_INTERVAL);
1959 log_flush_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
1960
1961 let flush_logs =
1962 |buffer: &mut Vec<crate::log_parse::ParsedLog>,
1963 pending: &mut Vec<tokio::task::JoinHandle<()>>| {
1964 pending.retain(|handle| !handle.is_finished());
1965 if buffer.is_empty() {
1966 return;
1967 }
1968 let store = Arc::clone(&log_store);
1969 let id = id.clone();
1970 let batch = std::mem::take(buffer);
1971 pending.push(tokio::task::spawn_blocking(move || {
1972 if let Err(e) = store.append_structured_batch(&id, &batch) {
1973 error!("Failed to write batch to log for daemon {id}: {e}");
1974 }
1975 }))
1976 };
1977
1978 let mut ready_notified = false;
1982 let mut oneshot_completion_pending = false;
1987 let mut ready_tx = ready_tx;
1988 let ready_pattern = ready_output
1989 .as_ref()
1990 .and_then(|o| get_or_compile_regex(&o.pattern));
1991 let mut active_port_spawned = false;
1993
1994 let on_output_hook = match on_output_hook {
1998 Some(ref hook) => match hook.validate(id.name()) {
1999 Ok(()) => on_output_hook,
2000 Err(e) => {
2001 error!("{e}");
2002 None
2003 }
2004 },
2005 None => None,
2006 };
2007
2008 let on_output_pattern: Option<regex::Regex> = on_output_hook
2011 .as_ref()
2012 .and_then(|h| h.regex.as_deref().and_then(get_or_compile_regex));
2013 let on_output_debounce = on_output_hook
2014 .as_ref()
2015 .map(|h| h.debounce_duration())
2016 .unwrap_or(Duration::from_millis(1000));
2017 let mut on_output_last_fired: Option<std::time::Instant> = None;
2019
2020 let ready_delay = ready_delay.or_else(|| {
2022 (!opts.oneshot
2023 && ready_output.is_none()
2024 && ready_http.is_none()
2025 && ready_port.is_none()
2026 && ready_cmd.is_none())
2027 .then_some(0)
2028 });
2029 let mut delay_timer =
2030 ready_delay.map(|secs| Box::pin(time::sleep(Duration::from_secs(secs))));
2031
2032 let mut http_exhausted = false;
2034 let mut cmd_exhausted = false;
2035 let mut port_exhausted = false;
2036 let mut output_exhausted = false;
2037
2038 let s = settings();
2040 let ready_check_interval = s.supervisor_ready_check_interval();
2041 let http_client_timeout = s.supervisor_http_client_timeout();
2042
2043 let mut output_deadline = ready_output
2045 .as_ref()
2046 .and_then(|o| o.timeout)
2047 .map(|d| Box::pin(time::sleep(d)));
2048
2049 let mut http_check_interval = ready_http
2051 .as_ref()
2052 .map(|_| tokio::time::interval(ready_check_interval));
2053 let mut http_deadline = ready_http
2054 .as_ref()
2055 .and_then(|h| h.timeout)
2056 .map(|d| Box::pin(time::sleep(d)));
2057 let http_client = if ready_http.is_some() {
2058 Some(crate::supervisor::health::supervisor_http_client().await)
2059 } else {
2060 None
2061 };
2062 let mut http_probe: Option<HttpProbe> = None;
2063
2064 let mut port_check_interval =
2066 ready_port.map(|_| tokio::time::interval(ready_check_interval));
2067 let mut port_deadline = ready_port_config
2068 .as_ref()
2069 .and_then(|p| p.timeout)
2070 .map(|d| Box::pin(time::sleep(d)));
2071 let mut port_probe: Option<PortProbe> = None;
2072
2073 let mut cmd_probe: Option<CmdProbe> = None;
2076 let mut cmd_respawn_delay: Option<_> = None;
2077 let mut cmd_deadline = ready_cmd
2078 .as_ref()
2079 .and_then(|c| c.timeout)
2080 .map(|d| Box::pin(time::sleep(d)));
2081 if let Some(ref cmd) = ready_cmd {
2082 cmd_probe = Some(spawn_cmd_probe(
2083 &id,
2084 &cmd.run,
2085 daemon_dir.as_path(),
2086 hook_retry_count,
2087 readiness_daemon_env.as_ref(),
2088 &readiness_resolved_ports,
2089 ));
2090 }
2091
2092 let (exit_tx, mut exit_rx) =
2094 tokio::sync::mpsc::channel::<std::io::Result<std::process::ExitStatus>>(1);
2095
2096 let child_pid = child.id().unwrap_or(0);
2098 tokio::spawn(async move {
2099 let result = child.wait().await;
2100 #[cfg(all(unix, not(target_os = "linux")))]
2110 let result = match &result {
2111 Err(e) if e.raw_os_error() == Some(nix::libc::ECHILD) => {
2112 if let Some(code) = super::REAPED_STATUSES.lock().await.remove(&child_pid) {
2113 warn!(
2114 "daemon pid {child_pid} wait() got ECHILD; \
2115 recovered exit code {code} from zombie reaper"
2116 );
2117 use std::os::unix::process::ExitStatusExt;
2122 if code >= 0 {
2123 Ok(std::process::ExitStatus::from_raw(code << 8))
2124 } else {
2125 Ok(std::process::ExitStatus::from_raw((-code) & 0x7f))
2127 }
2128 } else {
2129 warn!(
2130 "daemon pid {child_pid} wait() got ECHILD but no \
2131 stashed status found; reporting as error"
2132 );
2133 result
2134 }
2135 }
2136 _ => result,
2137 };
2138 debug!("daemon pid {child_pid} wait() completed with result: {result:?}");
2139 let _ = exit_tx.send(result).await;
2140 });
2141
2142 #[allow(unused_assignments)]
2143 let mut exit_status = None;
2145
2146 if has_port_config
2152 && ready_pattern.is_none()
2153 && ready_http.is_none()
2154 && ready_port.is_none()
2155 && ready_cmd.is_none()
2156 && delay_timer.is_none()
2157 {
2158 active_port_spawned = true;
2159 detect_and_store_active_port(id.clone(), daemon_pid);
2160 }
2161
2162 let mut ready_fail_kill: Option<tokio::task::JoinHandle<Result<bool>>> = None;
2169
2170 loop {
2171 select! {
2173 biased;
2174 Some(result) = exit_rx.recv() => {
2175 exit_status = Some(result);
2177 port_claim.take();
2178 debug!("daemon {id} process exited, exit_status: {exit_status:?}");
2179 if !ready_notified {
2180 let is_success = exit_status.as_ref()
2182 .and_then(|r| r.as_ref().ok())
2183 .map(|s| s.success())
2184 .unwrap_or(false);
2185 if is_success && opts.oneshot {
2186 debug!("daemon {id} completed, deferring success notification until the completed state is persisted");
2187 oneshot_completion_pending = true;
2188 } else if let Some(tx) = ready_tx.take() {
2189 if is_success {
2190 debug!("daemon {id} exited successfully before ready check, sending success notification");
2191 let _ = tx.send(Ok(()));
2192 } else {
2193 let exit_code = exit_status.as_ref()
2194 .and_then(|r| r.as_ref().ok())
2195 .and_then(|s| s.code());
2196 debug!("daemon {id} exited with failure before ready check, sending failure notification with exit_code: {exit_code:?}");
2197 let _ = tx.send(Err(ReadyFailure::Exit(exit_code)));
2198 }
2199 }
2200 } else {
2201 debug!("daemon {id} was already marked ready, not sending notification");
2202 }
2203 break;
2204 },
2205 _ = async {
2206 if let Some(ref mut deadline) = http_deadline {
2207 deadline.await;
2208 } else {
2209 std::future::pending::<()>().await;
2210 }
2211 }, if !ready_notified && ready_http.is_some() => {
2212 http_exhausted = true;
2213 http_deadline = None;
2214 http_check_interval = None;
2215 http_probe = None;
2216 warn!("daemon {id}: HTTP readiness check timed out");
2217 let any_remaining = any_ready_check_remaining(
2218 ready_output.as_ref(),
2219 output_exhausted,
2220 ready_port_config.as_ref(),
2221 port_exhausted,
2222 ready_http.as_ref(),
2223 http_exhausted,
2224 ready_cmd.as_ref(),
2225 cmd_exhausted,
2226 );
2227 if !any_remaining {
2228 error!("daemon {id}: all readiness checks exhausted, failing");
2229 stop_cmd_probe_state(&mut cmd_probe);
2230 ready_fail_kill = Some(spawn_ready_fail_kill(
2231 id.clone(),
2232 daemon_pid,
2233 opts.stop_signal.unwrap_or_default(),
2234 ));
2235 break;
2236 }
2237 }
2238 _ = async {
2239 if let Some(ref mut deadline) = output_deadline {
2240 deadline.await;
2241 } else {
2242 std::future::pending::<()>().await;
2243 }
2244 }, if !ready_notified && ready_output.is_some() => {
2245 output_exhausted = true;
2246 output_deadline = None;
2247 warn!("daemon {id}: output readiness check timed out");
2248 let any_remaining = any_ready_check_remaining(
2249 ready_output.as_ref(),
2250 output_exhausted,
2251 ready_port_config.as_ref(),
2252 port_exhausted,
2253 ready_http.as_ref(),
2254 http_exhausted,
2255 ready_cmd.as_ref(),
2256 cmd_exhausted,
2257 );
2258 if !any_remaining {
2259 error!("daemon {id}: all readiness checks exhausted, failing");
2260 stop_cmd_probe_state(&mut cmd_probe);
2261 ready_fail_kill = Some(spawn_ready_fail_kill(
2262 id.clone(),
2263 daemon_pid,
2264 opts.stop_signal.unwrap_or_default(),
2265 ));
2266 break;
2267 }
2268 }
2269 _ = async {
2270 if let Some(ref mut deadline) = port_deadline {
2271 deadline.await;
2272 } else {
2273 std::future::pending::<()>().await;
2274 }
2275 }, if !ready_notified && ready_port.is_some() => {
2276 port_exhausted = true;
2277 port_deadline = None;
2278 port_check_interval = None;
2279 port_probe = None;
2280 warn!("daemon {id}: TCP port readiness check timed out");
2281 let any_remaining = any_ready_check_remaining(
2282 ready_output.as_ref(),
2283 output_exhausted,
2284 ready_port_config.as_ref(),
2285 port_exhausted,
2286 ready_http.as_ref(),
2287 http_exhausted,
2288 ready_cmd.as_ref(),
2289 cmd_exhausted,
2290 );
2291 if !any_remaining {
2292 error!("daemon {id}: all readiness checks exhausted, failing");
2293 stop_cmd_probe_state(&mut cmd_probe);
2294 ready_fail_kill = Some(spawn_ready_fail_kill(
2295 id.clone(),
2296 daemon_pid,
2297 opts.stop_signal.unwrap_or_default(),
2298 ));
2299 break;
2300 }
2301 }
2302 _ = async {
2303 if let Some(ref mut deadline) = cmd_deadline {
2304 deadline.await;
2305 } else {
2306 std::future::pending::<()>().await;
2307 }
2308 }, if !ready_notified && ready_cmd.is_some() => {
2309 cmd_exhausted = true;
2310 cmd_deadline = None;
2311 stop_cmd_probe_state(&mut cmd_probe);
2312 cmd_respawn_delay = None;
2313 warn!("daemon {id}: command readiness check timed out");
2314 let any_remaining = any_ready_check_remaining(
2315 ready_output.as_ref(),
2316 output_exhausted,
2317 ready_port_config.as_ref(),
2318 port_exhausted,
2319 ready_http.as_ref(),
2320 http_exhausted,
2321 ready_cmd.as_ref(),
2322 cmd_exhausted,
2323 );
2324 if !any_remaining {
2325 error!("daemon {id}: all readiness checks exhausted, failing");
2326 ready_fail_kill = Some(spawn_ready_fail_kill(
2327 id.clone(),
2328 daemon_pid,
2329 opts.stop_signal.unwrap_or_default(),
2330 ));
2331 break;
2332 }
2333 }
2334 _ = async {
2335 if let Some(ref mut timer) = delay_timer {
2336 timer.await;
2337 } else {
2338 std::future::pending::<()>().await;
2339 }
2340 } => {
2341 let has_other_ready_check = ready_pattern.is_some()
2342 || ready_http.is_some()
2343 || ready_port.is_some()
2344 || ready_cmd.is_some();
2345 let delay_is_only_readiness = !ready_notified && !has_other_ready_check;
2346 let process_exited = exit_status.is_some();
2347 let process_running = if delay_is_only_readiness && !process_exited {
2348 PROCS.is_live(daemon_pid)
2351 } else {
2352 false
2353 };
2354
2355 if delay_readiness_succeeded(
2356 ready_notified,
2357 has_other_ready_check,
2358 process_exited,
2359 process_running,
2360 ) {
2361 info!("daemon {id} ready: delay elapsed");
2362 ready_notified = true;
2363 if let Some(tx) = ready_tx.take() {
2364 let _ = tx.send(Ok(()));
2365 }
2366 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2367 if !active_port_spawned && has_port_config {
2368 active_port_spawned = true;
2369 detect_and_store_active_port(id.clone(), daemon_pid);
2370 }
2371 } else if delay_is_only_readiness {
2372 if process_exited {
2373 debug!("daemon {id} exited during ready_delay, not marking as ready");
2374 } else {
2375 debug!("daemon {id} pid {daemon_pid} not running during ready_delay, deferring to exit handler");
2376 }
2377 }
2378
2379 if delay_is_only_readiness {
2380 output_deadline = None;
2383 http_deadline = None;
2384 cmd_deadline = None;
2385 port_deadline = None;
2386 stop_cmd_probe_state(&mut cmd_probe);
2387 }
2388 delay_timer = None;
2390 }
2391 _ = async {
2392 if let Some(ref mut interval) = http_check_interval {
2393 interval.tick().await;
2394 } else {
2395 std::future::pending::<()>().await;
2396 }
2397 }, if !ready_notified && ready_http.is_some() && !http_exhausted && http_probe.is_none() => {
2398 if let (Some(http), Some(client)) = (&ready_http, &http_client) {
2399 http_probe = Some(Box::pin(client.get(&http.url).timeout(http_client_timeout).send()));
2400 }
2401 }
2402 result = async {
2403 if let Some(probe) = http_probe.as_mut() {
2404 probe.as_mut().await
2405 } else {
2406 std::future::pending::<std::result::Result<reqwest::Response, reqwest::Error>>().await
2407 }
2408 }, if !ready_notified && http_probe.is_some() => {
2409 http_probe = None;
2410 if let Some(http) = &ready_http {
2411 match result {
2412 Ok(response) if http.accepts_status(response.status().as_u16()) => {
2413 info!("daemon {id} ready: HTTP check passed (status {})", response.status());
2414 ready_notified = true;
2415 if let Some(tx) = ready_tx.take() {
2416 let _ = tx.send(Ok(()));
2417 }
2418 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2419 http_check_interval = None;
2420 http_deadline = None;
2421 stop_cmd_probe_state(&mut cmd_probe);
2422 cmd_deadline = None;
2423 port_deadline = None;
2424 output_deadline = None;
2425 if !active_port_spawned && has_port_config {
2426 active_port_spawned = true;
2427 detect_and_store_active_port(id.clone(), daemon_pid);
2428 }
2429 }
2430 Ok(response) => {
2431 trace!("daemon {id} HTTP check: status {} (not ready)", response.status());
2432 }
2433 Err(e) => {
2434 trace!("daemon {id} HTTP check failed: {e}");
2435 }
2436 }
2437 }
2438 }
2439 _ = async {
2440 if let Some(ref mut interval) = port_check_interval {
2441 interval.tick().await;
2442 } else {
2443 std::future::pending::<()>().await;
2444 }
2445 }, if !ready_notified && ready_port.is_some() && !port_exhausted && port_probe.is_none() => {
2446 if let Some(port) = ready_port {
2447 port_probe = Some(Box::pin(tokio::net::TcpStream::connect(("127.0.0.1", port))));
2448 }
2449 }
2450 result = async {
2451 if let Some(probe) = port_probe.as_mut() {
2452 probe.as_mut().await
2453 } else {
2454 std::future::pending::<std::io::Result<tokio::net::TcpStream>>().await
2455 }
2456 }, if !ready_notified && port_probe.is_some() => {
2457 port_probe = None;
2458 if let Some(port) = ready_port {
2459 match result {
2460 Ok(_) => {
2461 info!("daemon {id} ready: TCP port {port} is listening");
2462 ready_notified = true;
2463 if let Some(tx) = ready_tx.take() {
2464 let _ = tx.send(Ok(()));
2465 }
2466 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2467 port_check_interval = None;
2469 port_deadline = None;
2470 stop_cmd_probe_state(&mut cmd_probe);
2471 http_deadline = None;
2472 cmd_deadline = None;
2473 output_deadline = None;
2474 if !active_port_spawned && has_port_config {
2475 active_port_spawned = true;
2476 if let Some(active_port) = active_port_from_ready_port(
2486 port,
2487 &readiness_resolved_ports,
2488 ) {
2489 let mut state_file =
2490 SUPERVISOR.state_file.lock().await;
2491 if let Some(d) = state_file.daemons.get(&id)
2492 && d.pid == Some(daemon_pid)
2493 {
2494 state_file.set_active_port(&id, active_port);
2495 }
2496 } else {
2497 detect_and_store_active_port(
2498 id.clone(),
2499 daemon_pid,
2500 );
2501 }
2502 }
2503 }
2504 Err(_) => {
2505 trace!("daemon {id} port check: port {port} not listening yet");
2506 }
2507 }
2508 }
2509 }
2510 _ = async {
2511 if let Some(ref mut delay) = cmd_respawn_delay {
2512 delay.await;
2513 } else {
2514 std::future::pending::<()>().await;
2515 }
2516 }, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted && cmd_probe.is_none() => {
2517 if let Some(ref cmd) = ready_cmd {
2518 cmd_probe = Some(spawn_cmd_probe(
2519 &id,
2520 &cmd.run,
2521 daemon_dir.as_path(),
2522 hook_retry_count,
2523 readiness_daemon_env.as_ref(),
2524 &readiness_resolved_ports,
2525 ));
2526 }
2527 cmd_respawn_delay = None;
2528 }
2529 result = async {
2530 if let Some(probe) = cmd_probe.as_mut() {
2531 std::pin::Pin::new(&mut probe.result_rx).await
2532 } else {
2533 std::future::pending::<Result<Result<std::process::ExitStatus, std::io::Error>, tokio::sync::oneshot::error::RecvError>>().await
2534 }
2535 }, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted => {
2536 let _ = cmd_probe.take();
2540 match result {
2541 Ok(Ok(status)) if status.success() => {
2542 info!("daemon {id} ready: readiness command succeeded");
2543 ready_notified = true;
2544 if let Some(tx) = ready_tx.take() {
2545 let _ = tx.send(Ok(()));
2546 }
2547 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2548 cmd_respawn_delay = None;
2549 cmd_deadline = None;
2550 http_deadline = None;
2551 port_deadline = None;
2552 output_deadline = None;
2553 if !active_port_spawned && has_port_config {
2554 active_port_spawned = true;
2555 detect_and_store_active_port(id.clone(), daemon_pid);
2556 }
2557 }
2558 Ok(Ok(_)) | Ok(Err(_)) | Err(_) => {
2559 trace!("daemon {id} cmd check: command not ready, will respawn");
2560 cmd_respawn_delay = Some(Box::pin(time::sleep(ready_check_interval)));
2561 }
2562 }
2563 }
2564 Some(super::OutputLine { text: line, source }) = output_rx.recv() => {
2565 if matches!(source, super::OutputSource::Local) {
2569 let parsed = parse_line(&line);
2570 log_buffer.push(parsed);
2571 if log_buffer.len() >= LOG_BATCH_SIZE {
2572 flush_logs(&mut log_buffer, &mut pending_log_writes);
2573 }
2574 }
2575 trace!("output: {id} {line}");
2576
2577 let line_clean = console::strip_ansi_codes(&line).to_string();
2580
2581 if !ready_notified
2583 && !output_exhausted
2584 && let Some(ref pattern) = ready_pattern
2585 && pattern.is_match(&line_clean)
2586 {
2587 flush_logs(&mut log_buffer, &mut pending_log_writes);
2592 for handle in pending_log_writes.drain(..) {
2593 let _ = handle.await;
2594 }
2595 info!("daemon {id} ready: output matched pattern");
2596 ready_notified = true;
2597 if let Some(tx) = ready_tx.take() {
2598 let _ = tx.send(Ok(()));
2599 }
2600 fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2601 stop_cmd_probe_state(&mut cmd_probe);
2602 http_deadline = None;
2603 cmd_deadline = None;
2604 port_deadline = None;
2605 output_deadline = None;
2606 if !active_port_spawned && has_port_config {
2607 active_port_spawned = true;
2608 detect_and_store_active_port(id.clone(), daemon_pid);
2609 }
2610 }
2611
2612 if let Some(ref hook) = on_output_hook {
2617 let matched = match source {
2618 super::OutputSource::Sink { fires_hook } => fires_hook,
2619 super::OutputSource::Local => match (&hook.filter, &on_output_pattern) {
2620 (Some(substr), _) => line_clean.contains(substr.as_str()),
2621 (None, Some(re)) => re.is_match(&line_clean),
2622 (None, None) => true,
2623 },
2624 };
2625 if matched {
2626 let now = std::time::Instant::now();
2631 let elapsed = on_output_last_fired.map(|t| now.duration_since(t));
2632 if elapsed.is_none_or(|e| e >= on_output_debounce) {
2633 on_output_last_fired = Some(now);
2634 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;
2635 }
2636 }
2637 }
2638 tokio::task::yield_now().await;
2640 }
2641 _ = log_flush_interval.tick() => {
2642 flush_logs(&mut log_buffer, &mut pending_log_writes);
2643 }
2644 }
2645 if ready_notified {
2646 http_probe = None;
2647 port_probe = None;
2648 }
2649 }
2650 drop(http_probe);
2651 drop(port_probe);
2652
2653 let pre_drain_daemon = SUPERVISOR.get_daemon(&id).await;
2667 let pre_drain_is_stopping = pre_drain_daemon
2668 .as_ref()
2669 .is_some_and(|d| d.status.is_stopped() || d.status.is_stopping_or_restarting());
2670
2671 drop(output_relay);
2684 let drain_deadline = tokio::time::Instant::now() + super::EXIT_OUTPUT_DRAIN_TIMEOUT;
2685 loop {
2686 let now = tokio::time::Instant::now();
2687 if now >= drain_deadline {
2688 break;
2689 }
2690 let Ok(Some(line)) =
2691 tokio::time::timeout(drain_deadline - now, output_rx.recv()).await
2692 else {
2693 break;
2694 };
2695 if matches!(line.source, super::OutputSource::Local) {
2697 log_buffer.push(parse_line(&line.text));
2698 }
2699 }
2700 flush_logs(&mut log_buffer, &mut pending_log_writes);
2703 for handle in pending_log_writes {
2704 let _ = handle.await;
2705 }
2706
2707 {
2709 let mut state_file = SUPERVISOR.state_file.lock().await;
2710 state_file.clear_active_port(&id);
2711 }
2712
2713 let readiness_failed = ready_fail_kill.is_some();
2714 let mut termination_error = None;
2715 if let Some(kill) = ready_fail_kill {
2716 let result = kill.await.into_diagnostic().and_then(|result| result);
2717 let failure = match result {
2718 Ok(_) => {
2719 port_claim.take();
2721 ReadyFailure::Exit(Some(124))
2722 }
2723 Err(error) => {
2724 let error = format!(
2725 "failed to terminate daemon {id} after readiness failure: {error}"
2726 );
2727 error!("{error}");
2728 let mut state_file = SUPERVISOR.state_file.lock().await;
2729 if state_file.daemons.get(&id).is_some_and(|daemon| {
2730 daemon.pid == Some(pid)
2731 && !daemon.status.is_stopped()
2732 && !daemon.status.is_stopping_or_restarting()
2733 }) {
2734 state_file.set_status(&id, DaemonStatus::Failed(error.clone()));
2735 }
2736 termination_error = Some(error.clone());
2737 ReadyFailure::Termination(error)
2738 }
2739 };
2740 if let Some(tx) = ready_tx.take() {
2741 let _ = tx.send(Err(failure));
2742 }
2743 }
2744
2745 if termination_error.is_some() {
2749 while PROCS.process_group_alive(daemon_pid) {
2750 time::sleep(Duration::from_millis(100)).await;
2752 }
2753 }
2754
2755 let exit_status = if let Some(status) = exit_status {
2757 status
2758 } else {
2759 match exit_rx.recv().await {
2761 Some(status) => status,
2762 None => {
2763 warn!("daemon {id} exit channel closed without receiving status");
2764 Err(std::io::Error::other("exit channel closed"))
2765 }
2766 }
2767 };
2768
2769 let current_daemon = SUPERVISOR.get_daemon(&id).await;
2770
2771 SUPERVISOR
2776 .active_monitors
2777 .fetch_add(1, atomic::Ordering::Release);
2778 struct MonitorGuard;
2779 impl Drop for MonitorGuard {
2780 fn drop(&mut self) {
2781 SUPERVISOR
2782 .active_monitors
2783 .fetch_sub(1, atomic::Ordering::Release);
2784 SUPERVISOR.monitor_done.notify_waiters();
2785 }
2786 }
2787 let _monitor_guard = MonitorGuard;
2788 if !pre_drain_is_stopping
2793 && (current_daemon.is_none()
2794 || current_daemon.as_ref().is_some_and(|d| {
2795 d.pid != Some(pid)
2796 && !d.status.is_stopped()
2797 && !d.status.is_stopping_or_restarting()
2798 }))
2799 {
2800 if oneshot_completion_pending && let Some(tx) = ready_tx.take() {
2804 let _ = tx.send(Ok(()));
2805 }
2806 return;
2807 }
2808 let already_stopped = current_daemon
2813 .as_ref()
2814 .is_some_and(|d| d.status.is_stopped());
2815 let is_stopping = already_stopped
2816 || pre_drain_is_stopping
2817 || current_daemon
2818 .as_ref()
2819 .is_some_and(|d| d.status.is_stopping_or_restarting());
2820
2821 let (exit_code, exit_reason) = match (&exit_status, is_stopping) {
2823 (Ok(status), true) => {
2824 (status.code().unwrap_or(-1), "stop")
2828 }
2829 (_, false) if readiness_failed => (124, "fail"),
2830 (Ok(status), false) if status.success() => (status.code().unwrap_or(-1), "exit"),
2831 (Ok(status), false) => (status.code().unwrap_or(-1), "fail"),
2832 (Err(_), true) => {
2833 (-1, "stop")
2835 }
2836 (Err(_), false) => (-1, "fail"),
2837 };
2838 if !already_stopped && !pre_drain_is_stopping {
2850 if let Ok(status) = &exit_status {
2851 info!("daemon {id} exited with status {status}");
2852 }
2853 let (mut new_status, last_exit_success) = terminal_exit_state(
2854 exit_reason,
2855 opts.oneshot,
2856 exit_code,
2857 exit_status.as_ref().map(|s| s.success()).unwrap_or(true),
2858 );
2859 if !is_stopping && let Some(error) = &termination_error {
2860 new_status = DaemonStatus::Failed(error.clone());
2861 }
2862 if !SUPERVISOR
2868 .finalize_monitored_exit(
2869 &id,
2870 pid,
2871 monitor_token,
2872 new_status,
2873 Some(last_exit_success),
2874 )
2875 .await
2876 {
2877 debug!("daemon {id} exit state was not written; a successor owns the record");
2878 }
2879 }
2880
2881 if oneshot_completion_pending && let Some(tx) = ready_tx.take() {
2886 if exit_reason == "exit" {
2887 let _ = tx.send(Ok(()));
2888 } else {
2889 warn!("daemon {id}: oneshot was stopped before completing");
2890 let _ = tx.send(Err(ReadyFailure::Exit(None)));
2891 }
2892 }
2893
2894 let hook_extra_env = vec![
2896 ("PITCHFORK_EXIT_CODE".to_string(), exit_code.to_string()),
2897 ("PITCHFORK_EXIT_REASON".to_string(), exit_reason.to_string()),
2898 ];
2899
2900 let hooks_to_fire: Vec<HookType> = match exit_reason {
2902 "stop" => vec![HookType::OnStop, HookType::OnExit],
2903 "exit" => vec![HookType::OnExit],
2904 _ if termination_error.is_some() || hook_retry_count >= hook_retry.count() => {
2906 vec![HookType::OnFail, HookType::OnExit]
2907 }
2908 _ => vec![],
2909 };
2910
2911 for hook_type in hooks_to_fire {
2912 fire_hook(
2913 hook_type,
2914 id.clone(),
2915 hook_dirs.clone(),
2916 hook_retry_count,
2917 hook_daemon_env.clone(),
2918 hook_resolved_ports.clone(),
2919 hook_extra_env.clone(),
2920 )
2921 .await;
2922 }
2923 });
2924
2925 if let Some(ready_rx) = ready_rx {
2926 let wait_ready = opts.wait_ready;
2927 let oneshot = opts.oneshot;
2928 let last_attempt = opts.retry_count >= opts.retry.count();
2929 let started = IpcResponse::DaemonStart {
2930 daemon: daemon.clone(),
2931 };
2932 let ready = async move {
2933 let id = daemon.id.clone();
2934 let ready = ready_rx.await;
2935 SUPERVISOR.end_ready_check(&id, &attempt_rx);
2936 match ready {
2937 Ok(Ok(())) => {
2938 info!("daemon {id} is ready");
2939 let daemon = match SUPERVISOR.get_daemon(&id).await {
2949 Some(current) if current.pid.is_none() || current.pid == Some(pid) => {
2950 current
2951 }
2952 _ if oneshot => crate::daemon::Daemon {
2959 status: DaemonStatus::Completed,
2960 pid: None,
2961 start_time: None,
2962 boot_time: None,
2963 last_exit_success: Some(true),
2964 ..daemon
2965 },
2966 _ => daemon,
2967 };
2968 IpcResponse::DaemonReady { daemon }
2969 }
2970 Ok(Err(ReadyFailure::Exit(exit_code))) => {
2971 error!("daemon {id} failed before becoming ready");
2972 if using_sink && last_attempt {
2983 super::log_sink::wait_for_output(&id, spawn_time, SINK_OUTPUT_TIMEOUT)
2984 .await;
2985 }
2986 IpcResponse::DaemonFailedWithCode {
2987 exit_code,
2988 resolved_ports: attempt_resolved_ports,
2989 }
2990 }
2991 Ok(Err(ReadyFailure::Termination(error))) => {
2992 IpcResponse::DaemonFailed { error }
2993 }
2994 Err(_) => {
2995 error!("readiness channel closed unexpectedly for daemon {id}");
2996 IpcResponse::DaemonStart { daemon }
2997 }
2998 }
2999 };
3000 let completion = tokio::spawn(async move {
3001 let response = ready.await;
3002 attempt_tx.send_replace(Some(response.clone()));
3003 response
3004 });
3005 if wait_ready {
3006 completion.await.into_diagnostic()
3007 } else {
3008 Ok(started)
3009 }
3010 } else {
3011 Ok(IpcResponse::DaemonStart { daemon })
3012 }
3013 }
3014
3015 pub async fn stop(&self, id: &DaemonId) -> Result<IpcResponse> {
3017 let lock = self.stop_lock(id).await;
3021 let _guard = lock.lock().await;
3022 self.stop_locked(id).await
3023 }
3024
3025 pub(crate) async fn stop_for_restart(&self, id: &DaemonId) -> Result<IpcResponse> {
3032 let lock = self.stop_lock(id).await;
3033 let _guard = lock.lock().await;
3034 self.stop_locked_with(id, true).await
3035 }
3036
3037 pub(super) async fn stop_locked(&self, id: &DaemonId) -> Result<IpcResponse> {
3039 self.stop_locked_with(id, false).await
3040 }
3041
3042 pub(super) async fn stop_locked_with(
3049 &self,
3050 id: &DaemonId,
3051 restarting: bool,
3052 ) -> Result<IpcResponse> {
3053 let (stopping_status, stopped_status) = if restarting {
3054 (DaemonStatus::Restarting, DaemonStatus::Restarting)
3055 } else {
3056 (DaemonStatus::Stopping, DaemonStatus::Stopped)
3057 };
3058 let pitchfork_id = DaemonId::pitchfork();
3059 if *id == pitchfork_id {
3060 return Ok(IpcResponse::Error(
3061 "Cannot stop supervisor via stop command".into(),
3062 ));
3063 }
3064 info!("stopping daemon: {id}");
3065 self.cancel_retrying(id);
3070 let _stop_epoch_bump = StopEpochGuard(id.clone());
3078 if let Some(daemon) = self.get_daemon(id).await {
3079 trace!("daemon to stop: {daemon}");
3080 if let Some(pid) = daemon.pid {
3081 trace!("killing pid: {pid}");
3082 if PROCS.is_running(pid) {
3083 if !super::signalling_pid_is_authorized(
3089 daemon.start_time,
3090 PROCS.start_time(pid),
3091 ) {
3092 warn!(
3093 "pid {pid} recorded for daemon {id} belongs to another process now; not signalling it"
3094 );
3095 self.upsert_daemon(
3096 UpsertDaemonOpts::builder(id.clone())
3097 .set(|o| {
3098 o.pid = None;
3099 o.status = stopped_status.clone();
3100 })
3101 .build(),
3102 )
3103 .await?;
3104 return Ok(IpcResponse::DaemonWasNotRunning);
3105 }
3106
3107 self.upsert_daemon(
3109 UpsertDaemonOpts::builder(id.clone())
3110 .set(|o| {
3111 o.pid = Some(pid);
3112 o.status = stopping_status.clone();
3113 })
3114 .build(),
3115 )
3116 .await?;
3117
3118 let stop_cfg = daemon.stop_signal.unwrap_or_default();
3121 let stop_signal: i32 = stop_cfg.signal.into();
3122 if let Err(e) = PROCS
3123 .kill_process_group_async(pid, stop_signal, stop_cfg.timeout)
3124 .await
3125 {
3126 debug!("failed to kill pid {pid}: {e}");
3127 if PROCS.process_group_alive(pid) {
3133 debug!(
3135 "failed to stop pid {pid}: process group still alive after kill"
3136 );
3137 self.upsert_daemon(
3138 UpsertDaemonOpts::builder(id.clone())
3139 .set(|o| {
3140 o.pid = Some(pid); o.status = DaemonStatus::Running;
3142 })
3143 .build(),
3144 )
3145 .await?;
3146 return Ok(IpcResponse::DaemonStopFailed {
3147 error: format!(
3148 "process group of {pid} still alive after kill attempt: {e}"
3149 ),
3150 });
3151 }
3152 #[cfg(windows)]
3157 {
3158 self.upsert_daemon(
3159 UpsertDaemonOpts::builder(id.clone())
3160 .set(|o| {
3161 o.pid = None;
3162 o.status = stopped_status.clone();
3163 o.last_exit_success = Some(true);
3164 })
3165 .build(),
3166 )
3167 .await?;
3168 return Ok(IpcResponse::DaemonStopFailed {
3169 error: format!("{e}"),
3170 });
3171 }
3172 }
3173
3174 self.upsert_daemon(
3182 UpsertDaemonOpts::builder(id.clone())
3183 .set(|o| {
3184 o.pid = None;
3185 o.status = stopped_status.clone();
3186 o.last_exit_success = Some(true);
3187 })
3188 .build(),
3189 )
3190 .await?;
3191 } else if daemon.oneshot && self.is_monitored(id, pid) {
3192 debug!(
3212 "pid {pid} not running but daemon {id} is still monitored; waiting for its monitor to settle the outcome"
3213 );
3214 self.wait_for_exit_finalized(id, Some(pid)).await;
3215 let finished = self.get_daemon(id).await;
3216 if finished
3217 .as_ref()
3218 .is_some_and(|d| stop_keeps_finalized_status(&d.status))
3219 {
3220 return Ok(IpcResponse::DaemonWasNotRunning);
3221 }
3222 self.upsert_daemon(
3226 UpsertDaemonOpts::builder(id.clone())
3227 .set(|o| {
3228 o.pid = None;
3229 o.status = stopped_status.clone();
3230 })
3231 .build(),
3232 )
3233 .await?;
3234 return Ok(IpcResponse::DaemonWasNotRunning);
3235 } else {
3236 debug!("pid {pid} not running, process may have exited unexpectedly");
3237 self.upsert_daemon(
3244 UpsertDaemonOpts::builder(id.clone())
3245 .set(|o| {
3246 o.pid = None;
3247 o.status = stopped_status.clone();
3248 })
3249 .build(),
3250 )
3251 .await?;
3252 return Ok(IpcResponse::DaemonWasNotRunning);
3253 }
3254 Ok(IpcResponse::Ok)
3255 } else {
3256 debug!("daemon {id} not running");
3257 if !restarting && daemon.status.is_restarting() {
3262 self.upsert_daemon(
3263 UpsertDaemonOpts::builder(id.clone())
3264 .set(|o| {
3265 o.pid = None;
3266 o.status = DaemonStatus::Stopped;
3267 })
3268 .build(),
3269 )
3270 .await?;
3271 return Ok(IpcResponse::Ok);
3272 }
3273 if daemon.status.is_errored() && daemon.retry_count < daemon.retry.count() {
3278 self.upsert_daemon(
3279 UpsertDaemonOpts::builder(id.clone())
3280 .set(|o| {
3281 o.pid = None;
3282 o.status = stopped_status.clone();
3283 })
3284 .build(),
3285 )
3286 .await?;
3287 return Ok(IpcResponse::DaemonWasNotRunning);
3288 }
3289 Ok(IpcResponse::DaemonNotRunning)
3290 }
3291 } else {
3292 debug!("daemon {id} not found");
3293 Ok(IpcResponse::DaemonNotFound)
3294 }
3295 }
3296}
3297
3298#[cfg(unix)]
3299fn resolve_effective_run_identity(daemon_user: Option<&str>) -> Result<RunIdentity> {
3300 let s = settings();
3301 let settings_user = s.supervisor.user.trim();
3302 let daemon_user = daemon_user.map(str::trim).filter(|user| !user.is_empty());
3303 let settings_user = (!settings_user.is_empty()).then_some(settings_user);
3304 let configured = daemon_user.or(settings_user);
3305 let current_uid = nix::unistd::Uid::effective().as_raw();
3306 let current_gid = nix::unistd::Gid::effective().as_raw();
3307 let invoking = env::invoking_user_ids().map(|(uid, gid)| (uid.to_string(), gid.to_string()));
3310 resolve_run_identity(
3311 configured,
3312 current_uid,
3313 current_gid,
3314 invoking.as_ref().map(|(uid, _)| uid.as_str()),
3315 invoking.as_ref().map(|(_, gid)| gid.as_str()),
3316 )
3317}
3318
3319#[cfg(unix)]
3320fn resolve_run_identity(
3321 configured: Option<&str>,
3322 current_uid: u32,
3323 current_gid: u32,
3324 sudo_uid: Option<&str>,
3325 sudo_gid: Option<&str>,
3326) -> Result<RunIdentity> {
3327 let current_uid = nix::unistd::Uid::from_raw(current_uid);
3328 let current_gid = nix::unistd::Gid::from_raw(current_gid);
3329 if let Some(user) = configured {
3330 let identity = resolve_configured_user(user)?;
3331 ensure_can_use_identity(user, &identity, current_uid, current_gid)?;
3332 if identity.matches(current_uid, current_gid) {
3333 return Ok(RunIdentity::Inherit);
3334 }
3335 return Ok(identity);
3336 }
3337
3338 if current_uid.is_root()
3339 && let Some(identity) = resolve_sudo_identity(sudo_uid, sudo_gid)
3340 {
3341 if identity.matches(current_uid, current_gid) {
3342 return Ok(RunIdentity::Inherit);
3343 }
3344 return Ok(identity);
3345 }
3346
3347 Ok(RunIdentity::Inherit)
3348}
3349
3350#[cfg(unix)]
3351fn resolve_configured_user(user: &str) -> Result<RunIdentity> {
3352 if user.chars().all(|c| c.is_ascii_digit()) {
3353 let uid = user
3354 .parse::<u32>()
3355 .map_err(|e| miette::miette!("invalid run user UID '{}': {}", user, e))?;
3356 let user_record = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
3357 .into_diagnostic()?
3358 .ok_or_else(|| miette::miette!("run user UID '{}' does not exist", user))?;
3359 return run_identity_from_user_record(user_record);
3360 }
3361
3362 let user_record = nix::unistd::User::from_name(user)
3363 .into_diagnostic()?
3364 .ok_or_else(|| miette::miette!("run user '{}' does not exist", user))?;
3365 run_identity_from_user_record(user_record)
3366}
3367
3368#[cfg(unix)]
3369fn run_identity_from_user_record(user: nix::unistd::User) -> Result<RunIdentity> {
3370 let username = CString::new(user.name)
3371 .map_err(|e| miette::miette!("run user name contains an interior nul byte: {}", e))?;
3372 Ok(RunIdentity::Switch {
3373 uid: user.uid,
3374 gid: user.gid,
3375 username: Some(username),
3376 home: Some(user.dir),
3377 })
3378}
3379
3380#[cfg(unix)]
3381fn resolve_sudo_identity(sudo_uid: Option<&str>, sudo_gid: Option<&str>) -> Option<RunIdentity> {
3382 let uid = sudo_uid?.parse::<u32>().ok()?;
3383 let gid = sudo_gid?.parse::<u32>().ok()?;
3384 let user = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
3385 .ok()
3386 .flatten();
3387 let (username, home) = match user {
3388 Some(user) => (CString::new(user.name).ok(), Some(user.dir)),
3389 None => (None, None),
3390 };
3391 Some(RunIdentity::Switch {
3392 uid: nix::unistd::Uid::from_raw(uid),
3393 gid: nix::unistd::Gid::from_raw(gid),
3394 username,
3395 home,
3396 })
3397}
3398
3399#[cfg(unix)]
3400fn ensure_can_use_identity(
3401 configured_user: &str,
3402 identity: &RunIdentity,
3403 current_uid: nix::unistd::Uid,
3404 current_gid: nix::unistd::Gid,
3405) -> Result<()> {
3406 let RunIdentity::Switch { uid, gid, .. } = identity else {
3407 return Ok(());
3408 };
3409 if *uid == current_uid && *gid == current_gid {
3410 return Ok(());
3411 }
3412 if current_uid.is_root() {
3413 return Ok(());
3414 }
3415 Err(miette::miette!(
3416 "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.",
3417 configured_user,
3418 current_uid.as_raw(),
3419 current_gid.as_raw(),
3420 uid.as_raw(),
3421 gid.as_raw()
3422 ))
3423}
3424
3425#[cfg(unix)]
3432fn apply_identity_env(command: &mut tokio::process::Command, identity: &RunIdentity) {
3433 let RunIdentity::Switch { username, home, .. } = identity else {
3434 return;
3435 };
3436 match home.as_ref().filter(|home| !home.as_os_str().is_empty()) {
3437 Some(home) => command.env("HOME", home),
3438 None => command.env_remove("HOME"),
3439 };
3440 match username.as_ref().and_then(|name| name.to_str().ok()) {
3441 Some(name) => command.env("USER", name).env("LOGNAME", name),
3442 None => command.env_remove("USER").env_remove("LOGNAME"),
3443 };
3444}
3445
3446#[cfg(unix)]
3447fn apply_run_identity(identity: &RunIdentity) -> std::io::Result<()> {
3448 let RunIdentity::Switch {
3449 uid, gid, username, ..
3450 } = identity
3451 else {
3452 return Ok(());
3453 };
3454 if let Some(username) = username {
3455 initgroups_for_user(username, *gid)?;
3456 } else {
3457 setgroups_to_primary(*gid)?;
3458 }
3459 nix::unistd::setgid(*gid).map_err(nix_to_io_error)?;
3460 nix::unistd::setuid(*uid).map_err(nix_to_io_error)?;
3461 Ok(())
3462}
3463
3464#[cfg(unix)]
3465impl RunIdentity {
3466 fn matches(&self, uid: nix::unistd::Uid, gid: nix::unistd::Gid) -> bool {
3467 matches!(self, RunIdentity::Switch { uid: u, gid: g, .. } if *u == uid && *g == gid)
3468 }
3469}
3470
3471#[cfg(unix)]
3472fn setgroups_to_primary(gid: nix::unistd::Gid) -> std::io::Result<()> {
3473 let groups = [gid.as_raw() as libc::gid_t];
3474 #[cfg(any(target_os = "linux", target_os = "android"))]
3475 let group_count = groups.len();
3476 #[cfg(not(any(target_os = "linux", target_os = "android")))]
3477 let group_count = groups.len() as libc::c_int;
3478 let rc = unsafe { libc::setgroups(group_count, groups.as_ptr()) };
3479 if rc == -1 {
3480 Err(std::io::Error::last_os_error())
3481 } else {
3482 Ok(())
3483 }
3484}
3485
3486#[cfg(unix)]
3487fn initgroups_for_user(username: &CString, gid: nix::unistd::Gid) -> std::io::Result<()> {
3488 let gid = gid.as_raw();
3489 #[cfg(any(
3490 target_os = "macos",
3491 target_os = "ios",
3492 target_os = "tvos",
3493 target_os = "watchos"
3494 ))]
3495 let base_gid = i32::try_from(gid)
3496 .map_err(|_| std::io::Error::other(format!("gid {gid} is out of range")))?;
3497
3498 #[cfg(not(any(
3499 target_os = "macos",
3500 target_os = "ios",
3501 target_os = "tvos",
3502 target_os = "watchos"
3503 )))]
3504 let base_gid = gid as libc::gid_t;
3505
3506 let rc = unsafe { libc::initgroups(username.as_ptr(), base_gid) };
3509 if rc == -1 {
3510 Err(std::io::Error::last_os_error())
3511 } else {
3512 Ok(())
3513 }
3514}
3515
3516#[cfg(unix)]
3517fn nix_to_io_error(err: nix::errno::Errno) -> std::io::Error {
3518 std::io::Error::from_raw_os_error(err as i32)
3519}
3520
3521static PORT_CLAIMS: Lazy<std::sync::Mutex<HashMap<u16, (DaemonId, u64)>>> =
3529 Lazy::new(|| std::sync::Mutex::new(HashMap::new()));
3530
3531static PORT_RESOLUTION: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
3533
3534static PORT_CLAIM_GENERATION: atomic::AtomicU64 = atomic::AtomicU64::new(0);
3536
3537#[derive(Debug)]
3539struct PortClaim {
3540 generation: u64,
3541 ports: Vec<u16>,
3542}
3543
3544impl Drop for PortClaim {
3545 fn drop(&mut self) {
3546 let mut claims = PORT_CLAIMS.lock().unwrap_or_else(|e| e.into_inner());
3547 for port in &self.ports {
3548 if claims.get(port).is_some_and(|(_, g)| *g == self.generation) {
3550 claims.remove(port);
3551 }
3552 }
3553 }
3554}
3555
3556async fn claim_ports(
3563 id: &DaemonId,
3564 expected_ports: &[u16],
3565 auto_bump: bool,
3566 max_attempts: u32,
3567) -> Result<(Vec<u16>, PortClaim)> {
3568 let _resolution = PORT_RESOLUTION.lock().await;
3569 let claimed: HashMap<u16, DaemonId> = PORT_CLAIMS
3570 .lock()
3571 .unwrap_or_else(|e| e.into_inner())
3572 .iter()
3573 .filter(|(_, (owner, _))| owner != id)
3574 .map(|(port, (owner, _))| (*port, owner.clone()))
3575 .collect();
3576 let resolved = check_ports_available(expected_ports, auto_bump, max_attempts, &claimed).await?;
3577 let ports: Vec<u16> = resolved.iter().copied().filter(|&p| p != 0).collect();
3578 let generation = PORT_CLAIM_GENERATION.fetch_add(1, atomic::Ordering::Relaxed);
3579 {
3580 let mut claims = PORT_CLAIMS.lock().unwrap_or_else(|e| e.into_inner());
3581 for port in &ports {
3582 claims.insert(*port, (id.clone(), generation));
3583 }
3584 }
3585 Ok((resolved, PortClaim { generation, ports }))
3586}
3587
3588async fn check_ports_available(
3589 expected_ports: &[u16],
3590 auto_bump: bool,
3591 max_attempts: u32,
3592 claimed: &HashMap<u16, DaemonId>,
3593) -> Result<Vec<u16>> {
3594 if expected_ports.is_empty() {
3595 return Ok(Vec::new());
3596 }
3597
3598 for bump_offset in 0..=max_attempts {
3599 let candidate_ports: Vec<u16> = expected_ports
3601 .iter()
3602 .map(|&p| p.wrapping_add(bump_offset as u16))
3603 .collect();
3604
3605 let mut all_available = true;
3607 let mut conflicting_port = None;
3608 let mut conflicting_claim = None;
3609
3610 for &port in &candidate_ports {
3611 if port == 0 {
3614 continue;
3615 }
3616
3617 if let Some(owner) = claimed.get(&port) {
3631 all_available = false;
3632 conflicting_claim = Some((port, owner.clone()));
3633 break;
3634 }
3635 if let Some(address) = port_bind_conflict(port).await {
3636 all_available = false;
3637 conflicting_port = Some((port, address));
3638 break;
3639 }
3640 }
3641
3642 if all_available {
3643 if candidate_ports.contains(&0) && !expected_ports.contains(&0) {
3647 return Err(PortError::NoAvailablePort {
3648 start_port: expected_ports[0],
3649 attempts: bump_offset + 1,
3650 }
3651 .into());
3652 }
3653 if bump_offset > 0 {
3654 info!("ports {expected_ports:?} bumped by {bump_offset} to {candidate_ports:?}");
3655 }
3656 return Ok(candidate_ports);
3657 }
3658
3659 if bump_offset == 0
3661 && !auto_bump
3662 && let Some((port, daemon)) = conflicting_claim
3663 {
3664 return Err(PortError::Claimed {
3665 port,
3666 daemon: daemon.to_string(),
3667 }
3668 .into());
3669 }
3670 if bump_offset == 0
3671 && !auto_bump
3672 && let Some((port, address)) = conflicting_port
3673 {
3674 let (pid, process) = identify_port_owner(port, address).await;
3675 return Err(PortError::InUse {
3676 port,
3677 address: Some(shown_address(address)),
3678 process,
3679 pid,
3680 }
3681 .into());
3682 }
3683 }
3684
3685 Err(PortError::NoAvailablePort {
3687 start_port: expected_ports[0],
3688 attempts: max_attempts + 1,
3689 }
3690 .into())
3691}
3692
3693async fn port_bind_conflict(port: u16) -> Option<std::net::IpAddr> {
3699 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
3700 tokio::task::spawn_blocking(move || {
3701 for addr in [
3702 IpAddr::V4(Ipv4Addr::UNSPECIFIED),
3703 IpAddr::V4(Ipv4Addr::LOCALHOST),
3704 IpAddr::V6(Ipv6Addr::LOCALHOST),
3705 ] {
3706 match bind_probe((addr, port).into()) {
3707 Ok(socket) => drop(socket),
3708 Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => return Some(addr),
3709 Err(_) => continue,
3710 }
3711 }
3712 None
3713 })
3714 .await
3715 .unwrap_or(None)
3716}
3717
3718#[cfg(unix)]
3729fn bind_probe(addr: std::net::SocketAddr) -> std::io::Result<tokio::net::TcpSocket> {
3730 let socket = if addr.is_ipv4() {
3731 tokio::net::TcpSocket::new_v4()?
3732 } else {
3733 tokio::net::TcpSocket::new_v6()?
3734 };
3735 socket.set_reuseaddr(true)?;
3736 socket.bind(addr)?;
3737 Ok(socket)
3738}
3739
3740#[cfg(not(unix))]
3746fn bind_probe(addr: std::net::SocketAddr) -> std::io::Result<std::net::TcpListener> {
3747 std::net::TcpListener::bind(addr)
3748}
3749
3750fn shown_address(addr: std::net::IpAddr) -> String {
3752 match addr {
3753 std::net::IpAddr::V4(v4) => v4.to_string(),
3754 std::net::IpAddr::V6(v6) => format!("[{v6}]"),
3755 }
3756}
3757
3758fn listener_match(listening: std::net::IpAddr, conflict: std::net::IpAddr) -> Option<u8> {
3765 use std::net::IpAddr;
3766 let listening = listening.to_canonical();
3767 if listening == conflict {
3768 return Some(0);
3769 }
3770 match (listening, conflict) {
3771 (IpAddr::V4(_), IpAddr::V4(_)) | (IpAddr::V6(_), IpAddr::V6(_))
3772 if listening.is_unspecified() || conflict.is_unspecified() =>
3773 {
3774 Some(1)
3775 }
3776 (IpAddr::V6(v6), IpAddr::V4(_)) if v6.is_unspecified() => Some(2),
3777 _ => None,
3778 }
3779}
3780
3781struct TcpSocket {
3783 addr: std::net::SocketAddr,
3784 listening: bool,
3785 pid: u32,
3786 process: String,
3787}
3788
3789fn pick_port_owner(
3799 sockets: impl IntoIterator<Item = TcpSocket>,
3800 port: u16,
3801 conflict: std::net::IpAddr,
3802) -> Option<(u32, String)> {
3803 sockets
3804 .into_iter()
3805 .filter(|s| s.addr.port() == port)
3806 .filter_map(|s| {
3807 let matched = listener_match(s.addr.ip(), conflict)?;
3808 let rank = (matched == 2, !s.listening, matched);
3809 Some((rank, s.pid, s.process))
3810 })
3811 .min_by_key(|(rank, _, _)| *rank)
3812 .map(|(_, pid, process)| (pid, process))
3813}
3814
3815async fn identify_port_owner(port: u16, conflict: std::net::IpAddr) -> (u32, String) {
3825 tokio::task::spawn_blocking(move || {
3826 listeners::get_all()
3827 .ok()
3828 .and_then(|list| {
3829 let tcp = list
3832 .into_iter()
3833 .filter(|l| l.protocol == listeners::Protocol::TCP)
3834 .map(|l| TcpSocket {
3835 addr: l.socket,
3836 listening: l.state == listeners::SocketState::Listen,
3837 pid: l.process.pid,
3838 process: l.process.name,
3839 });
3840 pick_port_owner(tcp, port, conflict)
3841 })
3842 .unwrap_or((0, "unknown".to_string()))
3843 })
3844 .await
3845 .unwrap_or((0, "unknown".to_string()))
3846}
3847
3848async fn detect_port_conflict(port: u16) -> Option<(String, u32, String)> {
3853 let address = port_bind_conflict(port).await?;
3854 let (pid, process) = identify_port_owner(port, address).await;
3855 Some((shown_address(address), pid, process))
3856}
3857
3858#[derive(Debug, PartialEq, Eq)]
3859enum ActivePortSelection {
3860 NoCandidates,
3861 Selected(u16),
3862 Ambiguous(Vec<u16>),
3863}
3864
3865fn discovery_preferred_port(daemon: &crate::daemon::Daemon) -> Option<u16> {
3866 daemon
3867 .resolved_port
3868 .first()
3869 .copied()
3870 .or_else(|| {
3871 daemon
3872 .port
3873 .as_ref()
3874 .and_then(|port| port.expect.first().copied())
3875 })
3876 .filter(|&port| port > 0)
3877}
3878
3879fn select_active_port(
3880 listeners: impl IntoIterator<Item = listeners::Listener>,
3881 descendant_pids: &std::collections::HashSet<u32>,
3882 preferred_port: Option<u16>,
3883) -> ActivePortSelection {
3884 let process_ports: std::collections::BTreeSet<u16> = listeners
3885 .into_iter()
3886 .filter(|listener| {
3887 listener.protocol == listeners::Protocol::TCP
3888 && listener.state == listeners::SocketState::Listen
3889 && descendant_pids.contains(&listener.process.pid)
3890 })
3891 .map(|listener| listener.socket.port())
3892 .filter(|&port| port > 0)
3893 .collect();
3894
3895 if let Some(port) = preferred_port
3896 && process_ports.contains(&port)
3897 {
3898 return ActivePortSelection::Selected(port);
3899 }
3900
3901 match process_ports.len() {
3902 0 => ActivePortSelection::NoCandidates,
3903 1 => ActivePortSelection::Selected(*process_ports.first().unwrap()),
3904 _ => ActivePortSelection::Ambiguous(process_ports.into_iter().collect()),
3905 }
3906}
3907
3908fn detect_and_store_active_port(id: DaemonId, pid: u32) {
3919 tokio::spawn(async move {
3920 for delay_ms in [500u64, 1000, 2000, 4000] {
3924 tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
3925
3926 let preferred_port: Option<u16> = {
3929 let state_file = SUPERVISOR.state_file.lock().await;
3930 match state_file.daemons.get(&id) {
3931 Some(d) if d.pid.is_none() => {
3932 debug!("daemon {id}: aborting active_port detection — process exited");
3933 return;
3934 }
3935 Some(d) => discovery_preferred_port(d),
3936 None => None,
3937 }
3938 };
3939
3940 let selection = tokio::task::spawn_blocking(move || {
3941 let listeners = listeners::get_all().ok()?;
3942
3943 PROCS.refresh_processes();
3945
3946 let descendant_pids: std::collections::HashSet<u32> = PROCS
3947 .all_children(pid)
3948 .into_iter()
3949 .chain(std::iter::once(pid))
3950 .collect();
3951
3952 Some(select_active_port(
3953 listeners,
3954 &descendant_pids,
3955 preferred_port,
3956 ))
3957 })
3958 .await
3959 .ok()
3960 .flatten()
3961 .unwrap_or(ActivePortSelection::NoCandidates);
3962
3963 let port = match selection {
3964 ActivePortSelection::Selected(port) => port,
3965 ActivePortSelection::Ambiguous(ports) => {
3966 debug!(
3967 "daemon {id}: ambiguous active_port candidates {ports:?} for pid {pid} \
3968 and its descendants; leaving active_port unset (will retry)"
3969 );
3970 continue;
3971 }
3972 ActivePortSelection::NoCandidates => {
3973 debug!(
3974 "daemon {id}: no active port detected for pid {pid} or its descendants \
3975 (will retry)"
3976 );
3977 continue;
3978 }
3979 };
3980
3981 debug!("daemon {id} active_port detected: {port}");
3982 let mut state_file = SUPERVISOR.state_file.lock().await;
3983 if let Some(d) = state_file.daemons.get(&id) {
3984 if d.pid == Some(pid) {
3988 state_file.set_active_port(&id, port);
3989 } else {
3990 debug!(
3991 "daemon {id}: skipping active_port write — PID mismatch \
3992 (expected {pid}, current {:?})",
3993 d.pid
3994 );
3995 }
3996 }
3997 return;
3998 }
3999
4000 debug!(
4001 "daemon {id}: active port detection exhausted all retries for pid {pid} and its descendants"
4002 );
4003 });
4004}
4005
4006#[cfg(test)]
4007mod port_conflict_tests {
4008 use super::{
4009 TcpSocket, check_ports_available, claim_ports, listener_match, pick_port_owner,
4010 port_bind_conflict, shown_address,
4011 };
4012 use crate::error::PortError;
4013 use std::net::{IpAddr, SocketAddr};
4014
4015 static FORKS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
4018
4019 #[tokio::test]
4020 async fn a_taken_port_is_reported_with_its_address_and_holder() {
4021 let _forks = FORKS.lock().await;
4022 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4023 let port = listener.local_addr().unwrap().port();
4024
4025 let address = shown_address(port_bind_conflict(port).await.unwrap());
4028 assert!(
4029 ["0.0.0.0", "127.0.0.1"].contains(&address.as_str()),
4030 "{address}"
4031 );
4032
4033 let err = check_ports_available(&[port], false, 0, &Default::default())
4034 .await
4035 .unwrap_err();
4036 match err.downcast_ref::<PortError>() {
4037 Some(PortError::InUse {
4038 port: p,
4039 address: Some(a),
4040 pid,
4041 ..
4042 }) => {
4043 assert_eq!(*p, port);
4044 assert_eq!(*a, address);
4045 assert_eq!(*pid, std::process::id());
4047 }
4048 other => panic!("unexpected error: {other:?}"),
4049 }
4050 drop(listener);
4051 assert_eq!(port_bind_conflict(port).await, None);
4052 }
4053
4054 #[tokio::test]
4055 async fn a_starting_daemons_ports_are_not_resolved_for_another() {
4056 use crate::daemon_id::DaemonId;
4057 let _forks = FORKS.lock().await;
4058 let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4059 let port = probe.local_addr().unwrap().port();
4060 drop(probe);
4061 let one = DaemonId::new("claim-one", "web");
4062 let two = DaemonId::new("claim-two", "web");
4063
4064 let (resolved, claim) = claim_ports(&one, &[port], false, 0).await.unwrap();
4065 assert_eq!(resolved, vec![port]);
4066
4067 let err = claim_ports(&two, &[port], false, 0).await.unwrap_err();
4070 assert!(
4071 matches!(err.downcast_ref::<PortError>(), Some(PortError::Claimed { port: p, .. }) if *p == port),
4072 "{err:?}"
4073 );
4074 let (bumped, bumped_claim) = claim_ports(&two, &[port], true, 10).await.unwrap();
4075 assert_ne!(bumped, vec![port]);
4076 drop(bumped_claim);
4077
4078 drop(claim);
4080 let (resolved, _claim) = claim_ports(&two, &[port], false, 0).await.unwrap();
4081 assert_eq!(resolved, vec![port]);
4082 }
4083
4084 #[tokio::test]
4085 async fn an_old_attempts_claim_does_not_release_its_replacement() {
4086 use crate::daemon_id::DaemonId;
4087 let _forks = FORKS.lock().await;
4088 let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
4089 let port = probe.local_addr().unwrap().port();
4090 drop(probe);
4091 let one = DaemonId::new("claim-restart", "web");
4092 let other = DaemonId::new("claim-other", "web");
4093
4094 let (_, old) = claim_ports(&one, &[port], false, 0).await.unwrap();
4095 let (_, new) = claim_ports(&one, &[port], false, 0).await.unwrap();
4096 drop(old);
4097 assert!(claim_ports(&other, &[port], false, 0).await.is_err());
4098 drop(new);
4099 assert!(claim_ports(&other, &[port], false, 0).await.is_ok());
4100 }
4101
4102 #[cfg(unix)]
4103 #[test]
4104 fn a_copy_of_a_probe_socket_does_not_look_like_a_listener() {
4105 use super::bind_probe;
4106 let copy = bind_probe(SocketAddr::from(([0, 0, 0, 0], 0))).unwrap();
4109 let port = copy.local_addr().unwrap().port();
4110 let addr = SocketAddr::from(([127, 0, 0, 1], port));
4111 bind_probe(addr).unwrap();
4112 let timeout = std::time::Duration::from_millis(200);
4115 assert!(std::net::TcpStream::connect_timeout(&addr, timeout).is_err());
4116 drop(copy);
4117 }
4118
4119 #[cfg(target_os = "linux")]
4128 #[tokio::test]
4129 async fn a_free_port_stays_free_while_another_thread_forks() {
4130 use crate::inherited_fds::CloseInheritedFds;
4131 use std::sync::Arc;
4132 use std::sync::atomic::{AtomicBool, Ordering};
4133
4134 let _forks = FORKS.lock().await;
4135 let port = std::net::TcpListener::bind("127.0.0.1:0")
4136 .unwrap()
4137 .local_addr()
4138 .unwrap()
4139 .port();
4140 let stop = Arc::new(AtomicBool::new(false));
4141 let forker = std::thread::spawn({
4142 let stop = stop.clone();
4143 move || {
4144 while !stop.load(Ordering::Relaxed) {
4145 std::process::Command::new("true")
4148 .close_inherited_fds()
4149 .status()
4150 .unwrap();
4151 }
4152 }
4153 });
4154 let mut conflicts = Vec::new();
4155 for _ in 0..500 {
4156 conflicts.extend(port_bind_conflict(port).await);
4157 }
4158 stop.store(true, Ordering::Relaxed);
4159 forker.join().unwrap();
4160 assert!(
4161 conflicts.is_empty(),
4162 "free port looked taken on {conflicts:?}"
4163 );
4164 }
4165
4166 fn ip(s: &str) -> IpAddr {
4167 s.parse().unwrap()
4168 }
4169
4170 fn socket(addr: &str, listening: bool, pid: u32) -> TcpSocket {
4171 TcpSocket {
4172 addr: addr.parse::<SocketAddr>().unwrap(),
4173 listening,
4174 pid,
4175 process: format!("p{pid}"),
4176 }
4177 }
4178
4179 #[test]
4180 fn only_a_listener_whose_address_conflicts_is_named() {
4181 let all = || {
4182 [
4183 socket("192.0.2.1:3000", true, 1),
4184 socket("127.0.0.1:3000", true, 2),
4185 socket("[::1]:3000", true, 3),
4186 socket("127.0.0.1:4000", true, 4),
4187 ]
4188 };
4189 assert_eq!(
4191 pick_port_owner(all(), 3000, ip("127.0.0.1")),
4192 Some((2, "p2".into()))
4193 );
4194 assert_eq!(
4195 pick_port_owner(all(), 3000, ip("::1")),
4196 Some((3, "p3".into()))
4197 );
4198 let v4 = pick_port_owner(all(), 3000, ip("0.0.0.0")).unwrap().0;
4200 assert!([1, 2].contains(&v4));
4201 assert_eq!(
4203 pick_port_owner([socket("[::1]:3000", true, 3)], 3000, ip("127.0.0.1")),
4204 None
4205 );
4206 assert_eq!(pick_port_owner(all(), 5000, ip("127.0.0.1")), None);
4207
4208 let both = [
4211 socket("127.0.0.1:3000", false, 5),
4212 socket("0.0.0.0:3000", true, 6),
4213 ];
4214 assert_eq!(
4215 pick_port_owner(both, 3000, ip("127.0.0.1")),
4216 Some((6, "p6".into()))
4217 );
4218 assert_eq!(
4219 pick_port_owner([socket("127.0.0.1:3000", false, 5)], 3000, ip("127.0.0.1")),
4220 Some((5, "p5".into()))
4221 );
4222
4223 let v6_wildcard = || {
4226 [
4227 socket("[::]:3000", true, 7),
4228 socket("127.0.0.1:3000", false, 8),
4229 ]
4230 };
4231 assert_eq!(
4232 pick_port_owner(v6_wildcard(), 3000, ip("127.0.0.1")),
4233 Some((8, "p8".into()))
4234 );
4235 assert_eq!(
4236 pick_port_owner(v6_wildcard(), 3000, ip("0.0.0.0")),
4237 Some((8, "p8".into()))
4238 );
4239 assert_eq!(
4241 pick_port_owner([socket("[::]:3000", true, 7)], 3000, ip("127.0.0.1")),
4242 Some((7, "p7".into()))
4243 );
4244 assert_eq!(
4246 pick_port_owner(
4247 [socket("[::ffff:127.0.0.1]:3000", false, 9)],
4248 3000,
4249 ip("127.0.0.1")
4250 ),
4251 Some((9, "p9".into()))
4252 );
4253
4254 assert_eq!(listener_match(ip("0.0.0.0"), ip("127.0.0.1")), Some(1));
4255 assert_eq!(listener_match(ip("::"), ip("127.0.0.1")), Some(2));
4256 assert_eq!(listener_match(ip("::1"), ip("127.0.0.1")), None);
4257 assert_eq!(listener_match(ip("192.0.2.1"), ip("127.0.0.1")), None);
4258 assert_eq!(shown_address(ip("::1")), "[::1]");
4259 }
4260}
4261
4262#[cfg(test)]
4263mod active_port_tests {
4264 use super::*;
4265 use crate::config_types::PortConfig;
4266 use listeners::{Listener, Process, Protocol, SocketState};
4267 use std::net::{IpAddr, Ipv4Addr, SocketAddr};
4268
4269 fn listener(pid: u32, port: u16, protocol: Protocol, state: SocketState) -> Listener {
4270 Listener {
4271 process: Process {
4272 pid,
4273 name: "test".to_string(),
4274 path: "/test".to_string(),
4275 },
4276 socket: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
4277 protocol,
4278 state,
4279 }
4280 }
4281
4282 #[test]
4283 fn active_port_candidates_exclude_outbound_tcp_and_udp_sockets() {
4284 let daemon_pid = 100;
4285 let child_pid = 101;
4286 let descendant_pids = [daemon_pid, child_pid].into_iter().collect();
4287 let listeners = vec![
4288 listener(child_pid, 3004, Protocol::TCP, SocketState::Listen),
4289 listener(daemon_pid, 47082, Protocol::TCP, SocketState::Established),
4290 listener(daemon_pid, 5353, Protocol::UDP, SocketState::Unknown),
4291 listener(999, 9000, Protocol::TCP, SocketState::Listen),
4292 ];
4293
4294 assert_eq!(
4295 select_active_port(listeners, &descendant_pids, None),
4296 ActivePortSelection::Selected(3004)
4297 );
4298 }
4299
4300 #[test]
4301 fn bumped_cmd_readiness_prefers_resolved_primary_port() {
4302 let daemon = crate::daemon::Daemon {
4303 resolved_port: vec![3004],
4304 port: Some(PortConfig {
4305 expect: vec![3000],
4306 ..PortConfig::default()
4307 }),
4308 ..crate::daemon::Daemon::default()
4309 };
4310 let descendant_pids = [100].into_iter().collect();
4311 let listeners = vec![
4312 listener(100, 9000, Protocol::TCP, SocketState::Listen),
4313 listener(100, 3004, Protocol::TCP, SocketState::Listen),
4314 ];
4315
4316 assert_eq!(discovery_preferred_port(&daemon), Some(3004));
4317 assert_eq!(
4318 select_active_port(
4319 listeners,
4320 &descendant_pids,
4321 discovery_preferred_port(&daemon),
4322 ),
4323 ActivePortSelection::Selected(3004)
4324 );
4325 }
4326
4327 #[test]
4328 fn legacy_state_uses_expected_primary_port_for_discovery() {
4329 let daemon = crate::daemon::Daemon {
4330 port: Some(PortConfig {
4331 expect: vec![3000],
4332 ..PortConfig::default()
4333 }),
4334 ..crate::daemon::Daemon::default()
4335 };
4336
4337 assert_eq!(discovery_preferred_port(&daemon), Some(3000));
4338 }
4339
4340 #[test]
4341 fn ambiguous_candidates_leave_active_port_unset() {
4342 let descendant_pids = [100].into_iter().collect();
4343 let listeners = vec![
4344 listener(100, 9000, Protocol::TCP, SocketState::Listen),
4345 listener(100, 3000, Protocol::TCP, SocketState::Listen),
4346 ];
4347
4348 assert_eq!(
4349 select_active_port(listeners, &descendant_pids, None),
4350 ActivePortSelection::Ambiguous(vec![3000, 9000])
4351 );
4352 }
4353
4354 #[test]
4355 fn bumped_ready_port_sets_only_the_resolved_primary_without_scanning() {
4356 assert_eq!(active_port_from_ready_port(3004, &[3004]), Some(3004));
4357 assert_eq!(active_port_from_ready_port(4003, &[3003, 4003]), None);
4358 }
4359
4360 #[test]
4361 fn delay_readiness_requires_delay_only_and_a_running_process() {
4362 assert!(delay_readiness_succeeded(false, false, false, true));
4363 assert!(!delay_readiness_succeeded(false, true, false, true));
4364 assert!(!delay_readiness_succeeded(false, false, true, false));
4365 assert!(!delay_readiness_succeeded(false, false, false, false));
4366 assert!(!delay_readiness_succeeded(true, false, false, true));
4367 }
4368}
4369
4370fn is_daemon_slug_target(id: &DaemonId) -> bool {
4378 let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
4382 slugs.iter().any(|(slug, entry)| {
4383 let daemon_name = entry.daemon.as_deref().unwrap_or(slug);
4384 id.name() == daemon_name
4385 })
4386}
4387
4388#[cfg(test)]
4389mod oneshot_tests {
4390 use super::*;
4391
4392 #[test]
4393 fn oneshot_clean_exit_is_completed() {
4394 let (status, success) = terminal_exit_state("exit", true, 0, true);
4395 assert!(matches!(status, DaemonStatus::Completed));
4396 assert!(success);
4397 }
4398
4399 #[test]
4400 fn service_clean_exit_is_still_stopped() {
4401 let (status, success) = terminal_exit_state("exit", false, 0, true);
4402 assert!(matches!(status, DaemonStatus::Stopped));
4403 assert!(success);
4404 }
4405
4406 #[test]
4407 fn oneshot_failure_is_errored_so_retry_applies() {
4408 let (status, success) = terminal_exit_state("fail", true, 3, false);
4411 assert!(matches!(status, DaemonStatus::Errored(3)));
4412 assert!(!success);
4413 }
4414
4415 #[test]
4416 fn a_stop_cancels_the_retry_sequence_it_finds() {
4417 let id = DaemonId::new("retry-cancel-test", "task");
4418 let claim = SUPERVISOR.mark_retrying(&id);
4419 assert!(!claim.is_cancelled());
4420 assert!(SUPERVISOR.is_retrying(&id));
4421 SUPERVISOR.cancel_retrying(&id);
4422 assert!(claim.is_cancelled());
4423 drop(claim);
4424 assert!(!SUPERVISOR.is_retrying(&id));
4425 }
4426
4427 #[test]
4428 fn a_stop_cancels_every_sequence_for_the_daemon() {
4429 let id = DaemonId::new("retry-cancel-test", "concurrent");
4433 let first = SUPERVISOR.mark_retrying(&id);
4434 let second = SUPERVISOR.mark_retrying(&id);
4435 SUPERVISOR.cancel_retrying(&id);
4436 assert!(first.is_cancelled());
4437 assert!(second.is_cancelled());
4438 drop(second);
4439 assert!(SUPERVISOR.is_retrying(&id));
4441 drop(first);
4442 assert!(!SUPERVISOR.is_retrying(&id));
4443 }
4444
4445 #[test]
4446 fn a_stop_invalidates_an_attempt_decided_on_before_it() {
4447 let id = DaemonId::new("stop-epoch-test", "task");
4451 let approved_at = SUPERVISOR.stop_epoch(&id);
4452 assert_eq!(SUPERVISOR.stop_epoch(&id), approved_at);
4453 SUPERVISOR.bump_stop_epoch(&id);
4454 assert_ne!(SUPERVISOR.stop_epoch(&id), approved_at);
4455 let approved_after = SUPERVISOR.stop_epoch(&id);
4457 assert_eq!(SUPERVISOR.stop_epoch(&id), approved_after);
4458 }
4459
4460 #[test]
4461 fn stop_epochs_are_tracked_per_daemon() {
4462 let stopped = DaemonId::new("stop-epoch-test", "stopped");
4463 let untouched = DaemonId::new("stop-epoch-test", "untouched");
4464 let approved_at = SUPERVISOR.stop_epoch(&untouched);
4465 SUPERVISOR.bump_stop_epoch(&stopped);
4466 assert_eq!(SUPERVISOR.stop_epoch(&untouched), approved_at);
4467 }
4468
4469 #[test]
4470 fn a_stop_leaves_a_completed_task_alone() {
4471 assert!(stop_keeps_finalized_status(&DaemonStatus::Completed));
4473 }
4474
4475 #[test]
4476 fn a_stop_replaces_a_failure_so_retries_do_not_resume() {
4477 assert!(!stop_keeps_finalized_status(&DaemonStatus::Errored(1)));
4480 assert!(!stop_keeps_finalized_status(&DaemonStatus::Running));
4481 assert!(!stop_keeps_finalized_status(&DaemonStatus::Stopped));
4482 }
4483
4484 #[test]
4485 fn stopped_oneshot_did_not_complete() {
4486 let (status, _) = terminal_exit_state("stop", true, 0, true);
4487 assert!(matches!(status, DaemonStatus::Stopped));
4488 }
4489}
4490
4491#[cfg(all(test, unix))]
4492mod tests {
4493 use super::*;
4494
4495 #[test]
4496 fn test_resolve_run_identity_empty_without_sudo() {
4497 let identity = resolve_run_identity(None, 501, 20, None, None).unwrap();
4498 assert_eq!(identity, RunIdentity::Inherit);
4499 }
4500
4501 #[test]
4502 fn test_resolve_run_identity_sudo_fallback() {
4503 let identity = resolve_run_identity(None, 0, 0, Some("501"), Some("20")).unwrap();
4504 let RunIdentity::Switch { uid, gid, .. } = identity else {
4505 panic!("expected identity switch");
4506 };
4507 assert_eq!(uid.as_raw(), 501);
4508 assert_eq!(gid.as_raw(), 20);
4509 }
4510
4511 #[test]
4512 fn test_resolve_run_identity_ignores_stale_sudo_when_not_root() {
4513 let identity = resolve_run_identity(None, 501, 20, Some("0"), Some("0")).unwrap();
4514 assert_eq!(identity, RunIdentity::Inherit);
4515 }
4516
4517 #[test]
4518 fn test_resolve_configured_user_root_name() {
4519 let identity = resolve_configured_user("root").unwrap();
4520 let RunIdentity::Switch { uid, username, .. } = identity else {
4521 panic!("expected identity switch");
4522 };
4523 assert_eq!(uid.as_raw(), 0);
4524 assert_eq!(
4525 username.as_deref().and_then(|s| s.to_str().ok()),
4526 Some("root")
4527 );
4528 }
4529
4530 #[test]
4531 fn test_resolve_configured_user_root_uid() {
4532 let identity = resolve_configured_user("0").unwrap();
4533 let RunIdentity::Switch { uid, username, .. } = identity else {
4534 panic!("expected identity switch");
4535 };
4536 assert_eq!(uid.as_raw(), 0);
4537 assert_eq!(
4538 username.as_deref().and_then(|s| s.to_str().ok()),
4539 Some("root")
4540 );
4541 }
4542
4543 #[test]
4544 fn test_resolve_configured_user_missing_user_fails() {
4545 let err = resolve_configured_user("pitchfork-user-that-should-not-exist")
4546 .unwrap_err()
4547 .to_string();
4548 assert!(err.contains("does not exist"));
4549 }
4550
4551 #[test]
4552 fn test_resolve_run_identity_requires_root_for_user_switch() {
4553 let err = resolve_run_identity(Some("root"), 501, 20, None, None)
4554 .unwrap_err()
4555 .to_string();
4556 assert!(err.contains("Restart the supervisor with sudo"));
4557 }
4558
4559 #[test]
4560 fn test_resolve_run_identity_same_user_is_noop() {
4561 let identity = resolve_run_identity(Some("root"), 0, 0, Some("501"), Some("20")).unwrap();
4562 assert_eq!(identity, RunIdentity::Inherit);
4563 }
4564
4565 #[test]
4566 fn test_resolve_configured_user_records_home() {
4567 let identity = resolve_configured_user("root").unwrap();
4568 let RunIdentity::Switch { home, .. } = identity else {
4569 panic!("expected identity switch");
4570 };
4571 let expected = nix::unistd::User::from_name("root").unwrap().unwrap().dir;
4572 assert_eq!(home, Some(expected));
4573 }
4574
4575 fn switch_to(name: Option<&str>, home: Option<&str>) -> RunIdentity {
4576 RunIdentity::Switch {
4577 uid: nix::unistd::Uid::from_raw(501),
4578 gid: nix::unistd::Gid::from_raw(20),
4579 username: name.map(|n| CString::new(n).unwrap()),
4580 home: home.map(std::path::PathBuf::from),
4581 }
4582 }
4583
4584 fn command_env(
4587 command: &tokio::process::Command,
4588 key: &str,
4589 ) -> Option<Option<std::ffi::OsString>> {
4590 command
4591 .as_std()
4592 .get_envs()
4593 .find(|(k, _)| *k == key)
4594 .map(|(_, v)| v.map(ToOwned::to_owned))
4595 }
4596
4597 fn daemon_command(
4599 identity: &RunIdentity,
4600 daemon_env: Option<&IndexMap<String, String>>,
4601 ) -> tokio::process::Command {
4602 let mut command = tokio::process::Command::new("true");
4603 apply_identity_env(&mut command, identity);
4604 apply_runtime_env(
4605 &mut command,
4606 &DaemonId::new("identity-env-test", "api"),
4607 0,
4608 daemon_env,
4609 &[],
4610 );
4611 command
4612 }
4613
4614 #[test]
4615 fn test_identity_env_describes_the_switched_user() {
4616 let command = daemon_command(&switch_to(Some("alice"), Some("/home/alice")), None);
4617 assert_eq!(
4618 command_env(&command, "HOME"),
4619 Some(Some("/home/alice".into()))
4620 );
4621 assert_eq!(command_env(&command, "USER"), Some(Some("alice".into())));
4622 assert_eq!(command_env(&command, "LOGNAME"), Some(Some("alice".into())));
4623 }
4624
4625 #[test]
4626 fn test_identity_env_leaves_inherited_env_alone() {
4627 let command = daemon_command(&RunIdentity::Inherit, None);
4628 assert_eq!(command_env(&command, "HOME"), None);
4629 assert_eq!(command_env(&command, "USER"), None);
4630 assert_eq!(command_env(&command, "LOGNAME"), None);
4631 }
4632
4633 #[test]
4634 fn test_root_sudo_to_root_preserves_environment() {
4635 let identity = resolve_run_identity(None, 0, 0, Some("0"), Some("0")).unwrap();
4636 assert_eq!(identity, RunIdentity::Inherit);
4637 let command = daemon_command(&identity, None);
4638 for key in ["HOME", "USER", "LOGNAME"] {
4639 assert_eq!(command_env(&command, key), None);
4640 }
4641 }
4642
4643 #[test]
4644 fn test_daemon_env_overrides_identity_env() {
4645 let mut env = IndexMap::new();
4646 env.insert("HOME".to_string(), "/srv/app".to_string());
4647 env.insert("USER".to_string(), "app".to_string());
4648 let command = daemon_command(&switch_to(Some("alice"), Some("/home/alice")), Some(&env));
4649 assert_eq!(command_env(&command, "HOME"), Some(Some("/srv/app".into())));
4650 assert_eq!(command_env(&command, "USER"), Some(Some("app".into())));
4651 assert_eq!(command_env(&command, "LOGNAME"), Some(Some("alice".into())));
4652 }
4653
4654 #[test]
4655 fn test_identity_env_drops_values_without_a_passwd_entry() {
4656 let command = daemon_command(&switch_to(None, None), None);
4659 assert_eq!(command_env(&command, "HOME"), Some(None));
4660 assert_eq!(command_env(&command, "USER"), Some(None));
4661 assert_eq!(command_env(&command, "LOGNAME"), Some(None));
4662 }
4663
4664 #[test]
4665 fn test_daemon_env_restores_values_without_a_passwd_entry() {
4666 let mut env = IndexMap::new();
4667 env.insert("HOME".to_string(), "/srv/app".to_string());
4668 let command = daemon_command(&switch_to(None, None), Some(&env));
4669 assert_eq!(command_env(&command, "HOME"), Some(Some("/srv/app".into())));
4670 }
4671}
4672
4673fn inject_proxy_env(cmd: &mut tokio::process::Command, host: &Option<String>) {
4682 let s = crate::settings::settings();
4683 let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
4684
4685 if s.proxy.enable && host.is_some() && !lan_enabled {
4686 cmd.env("HOST", "127.0.0.1");
4689 }
4690
4691 if let Some(url) = build_pitchfork_url(host, &s) {
4693 cmd.env("PITCHFORK_URL", &url);
4694 }
4695
4696 if s.proxy.enable && s.proxy.https {
4702 let ca_path = if s.proxy.tls_cert.is_empty() {
4703 crate::env::PITCHFORK_STATE_DIR.join("proxy").join("ca.pem")
4704 } else {
4705 std::path::PathBuf::from(&s.proxy.tls_cert)
4706 };
4707 if ca_path.exists() {
4708 let ca_path = ca_path.to_string_lossy().to_string();
4709 cmd.env("PITCHFORK_CA_FILE", &ca_path);
4710 cmd.env("NODE_EXTRA_CA_CERTS", &ca_path);
4711 }
4712 }
4713
4714 if s.proxy.enable {
4716 let tld = if lan_enabled { "local" } else { &s.proxy.tld };
4717 cmd.env("__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS", format!(".{tld}"));
4718 }
4719
4720 if lan_enabled {
4722 cmd.env("PITCHFORK_LAN", "1");
4723 }
4724}
4725
4726async fn daemon_proxy_host(opts: &RunOptions) -> Option<String> {
4732 if !crate::settings::settings().proxy.enable {
4735 return None;
4736 }
4737 if let Some(slug) = opts.slug.as_deref()
4741 && crate::proxy::hostname::hostname_fits(slug)
4742 {
4743 return opts.slug.clone();
4744 }
4745 let config_dir = opts
4748 .watch_base_dir
4749 .clone()
4750 .unwrap_or_else(|| opts.dir.0.clone());
4751 let id = opts.id.clone();
4752 tokio::task::spawn_blocking(move || {
4758 let pt = crate::pitchfork_toml::PitchforkToml::all_merged_from(&config_dir).ok()?;
4759 let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
4760 crate::proxy::hostname::host_for_daemon(&id, pt.daemons.get(&id), &slugs)
4761 })
4762 .await
4763 .unwrap_or_default()
4764}
4765
4766fn build_pitchfork_url(host: &Option<String>, s: &crate::settings::Settings) -> Option<String> {
4770 crate::proxy::build_proxy_url(host.as_deref(), s)
4771}
4772
4773#[cfg(test)]
4774mod ready_check_tests {
4775 use super::*;
4776 use std::time::Duration;
4777
4778 #[test]
4779 fn any_ready_check_remaining_prefers_unbounded_checks() {
4780 let http = ReadyHttp::new("http://localhost/health");
4781 let cmd = ReadyCmd::new("true");
4782
4783 assert!(any_ready_check_remaining(
4784 None,
4785 false,
4786 None,
4787 false,
4788 Some(&http),
4789 false,
4790 None,
4791 false
4792 ));
4793 assert!(any_ready_check_remaining(
4794 None,
4795 false,
4796 None,
4797 false,
4798 None,
4799 false,
4800 Some(&cmd),
4801 false
4802 ));
4803 assert!(any_ready_check_remaining(
4804 None,
4805 false,
4806 Some(&ReadyPort::new(8080)),
4807 false,
4808 Some(&http),
4809 true,
4810 Some(&cmd),
4811 true
4812 ));
4813 }
4814
4815 #[test]
4816 fn any_ready_check_remaining_exhausted_timed_checks() {
4817 let http = ReadyHttp {
4818 url: "http://localhost/health".to_string(),
4819 status: vec![],
4820 timeout: Some(Duration::from_secs(5)),
4821 };
4822 let cmd = ReadyCmd {
4823 run: "true".into(),
4824 timeout: Some(Duration::from_secs(5)),
4825 };
4826
4827 assert!(any_ready_check_remaining(
4828 None,
4829 false,
4830 None,
4831 false,
4832 Some(&http),
4833 false,
4834 Some(&cmd),
4835 false
4836 ));
4837 assert!(!any_ready_check_remaining(
4838 None,
4839 false,
4840 None,
4841 false,
4842 Some(&http),
4843 true,
4844 Some(&cmd),
4845 true
4846 ));
4847 }
4848
4849 #[tokio::test]
4850 async fn spawn_cmd_probe_reports_success() {
4851 let id = DaemonId::new("global", "probe-test");
4852 let probe = spawn_cmd_probe(&id, &"true".into(), &std::env::temp_dir(), 0, None, &[]);
4853 let status = probe.result_rx.await.unwrap().unwrap();
4854 assert!(status.success());
4855 }
4856
4857 #[cfg(unix)]
4861 #[tokio::test]
4862 async fn spawn_cmd_probe_runs_an_argv_without_a_shell() {
4863 let id = DaemonId::new("global", "probe-test");
4864 let argv = |arg: &str| -> RunCommand {
4865 RunCommand::Argv(
4866 ["test", arg, "=", "a b $HOME %PATH% &"]
4867 .map(str::to_string)
4868 .to_vec(),
4869 )
4870 };
4871 let probe = spawn_cmd_probe(
4872 &id,
4873 &argv("a b $HOME %PATH% &"),
4874 &std::env::temp_dir(),
4875 0,
4876 None,
4877 &[],
4878 );
4879 assert!(probe.result_rx.await.unwrap().unwrap().success());
4880 let probe = spawn_cmd_probe(
4882 &id,
4883 &"test a b $HOME %PATH% & = 'a b $HOME %PATH% &'".into(),
4884 &std::env::temp_dir(),
4885 0,
4886 None,
4887 &[],
4888 );
4889 assert!(!probe.result_rx.await.unwrap().unwrap().success());
4890 let probe = spawn_cmd_probe(&id, &argv("different"), &std::env::temp_dir(), 0, None, &[]);
4891 assert!(!probe.result_rx.await.unwrap().unwrap().success());
4892 }
4893
4894 #[tokio::test]
4895 async fn spawn_cmd_probe_stops_on_request() {
4896 let id = DaemonId::new("global", "probe-test");
4897 let probe = spawn_cmd_probe(&id, &"sleep 30".into(), &std::env::temp_dir(), 0, None, &[]);
4898 let CmdProbe {
4899 cancel_tx,
4900 result_rx,
4901 } = probe;
4902 let _ = cancel_tx.send(());
4903 let status = result_rx.await.unwrap().unwrap();
4904 assert!(!status.success());
4905 }
4906
4907 #[tokio::test]
4908 async fn spawn_cmd_probe_receives_daemon_and_resolved_port_environment() {
4909 let id = DaemonId::new("worktree", "api");
4910 let daemon_env = IndexMap::from([("CUSTOM_VALUE".to_string(), "yes".to_string())]);
4911 let check = if cfg!(windows) {
4914 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"#
4915 } else {
4916 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"#
4917 };
4918 let probe = spawn_cmd_probe(
4919 &id,
4920 &check.into(),
4921 &std::env::temp_dir(),
4922 2,
4923 Some(&daemon_env),
4924 &[4100, 5100],
4925 );
4926 let status = probe.result_rx.await.unwrap().unwrap();
4927 assert!(status.success());
4928 }
4929
4930 #[test]
4931 fn configured_ready_port_follows_expected_port_bump() {
4932 assert_eq!(resolve_configured_ready_port(3000, &[3000], &[3004]), 3004);
4933 assert_eq!(
4934 resolve_configured_ready_port(4000, &[3000, 4000], &[3003, 4003]),
4935 4003
4936 );
4937 assert_eq!(resolve_configured_ready_port(8080, &[3000], &[3004]), 8080);
4938 }
4939}
4940
4941#[cfg(test)]
4942mod launch_command_tests {
4943 use super::{invalid_argv_program, launch_command};
4944 use crate::daemon_id::DaemonId;
4945
4946 #[test]
4947 fn refuses_an_argv_whose_program_rendered_empty_or_to_exec() {
4948 let id = DaemonId::new("proj", "api");
4949 assert!(invalid_argv_program(&id, &[]).is_some());
4950 assert!(invalid_argv_program(&id, &words(&["", "server.js"])).is_some());
4951 assert!(invalid_argv_program(&id, &words(&["exec", "node"])).is_some());
4952 assert_eq!(invalid_argv_program(&id, &words(&["node", ""])), None);
4953 }
4954
4955 #[test]
4956 fn refuses_a_probe_array_whose_program_rendered_empty_or_to_exec() {
4957 use super::invalid_probe_program;
4958 use crate::pitchfork_toml::RunCommand;
4959 let id = DaemonId::new("proj", "api");
4960 for field in ["ready_cmd", "health_cmd"] {
4961 let check =
4962 |run: Vec<String>| invalid_probe_program(&id, field, Some(&RunCommand::Argv(run)));
4963 assert!(check(vec![]).unwrap().contains(field));
4964 assert!(check(words(&["", "-h"])).is_some());
4965 assert!(check(words(&["exec", "pg_isready"])).is_some());
4966 assert_eq!(check(words(&["pg_isready", ""])), None);
4967 }
4968 assert_eq!(
4970 invalid_probe_program(&id, "health_cmd", Some(&RunCommand::Shell(String::new()))),
4971 None
4972 );
4973 assert_eq!(invalid_probe_program(&id, "health_cmd", None), None);
4974 }
4975
4976 fn words(words: &[&str]) -> Vec<String> {
4977 words.iter().map(|w| w.to_string()).collect()
4978 }
4979
4980 #[test]
4981 fn windows_rejects_only_enabled_unsupported_options() {
4982 let mut opts = crate::daemon::RunOptions::default();
4983 assert_eq!(super::unsupported_windows_options(&opts, ""), None);
4984 opts.pty = Some(false);
4985 opts.user = Some(" \t".into());
4986 assert_eq!(super::unsupported_windows_options(&opts, " \t"), None);
4987 opts.pty = Some(true);
4988 assert!(
4989 super::unsupported_windows_options(&opts, "")
4990 .unwrap()
4991 .contains("pty = true")
4992 );
4993 opts.pty = Some(false);
4994 opts.user = Some("postgres".into());
4995 assert!(
4996 super::unsupported_windows_options(&opts, "")
4997 .unwrap()
4998 .contains("user switching")
4999 );
5000 opts.user = None;
5001 assert!(
5002 super::unsupported_windows_options(&opts, "postgres")
5003 .unwrap()
5004 .contains("settings.supervisor.user")
5005 );
5006 }
5007
5008 #[test]
5009 fn starts_the_first_word_with_the_rest_as_arguments() {
5010 let argv = words(&["node", "my server.js", "--name=\"a b\"", "&", "%PATH%"]);
5011 assert_eq!(
5012 launch_command(argv, None),
5013 (
5014 "node".to_string(),
5015 words(&["my server.js", "--name=\"a b\"", "&", "%PATH%"])
5016 )
5017 );
5018 }
5019
5020 #[test]
5021 fn mise_receives_every_word_after_the_separator() {
5022 let argv = words(&["node", "my server.js", "'single'"]);
5023 let mise = std::path::Path::new("/opt/mise/bin/mise");
5024 let (program, args) = launch_command(argv, Some(mise));
5025 assert_eq!(program, mise.to_string_lossy());
5026 assert_eq!(
5027 args,
5028 words(&["x", "--", "node", "my server.js", "'single'"])
5029 );
5030 }
5031}
5032
5033#[cfg(all(test, windows))]
5034mod windows_retry_tests {
5035 use super::*;
5036 use crate::config_types::{Dir, Retry};
5037 use crate::settings::reload_settings;
5038 use std::process::Stdio;
5039 use tokio::io::AsyncBufReadExt;
5040
5041 #[tokio::test]
5042 async fn forced_retry_claim_revalidates_settings_before_stopping_a_live_instance() {
5043 const CHILD_ENV: &str = "PITCHFORK_TEST_WINDOWS_RETRY_CLAIM";
5044 const CHILD_SENTINEL: &str = "windows-retry-claim-child-ran";
5045 if std::env::var_os(CHILD_ENV).is_none() {
5046 let temp = tempfile::tempdir().unwrap();
5049 std::fs::create_dir(temp.path().join("config")).unwrap();
5050 std::fs::write(
5051 temp.path().join("pitchfork.toml"),
5052 "[settings.supervisor]\nuser = ''\n",
5053 )
5054 .unwrap();
5055 let mut command = tokio::process::Command::new(std::env::current_exe().unwrap());
5056 for (name, _) in std::env::vars_os() {
5057 if name
5058 .to_string_lossy()
5059 .to_ascii_uppercase()
5060 .starts_with("PITCHFORK_")
5061 {
5062 command.env_remove(name);
5063 }
5064 }
5065 command
5066 .args([
5067 "--exact",
5068 "supervisor::lifecycle::windows_retry_tests::forced_retry_claim_revalidates_settings_before_stopping_a_live_instance",
5069 "--nocapture",
5070 ])
5071 .current_dir(temp.path())
5072 .env(CHILD_ENV, "1")
5073 .env("PITCHFORK_CONFIG_DIR", temp.path().join("config"))
5074 .env("PITCHFORK_STATE_DIR", temp.path().join("state"))
5075 .env("PITCHFORK_LOGS_DIR", temp.path().join("logs"))
5076 .env("PITCHFORK_BOOT_EXECUTABLE", temp.path().join("missing.exe"))
5077 .hide_console_window()
5078 .kill_on_drop(true);
5079 let output = time::timeout(Duration::from_secs(30), command.output())
5080 .await
5081 .expect("isolated retry claim test timed out")
5082 .unwrap();
5083 assert!(
5084 output.status.success(),
5085 "isolated retry claim test failed:\nstdout:\n{}\nstderr:\n{}",
5086 String::from_utf8_lossy(&output.stdout),
5087 String::from_utf8_lossy(&output.stderr)
5088 );
5089 assert!(String::from_utf8_lossy(&output.stderr).contains(CHILD_SENTINEL));
5090 return;
5091 }
5092 eprintln!("{CHILD_SENTINEL}");
5093
5094 let mut opts = RunOptions {
5095 id: DaemonId::new("windows-retry", "live"),
5096 force: true,
5097 wait_ready: true,
5098 retry: Retry(2),
5099 dir: Dir(env::CWD.clone()),
5100 ..RunOptions::default()
5101 };
5102 let mut restart_mark = None;
5103 let mut guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
5104 assert!(
5105 SUPERVISOR
5106 .claim_or_defer(&opts, &mut guard, &mut restart_mark, None)
5107 .await
5108 .unwrap()
5109 .is_none()
5110 );
5111 drop(guard.take());
5112 let retrying_claim = SUPERVISOR.mark_retrying(&opts.id);
5113
5114 let powershell = std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap())
5119 .join("System32/WindowsPowerShell/v1.0/powershell.exe");
5120 let mut child = tokio::process::Command::new(powershell)
5121 .args([
5122 "-NoLogo",
5123 "-NoProfile",
5124 "-NonInteractive",
5125 "-Command",
5126 "[Console]::Out.WriteLine('READY'); [Console]::In.ReadToEnd() | Out-Null",
5127 ])
5128 .current_dir(std::env::var_os("SystemRoot").unwrap())
5129 .stdin(Stdio::piped())
5130 .stdout(Stdio::piped())
5131 .stderr(Stdio::null())
5132 .kill_on_drop(true)
5133 .hide_console_window()
5134 .spawn()
5135 .unwrap();
5136 let mut stdout = tokio::io::BufReader::new(child.stdout.take().unwrap());
5137 let mut ready = String::new();
5138 stdout.read_line(&mut ready).await.unwrap();
5139 assert_eq!(ready.trim_end(), "READY");
5140 let pid = child.id().unwrap();
5141 PROCS.refresh_pids(&[pid]);
5142 assert!(PROCS.is_running(pid));
5143 assert!(child.try_wait().unwrap().is_none());
5144 guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
5145 let running = SUPERVISOR
5146 .upsert_daemon(
5147 UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
5148 .set(|o| o.pid = Some(pid))
5149 .build(),
5150 )
5151 .await
5152 .unwrap();
5153 assert!(running.start_time.is_some());
5154 assert_eq!(running.start_time, PROCS.start_time(pid));
5155 let stop_epoch = SUPERVISOR.stop_epoch(&opts.id);
5156
5157 std::fs::write(
5158 env::CWD.join("pitchfork.toml"),
5159 "[settings.supervisor]\nuser = 'unsupported-account'\n",
5160 )
5161 .unwrap();
5162 reload_settings();
5163 assert_eq!(settings().supervisor.user, "unsupported-account");
5164 opts.retry_count = 1;
5165 let response = SUPERVISOR
5166 .claim_or_defer(&opts, &mut guard, &mut restart_mark, None)
5167 .await
5168 .unwrap();
5169
5170 assert!(
5172 child.try_wait().unwrap().is_none(),
5173 "the live instance was stopped"
5174 );
5175 let preserved = SUPERVISOR.get_daemon(&opts.id).await.unwrap();
5176 assert_eq!(preserved.pid, Some(pid));
5177 assert!(preserved.status.is_running());
5178 assert_eq!(
5179 serde_json::to_value(&preserved).unwrap(),
5180 serde_json::to_value(&running).unwrap()
5181 );
5182 assert_eq!(SUPERVISOR.stop_epoch(&opts.id), stop_epoch);
5183 assert!(!retrying_claim.is_cancelled());
5184 assert!(restart_mark.is_none());
5185 assert!(matches!(response, Some(IpcResponse::DaemonFailed { .. })));
5186 drop(guard.take());
5187 child.kill().await.unwrap();
5188 child.wait().await.unwrap();
5189
5190 opts.id = DaemonId::new("windows-retry", "pidless");
5193 guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
5194 SUPERVISOR
5195 .upsert_daemon(
5196 UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Errored(7)).build(),
5197 )
5198 .await
5199 .unwrap();
5200 assert!(matches!(
5201 SUPERVISOR
5202 .claim_or_defer(&opts, &mut guard, &mut restart_mark, None)
5203 .await
5204 .unwrap(),
5205 Some(IpcResponse::DaemonFailed { .. })
5206 ));
5207 let failed = SUPERVISOR.get_daemon(&opts.id).await.unwrap();
5208 assert!(failed.status.is_failed());
5209 assert!(failed.pid.is_none());
5210 assert_eq!(failed.retry_count, 1);
5211 assert_eq!(failed.retry, Retry(2));
5212 }
5213}
5214
5215#[cfg(test)]
5216mod output_reader_tests {
5217 use super::{forward_output_lines, output_line_text};
5218
5219 #[test]
5220 fn line_endings_are_removed() {
5221 assert_eq!(output_line_text(b"ready\n"), "ready");
5222 assert_eq!(output_line_text(b"ready\r\n"), "ready");
5224 assert_eq!(output_line_text(b"ready\r\r\n"), "ready");
5225 assert_eq!(output_line_text(b"ready"), "ready");
5227 }
5228
5229 #[tokio::test]
5230 async fn a_line_that_is_not_utf8_does_not_end_the_read() {
5231 let output: &[u8] = b"before\nbad \xff\xfe bytes\nafter 1\nafter 2\nlast";
5234 let (tx, mut rx) = tokio::sync::mpsc::channel(16);
5235 forward_output_lines(tokio::io::BufReader::new(output), tx).await;
5236
5237 let mut lines = Vec::new();
5238 while let Some(line) = rx.recv().await {
5239 lines.push(line.text);
5240 }
5241 assert_eq!(lines.len(), 5, "{lines:?}");
5242 assert_eq!(lines[0], "before");
5243 assert!(lines[1].starts_with("bad "), "{:?}", lines[1]);
5244 assert_eq!(&lines[2..], ["after 1", "after 2", "last"]);
5245 }
5246}
5247
5248#[cfg(test)]
5249mod output_reader_eio_tests {
5250 use super::forward_output_lines;
5251 use std::pin::Pin;
5252 use std::task::{Context, Poll};
5253
5254 struct EndsWithEio(Option<&'static [u8]>);
5257
5258 impl tokio::io::AsyncRead for EndsWithEio {
5259 fn poll_read(
5260 mut self: Pin<&mut Self>,
5261 _cx: &mut Context<'_>,
5262 buf: &mut tokio::io::ReadBuf<'_>,
5263 ) -> Poll<std::io::Result<()>> {
5264 match self.0.take() {
5265 Some(bytes) => {
5266 buf.put_slice(bytes);
5267 Poll::Ready(Ok(()))
5268 }
5269 None => Poll::Ready(Err(std::io::Error::from_raw_os_error(5))),
5270 }
5271 }
5272 }
5273
5274 #[tokio::test]
5275 async fn a_last_line_cut_off_by_eio_is_still_forwarded() {
5276 let reader = tokio::io::BufReader::new(EndsWithEio(Some(b"first\nlast without newline")));
5277 let (tx, mut rx) = tokio::sync::mpsc::channel(16);
5278 forward_output_lines(reader, tx).await;
5279
5280 let mut lines = Vec::new();
5281 while let Some(line) = rx.recv().await {
5282 lines.push(line.text);
5283 }
5284 assert_eq!(lines, ["first", "last without newline"]);
5285 }
5286}
5287
5288#[cfg(all(test, unix))] mod readiness_tests;