forked from jdx/pitchfork
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlifecycle.rs
More file actions
1800 lines (1674 loc) · 77.4 KB
/
Copy pathlifecycle.rs
File metadata and controls
1800 lines (1674 loc) · 77.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Daemon lifecycle management - start/stop operations
//!
//! Contains the core `run()`, `run_once()`, and `stop()` methods for daemon process management.
use super::hooks::{self, HookType, fire_hook};
use super::{SUPERVISOR, Supervisor};
use crate::daemon::RunOptions;
use crate::daemon_id::DaemonId;
use crate::daemon_status::DaemonStatus;
use crate::error::PortError;
use crate::ipc::IpcResponse;
use crate::procs::PROCS;
use crate::settings::settings;
use crate::shell::Shell;
use crate::supervisor::state::UpsertDaemonOpts;
use crate::{Result, env};
use itertools::Itertools;
use miette::IntoDiagnostic;
use once_cell::sync::Lazy;
use regex::Regex;
use std::collections::HashMap;
#[cfg(unix)]
use std::ffi::CString;
use std::iter::once;
use std::sync::atomic;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufWriter};
use tokio::select;
use tokio::sync::oneshot;
use tokio::time;
/// Cache for compiled regex patterns to avoid recompilation on daemon restarts
static REGEX_CACHE: Lazy<std::sync::Mutex<HashMap<String, Regex>>> =
Lazy::new(|| std::sync::Mutex::new(HashMap::new()));
#[cfg(unix)]
#[derive(Clone, Debug, PartialEq, Eq)]
enum RunIdentity {
Inherit,
Switch {
uid: nix::unistd::Uid,
gid: nix::unistd::Gid,
username: Option<CString>,
},
}
/// Get or compile a regex pattern, caching the result for future use
pub(crate) fn get_or_compile_regex(pattern: &str) -> Option<Regex> {
let mut cache = REGEX_CACHE.lock().unwrap_or_else(|e| e.into_inner());
if let Some(re) = cache.get(pattern) {
return Some(re.clone());
}
match Regex::new(pattern) {
Ok(re) => {
cache.insert(pattern.to_string(), re.clone());
Some(re)
}
Err(e) => {
error!("invalid regex pattern '{pattern}': {e}");
None
}
}
}
impl Supervisor {
/// Run a daemon, handling retries if configured
pub async fn run(&self, opts: RunOptions) -> Result<IpcResponse> {
let id = &opts.id;
let cmd = opts.cmd.clone();
// Clear any pending autostop for this daemon since it's being started
{
let mut pending = self.pending_autostops.lock().await;
if pending.remove(id).is_some() {
info!("cleared pending autostop for {id} (daemon starting)");
}
}
let daemon = self.get_daemon(id).await;
if let Some(daemon) = daemon {
// Stopping state is treated as "not running" - the monitoring task will clean it up
// Only check for Running state with a valid PID
if !daemon.status.is_stopping()
&& !daemon.status.is_stopped()
&& let Some(pid) = daemon.pid
{
if opts.force {
self.stop(id).await?;
info!("run: stop completed for daemon {id}");
} else {
warn!("daemon {id} already running with pid {pid}");
return Ok(IpcResponse::DaemonAlreadyRunning);
}
}
}
// If wait_ready is true and retry is configured, implement retry loop
if opts.wait_ready && opts.retry.count() > 0 {
// Use saturating_add to avoid overflow when retry = u32::MAX (infinite)
let max_attempts = opts.retry.count().saturating_add(1);
for attempt in 0..max_attempts {
let mut retry_opts = opts.clone();
retry_opts.retry_count = attempt;
retry_opts.cmd = cmd.clone();
let result = self.run_once(retry_opts).await?;
match result {
IpcResponse::DaemonReady { daemon } => {
return Ok(IpcResponse::DaemonReady { daemon });
}
IpcResponse::DaemonFailedWithCode { exit_code } => {
if attempt < opts.retry.count() {
let backoff_secs = 2u64.saturating_pow(attempt).min(3600);
info!(
"daemon {id} failed (attempt {}/{}), retrying in {}s",
attempt + 1,
max_attempts,
backoff_secs
);
fire_hook(
HookType::OnRetry,
id.clone(),
opts.dir.0.clone(),
attempt + 1,
opts.env.clone(),
vec![],
)
.await;
time::sleep(Duration::from_secs(backoff_secs)).await;
continue;
} else {
info!("daemon {id} failed after {max_attempts} attempts");
return Ok(IpcResponse::DaemonFailedWithCode { exit_code });
}
}
other => return Ok(other),
}
}
}
// No retry or wait_ready is false
self.run_once(opts).await
}
/// Run a daemon once (single attempt)
pub(crate) async fn run_once(&self, opts: RunOptions) -> Result<IpcResponse> {
let id = &opts.id;
let original_cmd = opts.cmd.clone(); // Save original command for persistence
let cmd = opts.cmd;
// Create channel for readiness notification if wait_ready is true
let (ready_tx, ready_rx) = if opts.wait_ready {
let (tx, rx) = oneshot::channel();
(Some(tx), Some(rx))
} else {
(None, None)
};
// Check port availability and apply auto-bump if configured
let expected_ports = opts
.port
.as_ref()
.map(|p| p.expect.clone())
.unwrap_or_default();
let (resolved_ports, effective_ready_port) = if !expected_ports.is_empty() {
let port_cfg = opts.port.as_ref().unwrap();
match check_ports_available(
&expected_ports,
port_cfg.auto_bump(),
port_cfg.max_bump_attempts(),
)
.await
{
Ok(resolved) => {
let ready_port = if let Some(configured_port) = opts.ready_port {
// If ready_port matches one of the expected ports, apply the same bump offset
let bump_offset = resolved
.first()
.unwrap_or(&0)
.saturating_sub(*expected_ports.first().unwrap_or(&0));
if expected_ports.contains(&configured_port) && bump_offset > 0 {
configured_port
.checked_add(bump_offset)
.or(Some(configured_port))
} else {
Some(configured_port)
}
} else if opts.ready_output.is_none()
&& opts.ready_http.is_none()
&& opts.ready_cmd.is_none()
&& opts.ready_delay.is_none()
{
// No other ready check configured — use the first expected port as a
// TCP port readiness check so the daemon is considered ready once it
// starts listening. Skip port 0 (ephemeral port request).
resolved.first().copied().filter(|&p| p != 0)
} else {
// Another ready check is configured (output/http/cmd/delay).
// Don't add an implicit TCP port check — it could race and fire
// before the daemon has produced any output.
None
};
info!("daemon {id}: ports {expected_ports:?} resolved to {resolved:?}");
(resolved, ready_port)
}
Err(e) => {
error!("daemon {id}: port check failed: {e}");
// Convert PortError to structured IPC response
if let Some(port_error) = e.downcast_ref::<PortError>() {
match port_error {
PortError::InUse { port, process, pid } => {
return Ok(IpcResponse::PortConflict {
port: *port,
process: process.clone(),
pid: *pid,
});
}
PortError::NoAvailablePort {
start_port,
attempts,
} => {
return Ok(IpcResponse::NoAvailablePort {
start_port: *start_port,
attempts: *attempts,
});
}
}
}
return Ok(IpcResponse::DaemonFailed {
error: e.to_string(),
});
}
}
} else {
// When ready_port is set without expected_port, check that the port
// is not already occupied. If another process is listening on it,
// the TCP readiness probe would immediately succeed and pitchfork
// would falsely consider the daemon ready — routing proxy traffic to
// the wrong process.
if let Some(port) = opts.ready_port {
if port > 0 {
if let Some((pid, process)) = detect_port_conflict(port).await {
return Ok(IpcResponse::PortConflict { port, process, pid });
}
}
}
(Vec::new(), opts.ready_port)
};
let cmd: Vec<String> = if opts.mise.unwrap_or(settings().general.mise) {
match settings().resolve_mise_bin() {
Some(mise_bin) => {
let mise_bin_str = mise_bin.to_string_lossy().to_string();
info!("daemon {id}: wrapping command with mise ({mise_bin_str})");
once("exec".to_string())
.chain(once(mise_bin_str))
.chain(once("x".to_string()))
.chain(once("--".to_string()))
.chain(cmd)
.collect_vec()
}
None => {
warn!("daemon {id}: mise=true but mise binary not found, running without mise");
once("exec".to_string()).chain(cmd).collect_vec()
}
}
} else {
once("exec".to_string()).chain(cmd).collect_vec()
};
let args = vec!["-c".to_string(), shell_words::join(&cmd)];
let log_path = id.log_path();
if let Some(parent) = log_path.parent() {
xx::file::mkdirp(parent)?;
}
#[cfg(unix)]
let run_identity = match resolve_effective_run_identity(opts.user.as_deref()) {
Ok(identity) => identity,
Err(e) => {
return Ok(IpcResponse::DaemonFailed {
error: e.to_string(),
});
}
};
info!("run: spawning daemon {id} with args: {args:?}");
// Allocate PTY if configured
#[cfg(unix)]
let pty_pair = if opts.pty.unwrap_or(false) {
match super::pty::openpty() {
Ok(pair) => {
info!("daemon {id}: allocated PTY (pty = true)");
Some(pair)
}
Err(e) => {
warn!("daemon {id}: failed to allocate PTY, falling back to pipes: {e}");
None
}
}
} else {
None
};
let mut cmd = tokio::process::Command::new("sh");
#[cfg(unix)]
if let Some(ref pair) = pty_pair {
// PTY mode: connect both stdout and stderr to the slave PTY.
// The child uses the slave for stdin/stdout/stderr, and we read
// output from the master.
let slave_file = std::fs::File::from(
pair.slave
.try_clone()
.map_err(|e| miette::miette!("failed to dup slave PTY fd: {e}"))?,
);
cmd.stdin(std::process::Stdio::from(slave_file.try_clone().map_err(
|e| miette::miette!("failed to clone slave PTY fd for stdin: {e}"),
)?));
cmd.stdout(std::process::Stdio::from(slave_file.try_clone().map_err(
|e| miette::miette!("failed to clone slave PTY fd for stdout: {e}"),
)?));
cmd.stderr(std::process::Stdio::from(slave_file));
} else {
cmd.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
}
#[cfg(not(unix))]
{
cmd.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
}
cmd.args(&args).current_dir(&opts.dir);
#[cfg(unix)]
if pty_pair.is_none() {
cmd.stdin(std::process::Stdio::null());
}
#[cfg(not(unix))]
cmd.stdin(std::process::Stdio::null());
// Ensure daemon can find user tools by using the original PATH
if let Some(ref path) = *env::ORIGINAL_PATH {
cmd.env("PATH", path);
}
// Apply custom environment variables from config
if let Some(ref env_vars) = opts.env {
cmd.envs(env_vars);
}
// Inject pitchfork metadata env vars AFTER user env so they can't be overwritten
cmd.env("PITCHFORK_DAEMON_ID", id.qualified());
cmd.env("PITCHFORK_DAEMON_NAMESPACE", id.namespace());
cmd.env("PITCHFORK_RETRY_COUNT", opts.retry_count.to_string());
// Inject the resolved ports for the daemon to use
if !resolved_ports.is_empty() {
// Set PORT to the first port for backward compatibility
// When there's only one port, both PORT and PORT0 will be set to the same value.
// This follows the convention used by many deployment platforms (Heroku, etc.).
cmd.env("PORT", resolved_ports[0].to_string());
// Set individual ports as PORT0, PORT1, etc.
for (i, port) in resolved_ports.iter().enumerate() {
cmd.env(format!("PORT{i}"), port.to_string());
}
}
// Inject proxy-related environment variables
inject_proxy_env(&mut cmd, &opts.slug);
#[cfg(unix)]
{
let run_identity = run_identity.clone();
let use_pty = pty_pair.is_some();
unsafe {
cmd.pre_exec(move || {
nix::unistd::setsid().map_err(nix_to_io_error)?;
// When using a PTY, set the slave as the controlling terminal.
// The slave FD has already been dup'd onto stdin/stdout/stderr
// by tokio, so we can use stdin (fd 0) for TIOCSCTTY.
if use_pty {
let ret = libc::ioctl(0, libc::TIOCSCTTY as libc::c_ulong, 0);
if ret < 0 {
// Non-fatal: the process can still run without
// a controlling terminal.
#[cfg(target_os = "linux")]
eprintln!(
"pitchfork: TIOCSCTTY failed: {}",
std::io::Error::last_os_error()
);
}
}
apply_run_identity(&run_identity)?;
Ok(())
});
}
}
let mut child = cmd.spawn().into_diagnostic()?;
let pid = match child.id() {
Some(p) => p,
None => {
warn!("Daemon {id} exited before PID could be captured");
return Ok(IpcResponse::DaemonFailed {
error: "Process exited immediately".to_string(),
});
}
};
info!("started daemon {id} with pid {pid}");
PROCS.refresh_pids(&[pid]);
let daemon = self
.upsert_daemon(
UpsertDaemonOpts::builder(id.clone())
.set(|o| {
o.pid = Some(pid);
o.status = DaemonStatus::Running;
o.shell_pid = opts.shell_pid;
o.dir = Some(opts.dir.0.clone());
o.cmd = Some(original_cmd);
o.autostop = opts.autostop;
o.cron_schedule = opts.cron_schedule.clone();
o.cron_retrigger = opts.cron_retrigger;
o.retry = Some(opts.retry);
o.retry_count = Some(opts.retry_count);
o.ready_delay = opts.ready_delay;
o.ready_output = opts.ready_output.clone();
o.ready_http = opts.ready_http.clone();
o.ready_port = effective_ready_port;
o.ready_cmd = opts.ready_cmd.clone();
o.port = crate::config_types::PortConfig::from_parts(
expected_ports,
opts.port.as_ref().map(|p| p.bump).unwrap_or_default(),
);
o.resolved_port = resolved_ports;
o.depends = Some(opts.depends.clone());
o.env = opts.env.clone();
o.watch = Some(opts.watch.clone());
o.watch_mode = Some(opts.watch_mode);
o.watch_base_dir = opts.watch_base_dir.clone();
o.mise = opts.mise;
o.user = opts.user.clone();
o.memory_limit = opts.memory_limit;
o.cpu_limit = opts.cpu_limit;
o.stop_signal = opts.stop_signal;
o.pty = opts.pty;
})
.build(),
)
.await?;
let id_clone = id.clone();
let ready_delay = opts.ready_delay;
let ready_output = opts.ready_output.clone();
let ready_http = opts.ready_http.clone();
let ready_port = effective_ready_port;
let ready_cmd = opts.ready_cmd.clone();
let daemon_dir = opts.dir.0.clone();
let hook_retry_count = opts.retry_count;
let hook_retry = opts.retry;
let hook_daemon_env = opts.env.clone();
let on_output_hook = opts.on_output_hook.clone();
// Whether this daemon has any port-related config — used to skip the
// active_port detection task for daemons that never bind a port (e.g. `sleep 60`).
// When the proxy is enabled, only detect active_port for daemons that are
// actually referenced by a registered slug, rather than blanket-polling every
// daemon (which wastes ~7.5 s of listeners::get_all() calls per port-less daemon).
let has_port_config = opts.port.as_ref().is_some_and(|p| !p.expect.is_empty())
|| (settings().proxy.enable && is_daemon_slug_target(id));
let daemon_pid = pid;
// Prepare output readers before spawning the monitoring task.
// In PTY mode, we read from the PTY master FD.
// In pipe mode, we read from separate stdout/stderr pipes.
#[cfg(unix)]
let pty_reader = pty_pair.map(|p| {
tokio::io::BufReader::new(tokio::fs::File::from_std(std::fs::File::from(p.master)))
.lines()
});
#[cfg(not(unix))]
let pty_reader: Option<tokio::io::Lines<tokio::io::BufReader<tokio::fs::File>>> = None;
let stdout_reader = if pty_reader.is_none() {
child
.stdout
.take()
.map(|s| tokio::io::BufReader::new(s).lines())
} else {
None
};
let stderr_reader = if pty_reader.is_none() {
child
.stderr
.take()
.map(|s| tokio::io::BufReader::new(s).lines())
} else {
None
};
if pty_reader.is_none() && (stdout_reader.is_none() || stderr_reader.is_none()) {
error!("Failed to capture stdout/stderr for daemon {id}");
}
tokio::spawn(async move {
let id = id_clone;
// Merge all output sources (PTY master OR stdout+stderr) into a single channel.
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel::<String>(256);
if let Some(mut reader) = pty_reader {
// PTY mode: single merged stream from the master.
// output_tx is moved into the spawn; when the reader ends the
// channel closes automatically.
tokio::spawn(async move {
while let Ok(Some(mut line)) = reader.next_line().await {
// PTY slave uses ONLCR: \n → \r\n; strip the trailing \r.
if line.ends_with('\r') {
line.pop();
}
if output_tx.send(line).await.is_err() {
break;
}
}
});
} else {
// Pipe mode: stdout and stderr are merged into the same channel.
// Both `ready_output` and `on_output_hook` patterns match against
// lines from either stream, which is the expected behavior (a
// "server ready" message may appear on stderr in some tools).
if let Some(mut stdout) = stdout_reader {
let tx = output_tx.clone();
tokio::spawn(async move {
while let Ok(Some(line)) = stdout.next_line().await {
if tx.send(line).await.is_err() {
break;
}
}
});
}
if let Some(mut stderr) = stderr_reader {
let tx = output_tx.clone();
tokio::spawn(async move {
while let Ok(Some(line)) = stderr.next_line().await {
if tx.send(line).await.is_err() {
break;
}
}
});
}
// Drop the last sender so the channel closes when all readers finish.
drop(output_tx);
}
let log_file = match tokio::fs::File::options()
.append(true)
.create(true)
.open(&log_path)
.await
{
Ok(f) => f,
Err(e) => {
error!("Failed to open log file for daemon {id}: {e}");
return;
}
};
let mut log_appender = BufWriter::new(log_file);
let now = || chrono::Local::now().format("%Y-%m-%d %H:%M:%S");
let format_line = |line: String| {
let line_for_log = line;
if line_for_log.starts_with(&format!("{id} ")) {
// mise tasks often already have the id printed
format!("{} {line_for_log}\n", now())
} else {
format!("{} {id} {line_for_log}\n", now())
}
};
// Setup readiness checking
let mut ready_notified = false;
let mut ready_tx = ready_tx;
let ready_pattern = ready_output.as_ref().and_then(|p| get_or_compile_regex(p));
// Track whether we've already spawned the active_port detection task
let mut active_port_spawned = false;
// Validate on_output config early; discard the hook on any error so
// a bad regex does not silently fall through to the (None, None) => true
// match arm and fire on every line.
let on_output_hook = match on_output_hook {
Some(ref hook) => match hook.validate(id.name()) {
Ok(()) => on_output_hook,
Err(e) => {
error!("{e}");
None
}
},
None => None,
};
// Compile the regex pattern after validation so we only attempt this
// when the hook is known-good (validate() already checked the syntax).
let on_output_pattern: Option<regex::Regex> = on_output_hook
.as_ref()
.and_then(|h| h.regex.as_deref().and_then(get_or_compile_regex));
let on_output_debounce = on_output_hook
.as_ref()
.map(|h| h.debounce_duration())
.unwrap_or(Duration::from_millis(1000));
// Last time the on_output hook fired; None means it has never fired.
let mut on_output_last_fired: Option<std::time::Instant> = None;
let mut delay_timer =
ready_delay.map(|secs| Box::pin(time::sleep(Duration::from_secs(secs))));
// Get settings for intervals
let s = settings();
let ready_check_interval = s.supervisor_ready_check_interval();
let http_client_timeout = s.supervisor_http_client_timeout();
let log_flush_interval_duration = s.supervisor_log_flush_interval();
// Setup HTTP readiness check interval
let mut http_check_interval = ready_http
.as_ref()
.map(|_| tokio::time::interval(ready_check_interval));
let http_client = ready_http.as_ref().map(|_| {
reqwest::Client::builder()
.timeout(http_client_timeout)
.build()
.unwrap_or_default()
});
// Setup TCP port readiness check interval
let mut port_check_interval =
ready_port.map(|_| tokio::time::interval(ready_check_interval));
// Setup command readiness check interval
let mut cmd_check_interval = ready_cmd
.as_ref()
.map(|_| tokio::time::interval(ready_check_interval));
// Setup periodic log flush interval
let mut log_flush_interval = tokio::time::interval(log_flush_interval_duration);
// Use a channel to communicate process exit status
let (exit_tx, mut exit_rx) =
tokio::sync::mpsc::channel::<std::io::Result<std::process::ExitStatus>>(1);
// Spawn a task to wait for process exit
let child_pid = child.id().unwrap_or(0);
tokio::spawn(async move {
let result = child.wait().await;
// On non-Linux Unix (e.g. macOS) the zombie reaper may win the
// race and consume the exit status via waitpid(None, WNOHANG)
// before Tokio's child.wait() gets to it. When that happens,
// Tokio returns an ECHILD io::Error. We recover by checking
// REAPED_STATUSES for the stashed exit code.
//
// On Linux this is unnecessary because the reaper uses
// waitid(WNOWAIT) to peek before reaping, which avoids the
// race entirely.
#[cfg(all(unix, not(target_os = "linux")))]
let result = match &result {
Err(e) if e.raw_os_error() == Some(nix::libc::ECHILD) => {
if let Some(code) = super::REAPED_STATUSES.lock().await.remove(&child_pid) {
warn!(
"daemon pid {child_pid} wait() got ECHILD; \
recovered exit code {code} from zombie reaper"
);
// Synthesize an ExitStatus from the stashed code.
// On Unix we can use `ExitStatus::from_raw()` with
// a wait-style status word (code << 8 for normal
// exit, or raw signal number for signal death).
use std::os::unix::process::ExitStatusExt;
if code >= 0 {
Ok(std::process::ExitStatus::from_raw(code << 8))
} else {
// Negative code means killed by signal (-sig)
Ok(std::process::ExitStatus::from_raw((-code) & 0x7f))
}
} else {
warn!(
"daemon pid {child_pid} wait() got ECHILD but no \
stashed status found; reporting as error"
);
result
}
}
_ => result,
};
debug!("daemon pid {child_pid} wait() completed with result: {result:?}");
let _ = exit_tx.send(result).await;
});
#[allow(unused_assignments)]
// Initial None is a safety net; loop only exits via exit_rx.recv() which sets it
let mut exit_status = None;
// If there is no ready check of any kind and no delay, the daemon is
// considered immediately ready and the active_port detection task would
// never be triggered inside the select loop. Kick it off right away so
// that daemons without any readiness configuration still get their
// active_port populated (needed for proxy routing).
if has_port_config
&& ready_pattern.is_none()
&& ready_http.is_none()
&& ready_port.is_none()
&& ready_cmd.is_none()
&& delay_timer.is_none()
{
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
loop {
select! {
Some(line) = output_rx.recv() => {
let formatted = format_line(line.clone());
if let Err(e) = log_appender.write_all(formatted.as_bytes()).await {
error!("Failed to write to log for daemon {id}: {e}");
}
trace!("output: {id} {formatted}");
// Strip ANSI for pattern matching so user-written patterns
// work regardless of whether the process emits color codes.
let line_clean = console::strip_ansi_codes(&line).to_string();
// Check if output matches ready pattern
if !ready_notified
&& let Some(ref pattern) = ready_pattern
&& pattern.is_match(&line_clean)
{
info!("daemon {id} ready: output matched pattern");
ready_notified = true;
let _ = log_appender.flush().await;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Ok(()));
}
fire_hook(HookType::OnReady, id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), vec![]).await;
if !active_port_spawned && has_port_config {
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
}
// Check on_output hook
if let Some(ref hook) = on_output_hook {
let matched = match (&hook.filter, &on_output_pattern) {
(Some(substr), _) => line_clean.contains(substr.as_str()),
(None, Some(re)) => re.is_match(&line_clean),
(None, None) => true,
};
if matched {
let now = std::time::Instant::now();
let elapsed = on_output_last_fired.map(|t| now.duration_since(t));
if elapsed.is_none_or(|e| e >= on_output_debounce) {
on_output_last_fired = Some(now);
hooks::fire_output_hook(id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), hook.run.clone(), line_clean.clone()).await;
}
}
}
}
Some(result) = exit_rx.recv() => {
// Process exited - save exit status and notify if not ready yet
exit_status = Some(result);
debug!("daemon {id} process exited, exit_status: {exit_status:?}");
// Flush logs before notifying so clients see logs immediately
let _ = log_appender.flush().await;
if !ready_notified {
if let Some(tx) = ready_tx.take() {
// Check if process exited successfully
let is_success = exit_status.as_ref()
.and_then(|r| r.as_ref().ok())
.map(|s| s.success())
.unwrap_or(false);
if is_success {
debug!("daemon {id} exited successfully before ready check, sending success notification");
let _ = tx.send(Ok(()));
} else {
let exit_code = exit_status.as_ref()
.and_then(|r| r.as_ref().ok())
.and_then(|s| s.code());
debug!("daemon {id} exited with failure before ready check, sending failure notification with exit_code: {exit_code:?}");
let _ = tx.send(Err(exit_code));
}
}
} else {
debug!("daemon {id} was already marked ready, not sending notification");
}
break;
},
_ = async {
if let Some(ref mut interval) = http_check_interval {
interval.tick().await;
} else {
std::future::pending::<()>().await;
}
}, if !ready_notified && ready_http.is_some() => {
if let (Some(url), Some(client)) = (&ready_http, &http_client) {
match client.get(url).send().await {
Ok(response) if response.status().is_success() => {
info!("daemon {id} ready: HTTP check passed (status {})", response.status());
ready_notified = true;
let _ = log_appender.flush().await;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Ok(()));
}
fire_hook(HookType::OnReady, id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), vec![]).await;
http_check_interval = None;
if !active_port_spawned && has_port_config {
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
}
Ok(response) => {
trace!("daemon {id} HTTP check: status {} (not ready)", response.status());
}
Err(e) => {
trace!("daemon {id} HTTP check failed: {e}");
}
}
}
}
_ = async {
if let Some(ref mut interval) = port_check_interval {
interval.tick().await;
} else {
std::future::pending::<()>().await;
}
}, if !ready_notified && ready_port.is_some() => {
if let Some(port) = ready_port {
match tokio::net::TcpStream::connect(("127.0.0.1", port)).await {
Ok(_) => {
info!("daemon {id} ready: TCP port {port} is listening");
ready_notified = true;
// Flush logs before notifying so clients see logs immediately
let _ = log_appender.flush().await;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Ok(()));
}
fire_hook(HookType::OnReady, id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), vec![]).await;
// Stop checking once ready
port_check_interval = None;
if !active_port_spawned && has_port_config {
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
}
Err(_) => {
trace!("daemon {id} port check: port {port} not listening yet");
}
}
}
}
_ = async {
if let Some(ref mut interval) = cmd_check_interval {
interval.tick().await;
} else {
std::future::pending::<()>().await;
}
}, if !ready_notified && ready_cmd.is_some() => {
if let Some(ref cmd) = ready_cmd {
// Run the readiness check command using the shell abstraction
let mut command = Shell::default_for_platform().command(cmd);
command
.current_dir(&daemon_dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
let result: std::io::Result<std::process::ExitStatus> = command.status().await;
match result {
Ok(status) if status.success() => {
info!("daemon {id} ready: readiness command succeeded");
ready_notified = true;
let _ = log_appender.flush().await;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Ok(()));
}
fire_hook(HookType::OnReady, id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), vec![]).await;
// Stop checking once ready
cmd_check_interval = None;
if !active_port_spawned && has_port_config {
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
}
Ok(_) => {
trace!("daemon {id} cmd check: command returned non-zero (not ready)");
}
Err(e) => {
trace!("daemon {id} cmd check failed: {e}");
}
}
}
}
_ = async {
if let Some(ref mut timer) = delay_timer {
timer.await;
} else {
std::future::pending::<()>().await;
}
} => {
if !ready_notified && ready_pattern.is_none() && ready_http.is_none() && ready_port.is_none() && ready_cmd.is_none() {
info!("daemon {id} ready: delay elapsed");
ready_notified = true;
// Flush logs before notifying so clients see logs immediately
let _ = log_appender.flush().await;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Ok(()));
}
fire_hook(HookType::OnReady, id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), vec![]).await;
}
// Disable timer after it fires
delay_timer = None;
if !active_port_spawned && has_port_config {
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
}
_ = log_flush_interval.tick() => {
// Periodic flush to ensure logs are written to disk
if let Err(e) = log_appender.flush().await {
error!("Failed to flush log for daemon {id}: {e}");
}
}
}
}
// Final flush to ensure all buffered logs are written
if let Err(e) = log_appender.flush().await {
error!("Failed to final flush log for daemon {id}: {e}");
}
// Clear active_port since the process is no longer running
{
let mut state_file = SUPERVISOR.state_file.lock().await;
if let Some(d) = state_file.daemons.get_mut(&id) {
d.active_port = None;
}
if let Err(e) = state_file.write() {
debug!("Failed to write state after clearing active_port for {id}: {e}");
}
}
// Get the final exit status
let exit_status = if let Some(status) = exit_status {
status
} else {
// Streams closed but process hasn't exited yet, wait for it
match exit_rx.recv().await {
Some(status) => status,
None => {
warn!("daemon {id} exit channel closed without receiving status");
Err(std::io::Error::other("exit channel closed"))
}
}
};
let current_daemon = SUPERVISOR.get_daemon(&id).await;
// Signal that this monitoring task is processing its exit path.
// The RAII guard will decrement the counter and notify close()
// when the task finishes (including all fire_hook registrations),
// regardless of which return path is taken.
SUPERVISOR
.active_monitors
.fetch_add(1, atomic::Ordering::Release);
struct MonitorGuard;
impl Drop for MonitorGuard {
fn drop(&mut self) {
SUPERVISOR
.active_monitors
.fetch_sub(1, atomic::Ordering::Release);
SUPERVISOR.monitor_done.notify_waiters();
}
}
let _monitor_guard = MonitorGuard;
// Check if this monitoring task is for the current daemon process.
// Allow Stopped/Stopping daemons through: stop() clears pid atomically,
// so d.pid != Some(pid) would be true, but we still need the is_stopped()
// branch below to fire on_stop/on_exit hooks.
if current_daemon.is_none()
|| current_daemon.as_ref().is_some_and(|d| {
d.pid != Some(pid) && !d.status.is_stopped() && !d.status.is_stopping()
})
{
// Another process has taken over, don't update status
return;
}
// Capture the intentional-stop flag BEFORE any state changes.
// stop() transitions Stopping → Stopped and clears pid. If stop() wins the race
// and sets Stopped before this task runs, we still need to fire on_stop/on_exit.
// Treat both Stopping and Stopped as "intentional stop by pitchfork".
let already_stopped = current_daemon
.as_ref()
.is_some_and(|d| d.status.is_stopped());
let is_stopping = already_stopped
|| current_daemon
.as_ref()
.is_some_and(|d| d.status.is_stopping());