1use std::io::{self, IoSlice};
18use std::mem::MaybeUninit;
19use std::os::fd::{AsFd, OwnedFd};
20use std::sync::Arc;
21use std::time::{Duration, Instant};
22
23use prometheus_client::metrics::counter::Counter;
24use prometheus_client::metrics::family::Family;
25use prometheus_client::metrics::gauge::Gauge;
26use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags};
27use rustix::process::{Pid, kill_process_group};
28use schedr_model::runner::{
29 AgentMessage, ForkRequest, ForkServerRequest, MAX_MESSAGE_SIZE, RunnerMessage, RunnerMode,
30};
31use schedr_proto::pb;
32use tokio::io::AsyncWriteExt;
33use tokio::net::UnixStream;
34use tokio::net::unix::pipe;
35use tokio::sync::{Mutex, watch};
36use tokio::task::JoinHandle;
37
38use crate::attempt::WorkerSetup;
39use crate::channel::{ChannelError, Messages, read_message};
40use crate::launch::{LaunchError, start_runner};
41use crate::metrics::{ForkFallbackLabels, ForkServerLabels};
42use crate::output::TailBuffer;
43use crate::process::{OsProcess, ProcessSpec, collect, open_log};
44use crate::status::Termination;
45use crate::supervise::{Process, Signal};
46use crate::usage::Ended;
47
48#[cfg(test)]
49mod tests;
50
51pub const PRELOAD_TIMEOUT: Duration = Duration::from_secs(300);
53
54pub const FORK_ANSWER_TIMEOUT: Duration = Duration::from_secs(30);
56
57pub const BACKOFF_FIRST: Duration = Duration::from_secs(1);
59
60pub const BACKOFF_MAX: Duration = Duration::from_secs(300);
62
63pub const BACKOFF_RESET_AFTER: Duration = Duration::from_secs(600);
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Cause {
70 Import,
73 Lasting,
76}
77
78#[must_use]
83pub fn retried(cause: Cause, failing_for: Duration, window: Duration) -> bool {
84 cause == Cause::Import && failing_for < window
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct ForkBackoff {
90 pub first: Duration,
92 pub max: Duration,
94 pub reset_after: Duration,
96}
97
98impl Default for ForkBackoff {
99 fn default() -> Self {
101 Self {
102 first: BACKOFF_FIRST,
103 max: BACKOFF_MAX,
104 reset_after: BACKOFF_RESET_AFTER,
105 }
106 }
107}
108
109impl ForkBackoff {
110 #[must_use]
113 pub fn next(&self, previous: Duration, up_for: Option<Duration>) -> Duration {
114 if up_for.is_some_and(|up| up >= self.reset_after) {
115 self.first
116 } else {
117 (previous * 2).min(self.max)
118 }
119 }
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum Kind {
125 Preloaded,
127 Bare,
129}
130
131impl Kind {
132 #[must_use]
134 pub const fn label(self) -> &'static str {
135 match self {
136 Self::Preloaded => "preloaded",
137 Self::Bare => "bare",
138 }
139 }
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum Fallback {
145 Disabled,
147 Down,
149 ForkFailed,
151 ShimDied,
153}
154
155impl Fallback {
156 #[must_use]
158 pub const fn label(self) -> &'static str {
159 match self {
160 Self::Disabled => "disabled",
161 Self::Down => "down",
162 Self::ForkFailed => "fork_failed",
163 Self::ShimDied => "shim_died",
164 }
165 }
166}
167
168#[derive(Debug, Clone, Default)]
170pub struct ForkMetrics {
171 pub servers: Family<ForkServerLabels, Gauge>,
173 pub fallbacks: Family<ForkFallbackLabels, Counter>,
175}
176
177#[derive(Debug)]
179enum State {
180 Down,
182 Up {
186 control: UnixStream,
187 next_id: u64,
188 asking: bool,
189 },
190 Disabled(String),
192}
193
194impl State {
195 const fn label(&self) -> &'static str {
196 match self {
197 Self::Down => "down",
198 Self::Up { .. } => "up",
199 Self::Disabled(_) => "disabled",
200 }
201 }
202}
203
204#[derive(Debug)]
206struct Server {
207 kind: Kind,
208 interpreter: String,
209 group: std::sync::atomic::AtomicI32,
212 state: Mutex<State>,
213 metrics: ForkMetrics,
214 board: Arc<WarningBoard>,
215}
216
217#[derive(Debug)]
219struct WarningBoard {
220 interpreter: String,
221 bare_alone: bool,
223 reasons: std::sync::Mutex<std::collections::BTreeMap<&'static str, String>>,
225 warnings: watch::Sender<Vec<pb::WorkerWarning>>,
226}
227
228impl WarningBoard {
229 fn record(&self, kind: Kind, disabled: Option<&str>) {
231 let mut reasons = self
232 .reasons
233 .lock()
234 .unwrap_or_else(std::sync::PoisonError::into_inner);
235 let changed = match disabled {
236 Some(reason) => {
237 reasons.insert(kind.label(), reason.to_owned()).as_deref() != Some(reason)
238 }
239 None => reasons.remove(kind.label()).is_some(),
240 };
241 if changed {
242 let warnings = reasons
243 .iter()
244 .rev()
245 .map(|(label, reason)| self.warning(label, reason, &reasons))
246 .collect();
247 self.warnings.send_replace(warnings);
248 }
249 }
250
251 fn warning(
254 &self,
255 label: &str,
256 reason: &str,
257 disabled: &std::collections::BTreeMap<&'static str, String>,
258 ) -> pb::WorkerWarning {
259 let other = if label == "preloaded" {
260 "bare"
261 } else {
262 "preloaded"
263 };
264 let then = if self.bare_alone || disabled.contains_key(other) {
265 "tasks are spawned"
266 } else if label == "preloaded" {
267 "tasks are forked by the bare fork server, or spawned"
268 } else {
269 "tasks the preloaded fork server can't fork are spawned"
270 };
271 pb::WorkerWarning {
272 kind: FORK_SERVER_DISABLED.to_owned(),
273 interpreter: self.interpreter.clone(),
274 message: format!("the {label} fork server is disabled: {reason}; {then}"),
275 }
276 }
277}
278
279pub const FORK_SERVER_DISABLED: &str = "fork_server_disabled";
281
282impl Server {
283 fn set(&self, current: &mut State, state: State) {
285 for label in ["down", "up", "disabled"] {
286 let value = i64::from(label == state.label());
287 self.metrics
288 .servers
289 .get_or_create(&ForkServerLabels {
290 interpreter: self.interpreter.clone(),
291 kind: self.kind.label().to_owned(),
292 state: label.to_owned(),
293 })
294 .set(value);
295 }
296 let disabled = match &state {
297 State::Disabled(reason) => Some(reason.as_str()),
298 _ => None,
299 };
300 self.board.record(self.kind, disabled);
301 *current = state;
302 }
303}
304
305#[derive(Debug, Clone)]
307pub struct ForkServers {
308 servers: Arc<Vec<Server>>,
309 memory: Arc<std::sync::atomic::AtomicU64>,
311 warnings: watch::Receiver<Vec<pb::WorkerWarning>>,
312 answer_timeout: Duration,
314}
315
316#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct ForkConfig {
319 pub interpreter: String,
321 pub preload: Vec<String>,
323 pub import_retry: Duration,
325}
326
327#[derive(Debug, Clone)]
329pub struct ForkSetup {
330 pub interpreter: String,
332 pub process: ProcessSpec,
336 pub preload: Vec<String>,
338 pub import_retry: Duration,
340 pub timeouts: crate::attempt::WorkerTimeouts,
342 pub memory_interval: Duration,
344}
345
346impl ForkServers {
347 #[must_use]
351 pub fn for_worker(setup: &WorkerSetup, metrics: &ForkMetrics) -> Option<Self> {
352 let config = setup.fork_server.as_ref()?;
353 if !cfg!(target_os = "linux") {
354 tracing::warn!(
355 interpreter = config.interpreter,
356 "fork_server = true is ignored: fork servers run on Linux only; tasks are spawned"
357 );
358 return None;
359 }
360 let process = ProcessSpec {
361 program: setup.python.clone(),
362 args: vec![
363 "-P".to_owned(),
365 "-m".to_owned(),
366 "schedr.runner".to_owned(),
367 "fork_server".to_owned(),
368 ],
369 env: setup
371 .agent_env
372 .iter()
373 .filter(|(name, _)| crate::env::is_allowed(name) || setup.pass_env.contains(name))
374 .map(|(k, v)| (k.clone(), v.clone()))
375 .collect(),
376 working_dir: setup.log_dir.clone(),
377 log_file: setup.log_dir.join("fork-server.log"),
378 max_output_size: 64 * 1024,
379 mask: crate::mask::Mask::default(),
380 start_timeout: setup.timeouts.runner_start,
381 output_drain: setup.timeouts.output_drain,
382 };
383 let setup = ForkSetup {
384 interpreter: config.interpreter.clone(),
385 process,
386 preload: config.preload.clone(),
387 import_retry: config.import_retry,
388 memory_interval: setup.memory.interval,
389 timeouts: setup.timeouts,
390 };
391 Some(Self::start(&setup, metrics))
392 }
393
394 #[must_use]
397 pub fn start(setup: &ForkSetup, metrics: &ForkMetrics) -> Self {
398 let mut kinds = vec![
399 (Kind::Preloaded, setup.preload.clone()),
400 (Kind::Bare, vec![]),
401 ];
402 if setup.preload.is_empty() {
403 kinds.remove(0);
404 }
405 let (warnings, watching) = watch::channel(Vec::new());
406 let board = Arc::new(WarningBoard {
407 interpreter: setup.interpreter.clone(),
408 bare_alone: kinds.len() == 1,
409 reasons: std::sync::Mutex::default(),
410 warnings,
411 });
412 let servers: Vec<Server> = kinds
413 .iter()
414 .map(|(kind, _)| Server {
415 kind: *kind,
416 interpreter: setup.interpreter.clone(),
417 group: std::sync::atomic::AtomicI32::new(0),
418 state: Mutex::new(State::Down),
419 metrics: metrics.clone(),
420 board: Arc::clone(&board),
421 })
422 .collect();
423 for server in &servers {
424 server.set(&mut State::Down, State::Down);
426 }
427 let servers = Arc::new(servers);
428 for (index, (kind, preload)) in kinds.into_iter().enumerate() {
429 let mut process = setup.process.clone();
430 process.log_file = process
431 .log_file
432 .with_file_name(format!("fork-server-{}.log", kind.label()));
433 let timeouts = setup.timeouts;
434 let retry = setup.import_retry;
435 tokio::spawn(keep_up(
436 Arc::downgrade(&servers),
437 index,
438 process,
439 preload,
440 retry,
441 timeouts.fork_backoff,
442 timeouts.fork_preload,
443 ));
444 }
445 let memory = Arc::default();
446 tokio::spawn(measure(
447 Arc::downgrade(&servers),
448 Arc::clone(&memory),
449 setup.memory_interval,
450 ));
451 Self {
452 servers,
453 memory,
454 warnings: watching,
455 answer_timeout: setup.timeouts.fork_answer,
456 }
457 }
458
459 #[must_use]
461 pub fn memory(&self) -> u64 {
462 self.memory.load(std::sync::atomic::Ordering::Relaxed)
463 }
464
465 pub async fn settled(&self, within: Duration) -> Vec<String> {
469 let mut warnings = self.warnings();
470 let _ = tokio::time::timeout(within, async {
471 loop {
472 if !warnings.borrow_and_update().is_empty() || self.all_settled().await {
473 return;
474 }
475 let _ = tokio::time::timeout(Duration::from_millis(20), warnings.changed()).await;
476 }
477 })
478 .await;
479 warnings
480 .borrow()
481 .iter()
482 .map(|warning| warning.message.clone())
483 .collect()
484 }
485
486 async fn all_settled(&self) -> bool {
487 for server in self.servers.iter() {
488 if matches!(*server.state.lock().await, State::Down) {
489 return false;
490 }
491 }
492 true
493 }
494
495 #[must_use]
498 pub fn warnings(&self) -> watch::Receiver<Vec<pb::WorkerWarning>> {
499 self.warnings.clone()
500 }
501
502 pub async fn disabled(&self) -> Vec<(Kind, String)> {
504 let mut found = Vec::new();
505 for server in self.servers.iter() {
506 if let State::Disabled(reason) = &*server.state.lock().await {
507 found.push((server.kind, reason.clone()));
508 }
509 }
510 found
511 }
512
513 pub async fn fork(
521 &self,
522 spec: &ProcessSpec,
523 mode: RunnerMode,
524 preload: bool,
525 ) -> Result<Forked, Fallback> {
526 let mut last = Fallback::Down;
527 let tried = self
528 .servers
529 .iter()
530 .filter(|server| preload || server.kind == Kind::Bare);
531 for server in tried {
532 match fork_on(server, spec, mode, self.answer_timeout).await {
533 Ok(forked) => return Ok(forked),
534 Err(fallback) => {
535 server
536 .metrics
537 .fallbacks
538 .get_or_create(&ForkFallbackLabels {
539 interpreter: server.interpreter.clone(),
540 reason: fallback.label().to_owned(),
541 })
542 .inc();
543 last = fallback;
544 }
545 }
546 }
547 Err(last)
548 }
549}
550
551async fn measure(
555 servers: std::sync::Weak<Vec<Server>>,
556 memory: Arc<std::sync::atomic::AtomicU64>,
557 every: Duration,
558) {
559 let mut tick = tokio::time::interval(every);
560 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
561 loop {
562 tick.tick().await;
563 let Some(all) = servers.upgrade() else {
564 return;
565 };
566 let groups: Vec<i32> = all
567 .iter()
568 .map(|server| server.group.load(std::sync::atomic::Ordering::Relaxed))
569 .filter(|group| *group > 0)
570 .collect();
571 drop(all);
572 let measured = tokio::task::spawn_blocking(move || {
573 servers_memory(std::path::Path::new("/proc"), &groups)
574 })
575 .await
576 .ok()
577 .flatten();
578 if let Some(total) = measured {
579 memory.store(total, std::sync::atomic::Ordering::Relaxed);
580 }
581 }
582}
583
584#[must_use]
586pub fn servers_memory(proc_root: &std::path::Path, groups: &[i32]) -> Option<u64> {
587 groups
588 .iter()
589 .map(|group| crate::memory::group_memory(proc_root, *group, false))
590 .sum()
591}
592
593async fn keep_up(
597 servers: std::sync::Weak<Vec<Server>>,
598 index: usize,
599 process: ProcessSpec,
600 preload: Vec<String>,
601 import_retry: Duration,
602 spacing: ForkBackoff,
603 preload_timeout: Duration,
604) {
605 let mut backoff = spacing.first / 2;
606 let mut failing: Option<(Instant, String)> = None;
608 loop {
609 let up_for = match start_server(&process, &preload, preload_timeout).await {
610 Ok(Started::Ready(mut os, control)) => {
611 {
612 let Some(all) = servers.upgrade() else {
613 return;
614 };
615 let server = &all[index];
616 server
617 .group
618 .store(os.id(), std::sync::atomic::Ordering::Relaxed);
619 let mut state = server.state.lock().await;
620 server.set(
621 &mut state,
622 State::Up {
623 control,
624 next_id: 1,
625 asking: false,
626 },
627 );
628 tracing::info!(kind = server.kind.label(), "fork server up");
629 }
630 failing = None;
631 let up_at = Instant::now();
632 let ended = os.wait().await;
633 let Some(all) = servers.upgrade() else {
634 return;
635 };
636 let server = &all[index];
637 server.group.store(0, std::sync::atomic::Ordering::Relaxed);
638 let mut state = server.state.lock().await;
639 if matches!(*state, State::Disabled(_)) {
640 return;
641 }
642 tracing::warn!(kind = server.kind.label(), ?ended, "fork server ended");
643 server.set(&mut state, State::Down);
644 Some(up_at.elapsed())
645 }
646 Ok(Started::Disabled(reason, cause)) => {
647 let Some(all) = servers.upgrade() else {
648 return;
649 };
650 let server = &all[index];
651 let kind = server.kind.label();
652 let since = failing
653 .as_ref()
654 .map_or_else(Instant::now, |(since, _)| *since);
655 let again = retried(cause, since.elapsed(), import_retry);
656 if !again {
657 let gave_up = (cause == Cause::Import).then(|| since.elapsed().as_secs() / 60);
658 tracing::warn!(kind, reason, ?gave_up, "fork server disabled until restart");
659 } else if failing.as_ref().is_none_or(|(_, said)| *said != reason) {
660 tracing::warn!(kind, reason, "fork server disabled; retrying");
661 }
662 let mut state = server.state.lock().await;
663 server.set(&mut state, State::Disabled(reason.clone()));
664 if !again {
665 return;
666 }
667 failing = Some((since, reason));
668 None
669 }
670 Err(error) => {
671 let Some(all) = servers.upgrade() else {
672 return;
673 };
674 let server = &all[index];
675 tracing::warn!(kind = server.kind.label(), %error, "can't start the fork server");
676 let mut state = server.state.lock().await;
677 server.set(&mut state, State::Down);
678 None
679 }
680 };
681 backoff = spacing.next(backoff, up_for);
682 tokio::time::sleep(backoff).await;
683 if servers.strong_count() == 0 {
685 return;
686 }
687 }
688}
689
690enum Started {
692 Ready(Box<OsProcess>, UnixStream),
694 Disabled(String, Cause),
696}
697
698async fn start_server(
700 process: &ProcessSpec,
701 preload: &[String],
702 preload_timeout: Duration,
703) -> Result<Started, LaunchError> {
704 for dir in [
707 Some(process.working_dir.as_path()),
708 process.log_file.parent(),
709 ]
710 .into_iter()
711 .flatten()
712 {
713 tokio::fs::create_dir_all(dir)
714 .await
715 .map_err(|source| LaunchError::Start {
716 what: format!("the fork server's directory {}", dir.display()),
717 source,
718 })?;
719 }
720 let runner = match start_runner(process, RunnerMode::ForkServer, |_| {}).await {
721 Ok(runner) => runner,
722 Err(LaunchError::Channel(ChannelError::Refused(reason))) => {
723 return Ok(Started::Disabled(reason, Cause::Lasting));
724 }
725 Err(error) => return Err(error),
726 };
727 let (os, mut control) = (runner.process, runner.stream);
728 let request = AgentMessage::ForkServer(ForkServerRequest {
729 preload: preload.to_vec(),
730 });
731 crate::channel::write_message(&mut control, &request).await?;
732 let answer = tokio::time::timeout(preload_timeout, read_message(&mut control)).await;
733 match answer {
734 Ok(Ok(RunnerMessage::ForkServerReady)) => Ok(Started::Ready(Box::new(os), control)),
735 Ok(Ok(RunnerMessage::ForkServerDisabled { reason, threads })) => {
736 let cause = if threads.is_empty() {
737 Cause::Import
738 } else {
739 Cause::Lasting
740 };
741 Ok(Started::Disabled(reason, cause))
742 }
743 Ok(Ok(other)) => Err(ChannelError::Unexpected {
744 expected: "fork_server_ready",
745 got: format!("{other:?}"),
746 }
747 .into()),
748 Ok(Err(error)) => Err(error.into()),
749 Err(_) => Err(LaunchError::NoHello(preload_timeout)),
750 }
751}
752
753#[derive(Debug)]
755pub struct Forked {
756 pub process: ForkedProcess,
758 pub stream: UnixStream,
760 pub hold: GroupHold,
763}
764
765async fn fork_on(
767 server: &Server,
768 spec: &ProcessSpec,
769 mode: RunnerMode,
770 answer_timeout: Duration,
771) -> Result<Forked, Fallback> {
772 let io = |_| Fallback::ForkFailed;
773 let (ours, theirs) = std::os::unix::net::UnixStream::pair().map_err(io)?;
774 let (status, status_theirs) = std::os::unix::net::UnixStream::pair().map_err(io)?;
775 let (stdout, stdout_theirs) = std::io::pipe().map_err(io)?;
776 let (stderr, stderr_theirs) = std::io::pipe().map_err(io)?;
777 let log = open_log(spec).await.map_err(io)?;
778 {
779 let mut state = server.state.lock().await;
780 let (control, id) = match &mut *state {
781 State::Up { asking: true, .. } => {
782 return Err(out_of_step(
783 server,
784 &mut state,
785 "an earlier answer was abandoned",
786 ));
787 }
788 State::Up {
789 control,
790 next_id,
791 asking,
792 } => {
793 let id = *next_id;
794 *next_id += 1;
795 *asking = true;
796 (control, id)
797 }
798 State::Down => return Err(Fallback::Down),
799 State::Disabled(_) => return Err(Fallback::Disabled),
800 };
801 let request = AgentMessage::Fork(ForkRequest {
802 id,
803 mode,
804 env: spec.env.clone(),
805 cwd: spec.working_dir.to_string_lossy().into_owned(),
806 });
807 let fds = [
808 OwnedFd::from(theirs),
809 OwnedFd::from(stdout_theirs),
810 OwnedFd::from(stderr_theirs),
811 OwnedFd::from(status_theirs),
812 ];
813 if send_with_fds(control, &request, &fds).await.is_err() {
814 return Err(out_of_step(
815 server,
816 &mut state,
817 "the request couldn't be sent",
818 ));
819 }
820 let answer = tokio::time::timeout(answer_timeout, read_message(control)).await;
821 if let State::Up { asking, .. } = &mut *state {
822 *asking = false;
823 }
824 answered(server, &mut state, id, answer)?;
825 drop(fds);
827 }
828 let hold = GroupHold {
829 _open: OwnedFd::from(status.try_clone().map_err(io)?),
830 };
831 let mut status = tokio_stream(status).map_err(io)?;
832 let started = tokio::time::timeout(spec.start_timeout, read_message(&mut status)).await;
833 let Ok(Ok(RunnerMessage::ProcessStarted { pid })) = started else {
834 return Err(Fallback::ShimDied);
835 };
836 let group = Pid::from_raw(pid).ok_or(Fallback::ShimDied)?;
837 let limit = spec.max_output_size;
838 let stdout = pipe::Receiver::from_owned_fd(OwnedFd::from(stdout)).map_err(io)?;
839 let stderr = pipe::Receiver::from_owned_fd(OwnedFd::from(stderr)).map_err(io)?;
840 Ok(Forked {
841 process: ForkedProcess {
842 group,
843 status: Some(status.into()),
844 ended: None,
845 usage: Ended::default(),
846 stdout: Some(tokio::spawn(collect(
847 stdout,
848 Arc::clone(&log),
849 limit,
850 spec.mask.clone(),
851 ))),
852 stderr: Some(tokio::spawn(collect(stderr, log, limit, spec.mask.clone()))),
853 },
854 stream: tokio_stream(ours).map_err(io)?,
855 hold,
856 })
857}
858
859fn tokio_stream(stream: std::os::unix::net::UnixStream) -> io::Result<UnixStream> {
860 stream.set_nonblocking(true)?;
861 UnixStream::from_std(stream)
862}
863
864fn answered(
867 server: &Server,
868 state: &mut State,
869 id: u64,
870 answer: Result<Result<RunnerMessage, ChannelError>, tokio::time::error::Elapsed>,
871) -> Result<(), Fallback> {
872 match answer {
873 Ok(Ok(RunnerMessage::Forked { id: forked })) if forked == id => Ok(()),
874 Ok(Ok(RunnerMessage::ForkFailed { id: failed, reason })) if failed == id => {
875 tracing::warn!(kind = server.kind.label(), reason, "fork failed");
876 Err(Fallback::ForkFailed)
877 }
878 Ok(Ok(RunnerMessage::ForkServerDisabled { reason, .. })) => {
879 tracing::warn!(kind = server.kind.label(), reason, "fork server disabled");
880 server.set(state, State::Disabled(reason));
882 Err(Fallback::Disabled)
883 }
884 Ok(Ok(other)) => {
885 let why = format!("an answer that isn't this request's: {other:?}");
886 Err(out_of_step(server, state, &why))
887 }
888 Ok(Err(error)) => {
889 let why = format!("reading the answer: {error}");
890 Err(out_of_step(server, state, &why))
891 }
892 Err(_) => Err(out_of_step(server, state, "no answer in time")),
893 }
894}
895
896fn out_of_step(server: &Server, state: &mut State, why: &str) -> Fallback {
900 tracing::warn!(
901 kind = server.kind.label(),
902 why,
903 "fork server out of step; restarting it"
904 );
905 server.set(state, State::Down);
906 Fallback::Down
907}
908
909#[cfg(target_os = "linux")]
912const SEND_FLAGS: SendFlags = SendFlags::NOSIGNAL;
913#[cfg(not(target_os = "linux"))]
914const SEND_FLAGS: SendFlags = SendFlags::empty();
915
916async fn send_with_fds(
918 stream: &mut UnixStream,
919 message: &AgentMessage,
920 fds: &[OwnedFd],
921) -> Result<(), ChannelError> {
922 let body = serde_json::to_vec(message)?;
923 let size = u32::try_from(body.len())
924 .ok()
925 .filter(|size| *size <= MAX_MESSAGE_SIZE)
926 .ok_or(ChannelError::TooLarge(body.len() as u64))?;
927 let header = size.to_be_bytes();
928 let borrowed: Vec<_> = fds.iter().map(AsFd::as_fd).collect();
929 let mut sent = 0;
930 while sent == 0 {
931 stream.writable().await?;
932 let result = stream.try_io(tokio::io::Interest::WRITABLE, || {
933 let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(4))];
934 let mut control = SendAncillaryBuffer::new(&mut space);
935 control.push(SendAncillaryMessage::ScmRights(&borrowed));
936 rustix::net::sendmsg(&*stream, &[IoSlice::new(&header)], &mut control, SEND_FLAGS)
937 .map_err(io::Error::from)
938 });
939 match result {
940 Ok(n) => sent = n,
941 Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
942 Err(error) => return Err(error.into()),
943 }
944 }
945 stream.write_all(&header[sent..]).await?;
947 stream.write_all(&body).await?;
948 Ok(())
949}
950
951#[derive(Debug)]
955pub struct GroupHold {
956 _open: OwnedFd,
957}
958
959#[derive(Debug)]
961pub struct ForkedProcess {
962 group: Pid,
963 status: Option<Messages<UnixStream>>,
964 ended: Option<Termination>,
965 usage: Ended,
966 stdout: Option<JoinHandle<io::Result<TailBuffer>>>,
968 stderr: Option<JoinHandle<io::Result<TailBuffer>>>,
969}
970
971impl ForkedProcess {
972 #[must_use]
974 pub fn id(&self) -> i32 {
975 self.group.as_raw_nonzero().get()
976 }
977
978 pub async fn output(mut self) -> io::Result<(TailBuffer, TailBuffer)> {
984 let taken = (self.stdout.take(), self.stderr.take());
985 let (Some(stdout), Some(stderr)) = taken else {
986 return Err(io::Error::other("the output was taken already"));
987 };
988 let stdout = stdout.await.map_err(io::Error::other)??;
989 let stderr = stderr.await.map_err(io::Error::other)??;
990 Ok((stdout, stderr))
991 }
992}
993
994impl Drop for ForkedProcess {
995 fn drop(&mut self) {
999 if self.ended.is_none() {
1000 let _ = kill_process_group(self.group, rustix::process::Signal::KILL);
1001 }
1002 }
1003}
1004
1005impl Process for ForkedProcess {
1006 async fn wait(&mut self) -> io::Result<Termination> {
1007 if let Some(ended) = self.ended {
1008 return Ok(ended);
1009 }
1010 let Some(status) = &mut self.status else {
1011 return Ok(Termination::Unknown);
1012 };
1013 let ended = loop {
1014 match status.next().await {
1016 Ok(RunnerMessage::ProcessExited {
1017 code,
1018 signal,
1019 core_dumped,
1020 usage,
1021 }) => {
1022 self.usage = Ended { usage, core_dumped };
1023 break match (code, signal) {
1024 (Some(code), _) => Termination::Exited(code),
1025 (None, Some(signal)) => Termination::Signaled(signal),
1026 (None, None) => Termination::Unknown,
1027 };
1028 }
1029 Ok(_) => {}
1030 Err(_) => {
1031 let _ = kill_process_group(self.group, rustix::process::Signal::KILL);
1034 break Termination::Unknown;
1035 }
1036 }
1037 };
1038 self.ended = Some(ended);
1039 Ok(ended)
1040 }
1041
1042 fn signal(&mut self, signal: Signal) -> io::Result<()> {
1043 let sig = match signal {
1044 Signal::Term => rustix::process::Signal::TERM,
1045 Signal::Kill => rustix::process::Signal::KILL,
1046 };
1047 match kill_process_group(self.group, sig) {
1048 Ok(()) | Err(rustix::io::Errno::SRCH) => Ok(()),
1049 Err(e) => Err(e.into()),
1050 }
1051 }
1052
1053 fn group_alive(&self) -> bool {
1054 crate::process::group_running(self.group)
1055 }
1056
1057 fn ended(&self) -> Ended {
1058 self.usage
1059 }
1060}