1use super::*;
2
3pub const SUBC_ARG: &str = "--subc";
9
10#[cfg(any(unix, feature = "test-support"))]
13pub(super) const ADMISSION_TIMEOUT: Duration = Duration::from_secs(30);
14
15#[cfg(feature = "test-support")]
17pub const CHILD_ADMISSION_TIMEOUT: Duration = ADMISSION_TIMEOUT;
18
19#[cfg(unix)]
20pub(super) type SpawnRegistrationChannel = std::os::unix::net::UnixStream;
21#[cfg(windows)]
22pub(super) type SpawnRegistrationChannel = subc_os::registration_channel::RegistrationPipe;
23#[cfg(test)]
24pub(super) type CapturedRegistrationChannels =
25 Arc<Mutex<Option<Vec<(Arc<RegistrationSpawn>, CapturedRegistrationEndpoint)>>>>;
26#[cfg(test)]
27pub(super) struct CapturedRegistrationEndpoint {
28 pub(super) _channel: SpawnRegistrationChannel,
29}
30#[cfg(test)]
31impl fmt::Debug for CapturedRegistrationEndpoint {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 f.write_str("CapturedRegistrationEndpoint")
34 }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum ScriptRuntime {
41 Bun,
42 Python,
43}
44
45impl ScriptRuntime {
46 pub const fn as_str(self) -> &'static str {
47 match self {
48 Self::Bun => "bun",
49 Self::Python => "python",
50 }
51 }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
56#[non_exhaustive]
57pub struct ScriptEntry {
58 pub runtime: ScriptRuntime,
59 pub path: PathBuf,
60}
61
62impl ScriptEntry {
63 pub fn new(runtime: ScriptRuntime, path: PathBuf) -> Self {
64 Self { runtime, path }
65 }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct ModuleSpec {
71 pub module_id: String,
72 pub program: PathBuf,
73 pub script: Option<ScriptEntry>,
75 pub args: Vec<String>,
76 pub env: Vec<(String, String)>,
77 pub reserved: bool,
82 pub reserved_prefixes: Vec<String>,
87 pub protocol: ModuleProtocol,
106 pub overlap: ModuleOverlap,
111 pub carry_containment: bool,
115}
116
117#[derive(Clone, PartialEq, Eq)]
120pub(crate) struct LaunchSpecDigest(pub(super) [u8; 32]);
121
122impl fmt::Debug for LaunchSpecDigest {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.write_str("LaunchSpecDigest([redacted])")
125 }
126}
127
128impl LaunchSpecDigest {
129 pub(crate) fn from_spec(spec: &ModuleSpec) -> Self {
130 fn field(hash: &mut Sha256, bytes: &[u8]) {
131 hash.update((bytes.len() as u64).to_le_bytes());
132 hash.update(bytes);
133 }
134 let mut hash = Sha256::new();
135 if let Some(script) = &spec.script {
136 field(
137 &mut hash,
138 match script.runtime {
139 ScriptRuntime::Bun => b"bun-script",
140 ScriptRuntime::Python => b"python-script",
141 },
142 );
143 field(&mut hash, script.path.as_os_str().as_encoded_bytes());
144 }
145 if let Some(program) = spec.program.to_str() {
146 field(&mut hash, b"utf8-program");
147 field(&mut hash, program.as_bytes());
148 } else {
149 #[cfg(unix)]
152 {
153 use std::os::unix::ffi::OsStrExt;
154 field(&mut hash, b"unix-program");
155 field(&mut hash, spec.program.as_os_str().as_bytes());
156 }
157 #[cfg(windows)]
158 {
159 use std::os::windows::ffi::OsStrExt;
160 field(&mut hash, b"windows-program");
161 let bytes = spec
162 .program
163 .as_os_str()
164 .encode_wide()
165 .flat_map(u16::to_le_bytes)
166 .collect::<Vec<_>>();
167 field(&mut hash, &bytes);
168 }
169 #[cfg(not(any(unix, windows)))]
170 field(&mut hash, spec.program.to_string_lossy().as_bytes());
171 }
172 hash.update((spec.args.len() as u64).to_le_bytes());
173 for arg in &spec.args {
174 field(&mut hash, arg.as_bytes());
175 }
176 let mut env = spec.env.iter().collect::<Vec<_>>();
177 env.sort_unstable();
178 hash.update((env.len() as u64).to_le_bytes());
179 for (key, value) in env {
180 field(&mut hash, key.as_bytes());
181 field(&mut hash, value.as_bytes());
182 }
183 field(
184 &mut hash,
185 match spec.protocol {
186 ModuleProtocol::Subc => b"subc",
187 ModuleProtocol::None => b"none",
188 },
189 );
190 Self(hash.finalize().into())
191 }
192}
193
194#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
201pub enum ModuleOverlap {
202 #[default]
204 Exclusive,
205 Safe,
217}
218
219impl ModuleOverlap {
220 pub fn as_str(self) -> &'static str {
221 match self {
222 Self::Exclusive => "exclusive",
223 Self::Safe => "safe",
224 }
225 }
226}
227
228pub const SUBC_SPAWN_ROLE_ENV: &str = "SUBC_SPAWN_ROLE";
238pub const SPAWN_ROLE_SWAP_CANDIDATE: &str = "swap_candidate";
240
241pub(crate) struct RegisteredConfiguredModule {
245 pub(super) spec: ModuleSpec,
246 pub(super) runtime: SupervisorRuntimeConfig,
247 pub(super) module: SupervisedModule,
248 pub(super) commands: mpsc::Receiver<SupervisorCommand>,
249}
250
251#[cfg(test)]
257#[derive(Clone, Default)]
258pub(super) struct AfterFirstSpawnHook(pub(super) Option<AfterFirstSpawnFn>);
259
260#[cfg(test)]
261type AfterFirstSpawnFn = Arc<dyn Fn(&str) + Send + Sync>;
262
263#[cfg(test)]
264impl fmt::Debug for AfterFirstSpawnHook {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 f.write_str("AfterFirstSpawnHook")
267 }
268}
269
270#[cfg(test)]
271impl AfterFirstSpawnHook {
272 fn run(&self, module_id: &str) {
273 if let Some(hook) = &self.0 {
274 hook(module_id);
275 }
276 }
277}
278
279impl Supervisor {
280 #[cfg(all(test, target_os = "linux"))]
281 pub(crate) fn set_admission_hook_for_test(
282 &self,
283 hook: impl Fn(&str, &'static str, Option<u32>) -> bool + Send + Sync + 'static,
284 ) {
285 self.child_roster.set_admission_hook_for_test(hook);
286 }
287
288 #[cfg(test)]
289 pub(crate) fn new_for_test(registry: Arc<Registry>, policy: RestartPolicy) -> Self {
290 let supervisor = Self::new(registry, policy);
291 #[cfg(target_os = "macos")]
292 let supervisor = supervisor.with_privacy_trampoline(test_privacy_trampoline());
293 supervisor
294 }
295}
296
297impl Supervisor {
298 pub fn spawn(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
307 validate_spec(&spec)?;
308 self.establish_identity(&spec);
309
310 let runtime = self.runtime_config();
311 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
312 let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
313 let registration_watch = watch_registration(&self.registry, &spec);
314 let spawned = spawn_child(
315 &spec,
316 runtime.connection_file_path.as_deref(),
317 self.supervisor_handle.as_ref(),
318 &runtime.stderr_ring,
319 runtime.capture_logs_dir.as_deref(),
320 &runtime.child_roster,
321 runtime.spawn_delivery(),
322 #[cfg(target_os = "linux")]
323 runtime.cgroup_placement.as_ref(),
324 runtime.register_timeout,
325 );
326 #[cfg(test)]
327 self.test_after_first_spawn.run(&spec.module_id);
328 let mut child = match spawned {
329 Ok(child) => child,
330 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
331 defer_config_spawn(
332 &spec,
333 &runtime,
334 &snapshot,
335 RespawnKind::Spawn,
336 &runtime.failure_context(runtime.recovery_is_daemon),
337 )?;
338 return Ok(self.supervised_module(spec, runtime, snapshot, None));
339 }
340 Err(SuperviseError::ConfigHeld { .. }) => {
341 hold_config_spawn(
342 &spec,
343 &runtime,
344 &snapshot,
345 &runtime.failure_context(runtime.recovery_is_daemon),
346 )?;
347 return Ok(self.supervised_module(spec, runtime, snapshot, None));
348 }
349 Err(err) => {
350 self.abandon_unrostered(&spec.module_id);
353 return Err(err);
354 }
355 };
356 arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
357 self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
358 if let Some(spawn) = activity_spawn {
359 spawn.complete(&snapshot);
360 }
361
362 Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
363 }
364
365 pub async fn spawn_async(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
368 validate_spec(&spec)?;
369 self.establish_identity(&spec);
370 let mut identity = AsyncInitialIdentity {
371 supervisor: self,
372 module: spec.module_id.clone(),
373 committed: false,
374 };
375 let runtime = self.runtime_config();
376 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
377 let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
378 let registration_watch = watch_registration(&self.registry, &spec);
379 let spawned = spawn_child_async(&spec, &runtime).await;
380 #[cfg(test)]
381 self.test_after_first_spawn.run(&spec.module_id);
382 let mut child = match spawned {
383 Ok(child) => child,
384 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
385 defer_config_spawn(
386 &spec,
387 &runtime,
388 &snapshot,
389 RespawnKind::Spawn,
390 &runtime.failure_context(runtime.recovery_is_daemon),
391 )?;
392 identity.committed = true;
393 return Ok(self.supervised_module(spec, runtime, snapshot, None));
394 }
395 Err(SuperviseError::ConfigHeld { .. }) => {
396 hold_config_spawn(
397 &spec,
398 &runtime,
399 &snapshot,
400 &runtime.failure_context(runtime.recovery_is_daemon),
401 )?;
402 identity.committed = true;
403 return Ok(self.supervised_module(spec, runtime, snapshot, None));
404 }
405 Err(err) => {
406 self.abandon_unrostered(&spec.module_id);
407 return Err(err);
408 }
409 };
410 arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
411 self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
412 if let Some(spawn) = activity_spawn {
413 spawn.complete(&snapshot);
414 }
415 identity.committed = true;
416 Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
417 }
418
419 fn establish_identity(&self, spec: &ModuleSpec) {
432 if let Some(supervisor_handle) = &self.supervisor_handle {
433 supervisor_handle.apply_identity_configuration(spec);
434 supervisor_handle.mark_configured(&spec.module_id);
435 }
436 }
437
438 fn abandon_unrostered(&self, module_id: &str) {
441 if let Some(supervisor_handle) = &self.supervisor_handle {
442 supervisor_handle.unmark_configured_unless_rostered(module_id);
443 }
444 }
445
446 fn mark_first_process_running(
449 &self,
450 spec: &ModuleSpec,
451 runtime: &SupervisorRuntimeConfig,
452 snapshot: &SharedSnapshot,
453 child: &mut SupervisedChild,
454 ) -> Result<(), SuperviseError> {
455 if let Err(err) = set_running(snapshot, child, &spec.module_id, &runtime.spawn_events) {
456 containment::terminate_blocking(&runtime.child_roster.containment);
457 self.abandon_unrostered(&spec.module_id);
458 return Err(err);
459 }
460 self.process_liveness
461 .track(spec.module_id.clone(), Arc::clone(snapshot));
462 Ok(())
463 }
464
465 pub fn supervise_configured(
471 &self,
472 spec: ModuleSpec,
473 enabled: bool,
474 ) -> Result<SupervisedModule, SuperviseError> {
475 self.supervise_configured_requested(
476 spec,
477 enabled,
478 self.health.clone(),
479 None,
480 self.restart_policy,
481 DEFAULT_REGISTER_TIMEOUT,
482 None,
483 )
484 }
485
486 pub fn supervise_configured_with_health(
492 &self,
493 spec: ModuleSpec,
494 enabled: bool,
495 health: HealthConfig,
496 drain_timeout_ms: Option<u64>,
497 restart_policy: RestartPolicy,
498 ) -> Result<SupervisedModule, SuperviseError> {
499 self.supervise_configured_requested(
500 spec,
501 enabled,
502 health,
503 drain_timeout_ms,
504 restart_policy,
505 DEFAULT_REGISTER_TIMEOUT,
506 None,
507 )
508 }
509
510 #[allow(clippy::too_many_arguments)]
511 pub(crate) fn supervise_configured_requested(
512 &self,
513 spec: ModuleSpec,
514 enabled: bool,
515 health: HealthConfig,
516 drain_timeout_ms: Option<u64>,
517 restart_policy: RestartPolicy,
518 register_timeout: Duration,
519 requester: Option<Principal>,
520 ) -> Result<SupervisedModule, SuperviseError> {
521 let registered = self.register_configured_with_health(
522 spec,
523 enabled,
524 health,
525 drain_timeout_ms,
526 restart_policy,
527 register_timeout,
528 )?;
529 let daemon_initiated = requester.is_none();
530 self.start_registered_configured(registered, requester, daemon_initiated)
531 }
532
533 #[allow(clippy::too_many_arguments)]
534 pub(crate) async fn supervise_configured_requested_async(
535 &self,
536 spec: ModuleSpec,
537 enabled: bool,
538 health: HealthConfig,
539 drain_timeout_ms: Option<u64>,
540 restart_policy: RestartPolicy,
541 register_timeout: Duration,
542 requester: Option<Principal>,
543 ) -> Result<SupervisedModule, SuperviseError> {
544 let registered = self.register_configured_with_health(
545 spec,
546 enabled,
547 health,
548 drain_timeout_ms,
549 restart_policy,
550 register_timeout,
551 )?;
552 let daemon_initiated = requester.is_none();
553 self.start_registered_configured_async(registered, requester, daemon_initiated)
554 .await
555 }
556
557 pub(crate) fn register_configured_with_health(
562 &self,
563 spec: ModuleSpec,
564 enabled: bool,
565 health: HealthConfig,
566 drain_timeout_ms: Option<u64>,
567 restart_policy: RestartPolicy,
568 register_timeout: Duration,
569 ) -> Result<RegisteredConfiguredModule, SuperviseError> {
570 validate_spec(&spec)?;
571 self.establish_identity(&spec);
572
573 let mut runtime = self.runtime_config();
574 runtime.health = health;
575 runtime.restart_policy = restart_policy;
576 runtime.register_timeout = register_timeout;
577 if let Some(ms) = drain_timeout_ms {
578 runtime.drain_timeout = Duration::from_millis(ms);
579 *runtime
580 .effective_drain_timeout
581 .lock()
582 .unwrap_or_else(|poisoned| poisoned.into_inner()) = runtime.drain_timeout;
583 }
584 let snapshot = if enabled {
585 SupervisorSnapshot::starting()
586 } else {
587 SupervisorSnapshot::disabled()
588 };
589 let snapshot = {
590 let mut snapshot = snapshot;
591 if enabled {
592 if let Some((pid, reason)) = runtime.child_roster.previous_instance(&spec.module_id)
593 {
594 snapshot.waiting_for_previous_pid = Some(pid);
595 snapshot.waiting_for_previous_detail = Some(reason.waiting_message(pid));
596 }
597 }
598 snapshot
599 };
600 let (module, commands) =
601 self.register_module(&spec, &runtime, Arc::new(Mutex::new(snapshot)));
602 Ok(RegisteredConfiguredModule {
603 spec,
604 runtime,
605 module,
606 commands,
607 })
608 }
609
610 pub(crate) fn start_registered_configured(
613 &self,
614 registered: RegisteredConfiguredModule,
615 requester: Option<Principal>,
616 daemon_initiated: bool,
617 ) -> Result<SupervisedModule, SuperviseError> {
618 let RegisteredConfiguredModule {
619 spec,
620 mut runtime,
621 module,
622 commands,
623 } = registered;
624 runtime.start_requester = requester;
625 runtime.recovery_is_daemon = daemon_initiated;
626 let snapshot = &module.inner.snapshot;
627 let should_spawn = {
628 let state = lock_snapshot(snapshot)?;
629 state.enabled && state.waiting_for_previous_pid.is_none()
630 };
631 let child = if should_spawn {
632 let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
633 let registration_watch = watch_registration(&self.registry, &spec);
634 let spawned = spawn_child(
635 &spec,
636 runtime.connection_file_path.as_deref(),
637 self.supervisor_handle.as_ref(),
638 &runtime.stderr_ring,
639 runtime.capture_logs_dir.as_deref(),
640 &runtime.child_roster,
641 runtime.spawn_delivery(),
642 #[cfg(target_os = "linux")]
643 runtime.cgroup_placement.as_ref(),
644 runtime.register_timeout,
645 );
646 #[cfg(test)]
647 self.test_after_first_spawn.run(&spec.module_id);
648 match spawned {
649 Ok(mut child) => {
650 arm_registration_deadline(
651 &mut child,
652 runtime.register_timeout,
653 registration_watch,
654 );
655 self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
656 if let Some(spawn) = activity_spawn {
657 spawn.complete(snapshot);
658 }
659 Some(child)
660 }
661 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
662 defer_config_spawn(
663 &spec,
664 &runtime,
665 snapshot,
666 RespawnKind::Spawn,
667 &runtime.failure_context(daemon_initiated),
668 )?;
669 None
670 }
671 Err(mut err) => {
672 if matches!(err, SuperviseError::ConfigHeld { .. }) {
673 match hold_config_spawn(
674 &spec,
675 &runtime,
676 snapshot,
677 &runtime.failure_context(daemon_initiated),
678 ) {
679 Ok(()) => {
680 self.start_monitor(spec, runtime, &module, None, commands);
681 return Ok(module);
682 }
683 Err(parking_error) => err = parking_error,
684 }
685 }
686 if runtime.health.critical {
687 error!(
688 module_id = %spec.module_id,
689 program = %spec.program.display(),
690 error = %err,
691 "critical configured module failed to spawn; marking failed and alerting"
692 );
693 } else {
694 error!(
695 module_id = %spec.module_id,
696 program = %spec.program.display(),
697 error = %err,
698 "configured module failed to spawn; marking failed and continuing"
699 );
700 }
701 fail_snapshot(
702 snapshot,
703 Some(&spec.module_id),
704 None,
705 &runtime.failure_context(daemon_initiated),
706 );
707 None
708 }
709 }
710 } else {
711 None
712 };
713 self.start_monitor(spec, runtime, &module, child, commands);
714 Ok(module)
715 }
716
717 pub(crate) async fn start_registered_configured_async(
718 &self,
719 registered: RegisteredConfiguredModule,
720 requester: Option<Principal>,
721 daemon_initiated: bool,
722 ) -> Result<SupervisedModule, SuperviseError> {
723 self.start_registered_with_failure_policy(registered, requester, daemon_initiated, None)
724 .await
725 }
726
727 pub(crate) async fn start_registered_approved_async(
728 &self,
729 registered: RegisteredConfiguredModule,
730 requester: Principal,
731 generation: crate::config_gate::runtime::ApprovalIdentity,
732 ) -> Result<SupervisedModule, SuperviseError> {
733 self.start_registered_with_failure_policy(
734 registered,
735 Some(requester),
736 false,
737 Some(generation),
738 )
739 .await
740 }
741
742 async fn start_registered_with_failure_policy(
743 &self,
744 registered: RegisteredConfiguredModule,
745 requester: Option<Principal>,
746 daemon_initiated: bool,
747 approved_generation: Option<crate::config_gate::runtime::ApprovalIdentity>,
748 ) -> Result<SupervisedModule, SuperviseError> {
749 let RegisteredConfiguredModule {
750 spec,
751 mut runtime,
752 module,
753 commands,
754 } = registered;
755 runtime.start_requester = requester;
756 runtime.recovery_is_daemon = daemon_initiated;
757 let snapshot = &module.inner.snapshot;
758 let mut startup_error = None;
759 let failure = FailureContext {
760 approval: approved_generation.clone(),
761 ..runtime.failure_context(daemon_initiated)
762 };
763 let should_spawn = {
764 let state = lock_snapshot(snapshot)?;
765 state.enabled && state.waiting_for_previous_pid.is_none()
766 };
767 let child = if should_spawn {
768 let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
769 let registration_watch = watch_registration(&self.registry, &spec);
770 let spawned = spawn_child_async(&spec, &runtime).await;
771 #[cfg(any(target_os = "linux", target_os = "macos"))]
772 {
773 runtime.replacement_ticket = None;
774 }
775 #[cfg(test)]
776 self.test_after_first_spawn.run(&spec.module_id);
777 match spawned {
778 Ok(mut child) => {
779 arm_registration_deadline(
780 &mut child,
781 runtime.register_timeout,
782 registration_watch,
783 );
784 self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
785 if let Some(spawn) = activity_spawn {
786 spawn.complete(snapshot);
787 }
788 Some(child)
789 }
790 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
791 defer_config_spawn(&spec, &runtime, snapshot, RespawnKind::Spawn, &failure)?;
792 None
793 }
794 Err(mut err) => {
795 if matches!(err, SuperviseError::ConfigHeld { .. }) {
796 match hold_config_spawn(&spec, &runtime, snapshot, &failure) {
797 Ok(()) => {
798 self.start_monitor(spec, runtime, &module, None, commands);
799 return Ok(module);
800 }
801 Err(parking_error) => err = parking_error,
802 }
803 }
804 if runtime.health.critical {
805 error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
806 "critical configured module failed to spawn; marking failed and alerting");
807 } else {
808 error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
809 "configured module failed to spawn; marking failed and continuing");
810 }
811 fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
812 if let Some(generation) = approved_generation {
813 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
814 state.approved_start_failure = Some((generation, err.to_string()));
815 });
816 startup_error = Some(err);
817 }
818 None
819 }
820 }
821 } else {
822 None
823 };
824 self.start_monitor(spec, runtime, &module, child, commands);
825 startup_error.map_or(Ok(module), Err)
829 }
830
831 pub(super) fn runtime_config(&self) -> SupervisorRuntimeConfig {
832 let effective_drain_timeout = Arc::new(Mutex::new(self.drain_timeout));
833 SupervisorRuntimeConfig {
834 registry: self.registry.clone(),
835 config_delivery: self.config_delivery.clone(),
836 recovery_is_daemon: true,
837 start_requester: None,
838 pending_activity_restart: false,
839 provenance_probe: self.provenance_probe.clone(),
840 scheduled_respawn: Arc::default(),
841 deferred_reload_reply: Arc::default(),
842 restart_policy: self.restart_policy,
843 register_timeout: DEFAULT_REGISTER_TIMEOUT,
844 drain_timeout: self.drain_timeout,
845 child_roster: self
848 .child_roster
849 .for_module(Arc::clone(&effective_drain_timeout)),
850 effective_drain_timeout,
851 default_drain_timeout: self.drain_timeout,
852 health: self.health.clone(),
853 host_health: self.host_health.clone(),
854 connection_file_path: self.connection_file_path.clone(),
855 capture_logs_dir: self.capture_logs_dir.clone(),
856 forwarding: self.forwarding.clone(),
857 supervisor_handle: self.supervisor_handle.clone(),
858 #[cfg(any(target_os = "linux", target_os = "macos"))]
859 replacement_ticket: None,
860 stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
861 terminal_ring: Arc::new(Mutex::new(
862 TerminalRing::new(
863 TerminalRingConfig::default(),
864 self.daemon_start_clock.started_at_ms(),
865 )
866 .with_start_clock(self.daemon_start_clock)
867 .with_journal(self.terminal_journal.clone())
868 .with_daemon_shutdown(self.child_roster.shutdown_flag()),
869 )),
870 spawn_events: self.spawn_events.clone(),
871 #[cfg(target_os = "linux")]
872 cgroup_placement: self.cgroup_placement.clone(),
873 #[cfg(test)]
874 test_seed_stale_facts_before_enable_spawn: false,
875 #[cfg(test)]
876 test_reload_exit_record_gate: None,
877 }
878 }
879
880 pub(super) fn supervised_module(
881 &self,
882 spec: ModuleSpec,
883 runtime: SupervisorRuntimeConfig,
884 snapshot: SharedSnapshot,
885 child: Option<SupervisedChild>,
886 ) -> SupervisedModule {
887 let (module, commands) = self.register_module(&spec, &runtime, snapshot);
888 self.start_monitor(spec, runtime, &module, child, commands);
889 module
890 }
891
892 pub(super) fn register_module(
893 &self,
894 spec: &ModuleSpec,
895 runtime: &SupervisorRuntimeConfig,
896 snapshot: SharedSnapshot,
897 ) -> (SupervisedModule, mpsc::Receiver<SupervisorCommand>) {
898 runtime.host_health.track(spec, &snapshot);
899 let configuration = Arc::new(Mutex::new(SupervisedConfiguration {
900 spec: spec.clone(),
901 enabled: snapshot.lock().unwrap_or_else(|p| p.into_inner()).enabled,
902 health: runtime.health.clone(),
903 register_timeout: runtime.register_timeout,
904 restart_policy: runtime.restart_policy,
905 }));
906 let stderr_ring = Arc::clone(&runtime.stderr_ring);
907 let terminal_ring = Arc::clone(&runtime.terminal_ring);
908 let effective_drain_timeout = Arc::clone(&runtime.effective_drain_timeout);
909 let (tx, rx) = mpsc::channel(4);
910 let module_id = spec.module_id.clone();
911 let module = SupervisedModule {
912 inner: Arc::new(SupervisedModuleInner {
913 module_id: module_id.clone(),
914 registry: Arc::clone(&self.registry),
915 snapshot,
916 configuration,
917 stderr_ring,
918 terminal_ring,
919 commands: tx,
920 monitor: Mutex::new(None),
921 effective_drain_timeout,
922 provenance_probe: self.provenance_probe.clone(),
923 retained: runtime.child_roster.retained_view(),
924 }),
925 };
926 if let Some(supervisor_handle) = &self.supervisor_handle {
929 supervisor_handle.insert(module.clone());
930 }
931 (module, rx)
932 }
933
934 pub(super) fn start_monitor(
935 &self,
936 spec: ModuleSpec,
937 runtime: SupervisorRuntimeConfig,
938 module: &SupervisedModule,
939 child: Option<SupervisedChild>,
940 commands: mpsc::Receiver<SupervisorCommand>,
941 ) {
942 let monitor = tokio::spawn(supervise_loop(
943 spec,
944 runtime,
945 Arc::clone(&self.registry),
946 Arc::clone(&self.process_liveness),
947 Arc::clone(&module.inner.snapshot),
948 child,
949 commands,
950 ));
951 *module
952 .inner
953 .monitor
954 .lock()
955 .unwrap_or_else(|p| p.into_inner()) = Some(monitor);
956 }
957}
958
959pub(crate) fn validate_spec(spec: &ModuleSpec) -> Result<(), SuperviseError> {
960 if spec.carry_containment && spec.overlap == ModuleOverlap::Safe {
961 return Err(SuperviseError::InvalidSpec {
962 reason: "carry_containment cannot be combined with overlap: safe".to_owned(),
963 });
964 }
965 if spec.module_id.trim().is_empty() {
966 return Err(SuperviseError::InvalidSpec {
967 reason: "module_id must not be empty".to_string(),
968 });
969 }
970
971 Ok(())
972}
973
974#[cfg(test)]
988pub(super) fn apply_wire_spawn_args(
989 command: &mut Command,
990 spec: &ModuleSpec,
991 connection_file_path: Option<&std::path::Path>,
992 handle: Option<&SupervisorHandle>,
993) -> Result<Option<NonceHandoff>, SuperviseError> {
994 apply_wire_spawn_args_for_role(
995 command,
996 spec,
997 connection_file_path,
998 handle,
999 SpawnRole::Plain,
1000 )
1001}
1002
1003#[cfg(unix)]
1008type NonceHandoff = subc_os::LaunchNonceHandoff;
1009#[cfg(windows)]
1010type NonceHandoff = subc_os::LaunchNoncePipeHandoff;
1011#[cfg(not(any(unix, windows)))]
1012type NonceHandoff = std::convert::Infallible;
1013
1014#[cfg(test)]
1032fn apply_wire_spawn_args_for_role(
1033 command: &mut Command,
1034 spec: &ModuleSpec,
1035 connection_file_path: Option<&std::path::Path>,
1036 handle: Option<&SupervisorHandle>,
1037 role: SpawnRole,
1038) -> Result<Option<NonceHandoff>, SuperviseError> {
1039 apply_wire_spawn_args_for_admission(command, spec, connection_file_path, handle, role, None)
1040}
1041
1042pub(super) fn apply_wire_spawn_args_for_admission(
1043 command: &mut Command,
1044 spec: &ModuleSpec,
1045 connection_file_path: Option<&std::path::Path>,
1046 handle: Option<&SupervisorHandle>,
1047 role: SpawnRole,
1048 admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
1049) -> Result<Option<NonceHandoff>, SuperviseError> {
1050 command.env(SUBC_MODULE_ID_ENV, &spec.module_id);
1051 command.env_remove(subc_os::LAUNCH_NONCE_FD_ENV);
1056 #[cfg(windows)]
1057 {
1058 command.env_remove(subc_os::LAUNCH_NONCE_PIPE_ENV);
1059 command.env_remove(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV);
1060 }
1061 command.env_remove(SUBC_LAUNCH_NONCE_ENV);
1063 command.env_remove(subc_os::registration_channel::REGISTRATION_FD_ENV);
1064 command.env_remove(subc_os::registration_channel::REGISTRATION_PIPE_ENV);
1065 command.env_remove(subc_os::registration_channel::DAEMON_PID_ENV);
1066 if role == SpawnRole::Plain {
1067 if let Some(handle) = handle {
1068 #[cfg(all(test, unix))]
1069 {
1070 let pause = {
1071 let mut slot = handle.plain_identity_policy_pause.lock().unwrap();
1072 if slot
1073 .as_ref()
1074 .is_some_and(|(module, _)| module == &spec.module_id)
1075 {
1076 slot.take().map(|(_, pause)| pause)
1077 } else {
1078 None
1079 }
1080 };
1081 if let Some(pause) = pause {
1082 pause.reached.send(()).unwrap();
1083 pause.release.recv().unwrap();
1084 }
1085 }
1086 handle.apply_identity_policy(spec, spec.protocol);
1090 }
1091 }
1092 if spec.protocol == ModuleProtocol::None {
1093 return Ok(None);
1094 }
1095 if let Some(connection_file_path) = connection_file_path {
1096 command.arg(SUBC_ARG).arg(connection_file_path);
1097 }
1098
1099 if admission.is_some_and(|admission| admission.launch.is_some()) {
1100 if let Some(handle) = handle {
1101 match role {
1102 SpawnRole::Plain => {
1103 handle
1104 .spawn_nonces
1105 .lock()
1106 .unwrap_or_else(|p| p.into_inner())
1107 .remove(&spec.module_id);
1108 if spec.reserved {
1109 handle
1110 .reserved_nonces
1111 .lock()
1112 .unwrap_or_else(|p| p.into_inner())
1113 .insert(spec.module_id.clone(), None);
1114 }
1115 }
1116 SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, String::new()),
1119 }
1120 }
1121 return Ok(None);
1122 }
1123 let nonce = generate_launch_nonce()?;
1127 if let Some(handle) = handle {
1128 match role {
1129 SpawnRole::Plain => {
1130 handle.set_spawn_nonce(&spec.module_id, nonce.clone());
1131 if spec.reserved {
1132 handle.set_reserved_nonce(&spec.module_id, nonce.clone());
1133 }
1134 }
1135 SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, nonce.clone()),
1136 }
1137 }
1138 #[cfg(unix)]
1139 let handoff = {
1140 let handoff =
1141 subc_os::LaunchNonceHandoff::new(&nonce).map_err(|source| SuperviseError::Spawn {
1142 program: spec.program.clone(),
1143 source,
1144 cgroup_path: None,
1145 })?;
1146 command.env(subc_os::LAUNCH_NONCE_FD_ENV, handoff.fd_env_value());
1147 Some(handoff)
1148 };
1149 #[cfg(windows)]
1150 let handoff = Some(prepare_windows_nonce_pipe(
1151 command, spec, &nonce, handle, role,
1152 )?);
1153 #[cfg(not(any(unix, windows)))]
1154 let handoff = None;
1155 #[cfg(not(any(unix, windows)))]
1156 command.env(SUBC_LAUNCH_NONCE_ENV, nonce);
1157 Ok(handoff)
1158}
1159
1160pub(crate) fn apply_child_env(command: &mut Command, spec: &ModuleSpec) {
1161 command.env_remove(CK_LOG_ENV);
1162 command.env_remove(SUBC_SPAWN_ROLE_ENV);
1169 for (key, value) in &spec.env {
1170 if matches!(
1174 key.as_str(),
1175 CAPTURE_MAX_FILE_MB_ENV | CAPTURE_KEEP_ENV | CAPTURE_MAX_AGE_DAYS_ENV
1176 ) || key == SUBC_SPAWN_ROLE_ENV
1177 {
1178 continue;
1179 }
1180 command.env(key, value);
1181 }
1182}
1183
1184#[cfg(windows)]
1185pub(super) fn prepare_windows_registration_pipe(
1186 command: &mut Command,
1187 spec: &ModuleSpec,
1188) -> Result<Option<SpawnRegistrationChannel>, SuperviseError> {
1189 if spec.protocol == ModuleProtocol::None {
1190 return Ok(None);
1191 }
1192 let pipe = subc_os::registration_channel::RegistrationPipe::new().map_err(|source| {
1193 SuperviseError::Spawn {
1194 program: spec.program.clone(),
1195 source,
1196 cgroup_path: None,
1197 }
1198 })?;
1199 command
1200 .env(
1201 subc_os::registration_channel::REGISTRATION_PIPE_ENV,
1202 pipe.name(),
1203 )
1204 .env(
1205 subc_os::registration_channel::DAEMON_PID_ENV,
1206 std::process::id().to_string(),
1207 );
1208 Ok(Some(pipe))
1209}
1210
1211#[cfg(windows)]
1212fn prepare_windows_nonce_pipe(
1213 command: &mut Command,
1214 spec: &ModuleSpec,
1215 nonce: &str,
1216 handle: Option<&SupervisorHandle>,
1217 role: SpawnRole,
1218) -> Result<NonceHandoff, SuperviseError> {
1219 let handoff = subc_os::LaunchNoncePipeHandoff::new(nonce).map_err(|source| {
1220 update_nonce_pipe_refusal(handle, spec, role, Some("launch_nonce_pipe_prepare_failed"));
1221 windows_nonce_pipe_error(spec, "prepare", source)
1222 })?;
1223 command.env(subc_os::LAUNCH_NONCE_PIPE_ENV, handoff.name());
1224 Ok(handoff)
1225}
1226
1227#[cfg(windows)]
1228fn update_nonce_pipe_refusal(
1229 handle: Option<&SupervisorHandle>,
1230 spec: &ModuleSpec,
1231 role: SpawnRole,
1232 refusal: Option<&'static str>,
1233) {
1234 if role == SpawnRole::Plain {
1236 if let Some(module) = handle.and_then(|handle| handle.get(&spec.module_id)) {
1237 if let Err(error) =
1238 update_snapshot(&module.inner.snapshot, Some(&spec.module_id), |state| {
1239 state.nonce_pipe_refusal = refusal;
1240 })
1241 {
1242 error!(module_id = %spec.module_id, %error, "could not record Windows launch nonce pipe status");
1243 }
1244 }
1245 }
1246}
1247
1248#[cfg(windows)]
1249fn windows_nonce_pipe_error(spec: &ModuleSpec, step: &str, source: io::Error) -> SuperviseError {
1250 SuperviseError::Spawn {
1251 program: spec.program.clone(),
1252 source: io::Error::new(
1253 source.kind(),
1254 format!("could not {step} Windows launch nonce pipe: {source}"),
1255 ),
1256 cgroup_path: None,
1257 }
1258}
1259
1260pub(super) fn observed_launch_nonce_source(snapshot: &SupervisorSnapshot) -> Option<String> {
1261 #[cfg(windows)]
1262 if snapshot.process_alive
1263 && snapshot.spawned_protocol == Some(ModuleProtocol::Subc)
1264 && snapshot
1265 .pipe_consumed
1266 .as_ref()
1267 .is_some_and(|consumed| consumed.get().is_some())
1268 {
1269 return Some("pipe".to_owned());
1270 }
1271 let _ = snapshot;
1272 None
1273}
1274
1275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1278pub(crate) enum SpawnRole {
1279 Plain,
1280 SwapCandidate,
1281}
1282
1283pub(super) fn apply_spawn_role(command: &mut Command, role: SpawnRole) {
1286 if role == SpawnRole::SwapCandidate {
1287 command.env(SUBC_SPAWN_ROLE_ENV, SPAWN_ROLE_SWAP_CANDIDATE);
1288 }
1289}
1290
1291pub(super) fn previous_instance_error(
1292 spec: &ModuleSpec,
1293 pid: u32,
1294 reason: crate::live_children::RetainedReason,
1295) -> SuperviseError {
1296 SuperviseError::Spawn {
1297 program: spec.program.clone(),
1298 source: io::Error::new(io::ErrorKind::WouldBlock, reason.waiting_message(pid)),
1299 cgroup_path: None,
1300 }
1301}
1302
1303pub(super) fn carries_containment(configured: bool, has_container: bool) -> bool {
1304 configured || has_container
1305}
1306
1307pub(super) fn recovery_block_error(
1308 spec: &ModuleSpec,
1309 roster: &ChildRoster,
1310) -> Option<SuperviseError> {
1311 if !carries_containment(
1312 spec.carry_containment,
1313 containment::current(&roster.containment).is_some(),
1314 ) {
1315 return None;
1316 }
1317 Some(SuperviseError::Spawn {
1318 program: spec.program.clone(),
1319 source: io::Error::new(io::ErrorKind::WouldBlock, roster.recovery_block()?),
1320 cgroup_path: None,
1321 })
1322}
1323
1324#[allow(clippy::too_many_arguments)]
1325pub(super) fn spawn_child(
1326 spec: &ModuleSpec,
1327 connection_file_path: Option<&std::path::Path>,
1328 handle: Option<&SupervisorHandle>,
1329 ring: &Arc<Mutex<StderrRing>>,
1330 capture_logs_dir: Option<&std::path::Path>,
1331 roster: &ChildRoster,
1332 config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
1333 #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
1334 register_timeout: Duration,
1335) -> Result<SupervisedChild, SuperviseError> {
1336 #[cfg(all(test, unix))]
1337 if let Some(source) = containment_tests::join_failure(spec, roster) {
1338 containment::terminate_blocking(&roster.containment);
1339 return Err(SuperviseError::Spawn {
1340 program: spec.program.clone(),
1341 source,
1342 cgroup_path: None,
1343 });
1344 }
1345 let result = spawn_child_in_slot(
1346 spec,
1347 connection_file_path,
1348 handle,
1349 ring,
1350 capture_logs_dir,
1351 roster,
1352 config_delivery,
1353 #[cfg(target_os = "linux")]
1354 cgroup_placement,
1355 SpawnRole::Plain,
1356 false,
1357 register_timeout,
1358 );
1359 if result
1360 .as_ref()
1361 .is_err_and(|error| !is_launch_deferral(error))
1362 {
1363 if roster.admission_pending(&spec.module_id) {
1364 containment::terminate_deferred(&roster.containment);
1365 } else {
1366 containment::terminate_blocking(&roster.containment);
1367 }
1368 }
1369 result
1370}
1371
1372pub(super) fn is_launch_deferral(error: &SuperviseError) -> bool {
1378 matches!(error, SuperviseError::ConfigDeliveryDeferred { .. })
1379}
1380
1381#[allow(clippy::too_many_arguments)]
1394pub(super) fn spawn_child_in_slot(
1395 spec: &ModuleSpec,
1396 connection_file_path: Option<&std::path::Path>,
1397 handle: Option<&SupervisorHandle>,
1398 ring: &Arc<Mutex<StderrRing>>,
1399 capture_logs_dir: Option<&std::path::Path>,
1400 roster: &ChildRoster,
1401 config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
1402 #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
1403 role: SpawnRole,
1404 alternate_slot: bool,
1405 register_timeout: Duration,
1406) -> Result<SupervisedChild, SuperviseError> {
1407 let prepared = prepare_child_in_slot(
1408 spec,
1409 connection_file_path,
1410 handle,
1411 capture_logs_dir,
1412 roster,
1413 config_delivery,
1414 #[cfg(target_os = "linux")]
1415 cgroup_placement,
1416 role,
1417 alternate_slot,
1418 false,
1419 )?;
1420 let gate = config_delivery
1421 .map(|delivery| delivery.module_gate(spec))
1422 .transpose()?;
1423 let _gate = gate
1424 .as_ref()
1425 .map(|gate| {
1426 gate.try_lock()
1427 .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
1428 module_id: spec.module_id.clone(),
1429 })
1430 })
1431 .transpose()?;
1432 if let (Some(delivery), Some(admission)) = (config_delivery, &prepared.spawn_admission) {
1433 delivery.check(spec, admission)?;
1434 }
1435 let checked_base = prepared
1436 .spawn_admission
1437 .as_ref()
1438 .and_then(|admission| admission.approved_base())
1439 .cloned();
1440 let mut result = launch_child_in_slot(spec, ring, roster, prepared, register_timeout);
1441 drop(_gate);
1442 if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
1443 (config_delivery, &result)
1444 {
1445 if let Some(base) = checked_base.as_ref().filter(|_| code == "program_refused") {
1446 if !delivery.record_refusal(spec, base, detail)? {
1447 result = Err(spawn_plan_stale(spec));
1448 }
1449 }
1450 }
1451 result
1452}
1453
1454struct AsyncInitialIdentity<'a> {
1455 supervisor: &'a Supervisor,
1456 module: String,
1457 committed: bool,
1458}
1459impl Drop for AsyncInitialIdentity<'_> {
1460 fn drop(&mut self) {
1461 if !self.committed {
1462 self.supervisor.abandon_unrostered(&self.module);
1463 }
1464 }
1465}
1466
1467pub(super) struct PreparedChild {
1471 script_delivery: Option<script::Delivery>,
1472 registration_spawn: Option<Arc<RegistrationSpawn>>,
1473 registration_handle: Option<SupervisorHandle>,
1474 #[cfg(any(unix, windows))]
1475 registration_channel: Option<SpawnRegistrationChannel>,
1476 config_context: Option<config_delivery::ConfigDelivery>,
1477 binding_publication: Option<ProgramBindingPublication>,
1478 launch_spec: ModuleSpec,
1479 spawn_admission: Option<crate::config_gate::runtime::SpawnAdmission>,
1480 pub(super) command: Command,
1481 carrying: bool,
1482 carried: Option<Arc<containment::CarriedContainment>>,
1483 #[cfg(unix)]
1484 launch_identity: Option<containment::LaunchIdentity>,
1485 #[cfg(unix)]
1486 group_target: containment::GroupTarget,
1487 #[cfg(target_os = "linux")]
1488 pub(super) cgroup_placement: Option<subc_cgroup::Placement>,
1489 #[cfg(target_os = "linux")]
1490 pub(super) cgroup_name: String,
1491 #[cfg(target_os = "linux")]
1492 cgroup_cleanup: PreparedCgroup,
1493 pub(super) cgroup_path: Option<PathBuf>,
1494 #[cfg(unix)]
1495 admission_gate: Option<admission::Gate>,
1496 output_sink: ChildOutputSink,
1497 #[cfg(target_os = "macos")]
1498 privacy_exec: Option<PrivacyExec>,
1499 #[cfg(windows)]
1500 image_capture: subc_os::ExecutableCapture,
1501 #[cfg(windows)]
1502 nonce_handoff: Option<NonceHandoff>,
1503 #[cfg(windows)]
1504 role: SpawnRole,
1505 spawned_at: Instant,
1506 config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
1507 delivery_registration: Option<config_delivery::RegistrationGuard>,
1508 program_binding: Option<SpawnProgramBinding>,
1509}
1510
1511#[cfg(target_os = "linux")]
1512struct PreparedCgroup(Option<(subc_cgroup::Placement, String)>);
1513#[cfg(target_os = "linux")]
1514impl Drop for PreparedCgroup {
1515 fn drop(&mut self) {
1516 if let Some((placement, name)) = &self.0 {
1517 remove_module_cgroup(placement, name);
1518 }
1519 }
1520}
1521
1522pub(crate) struct SpawnProgramBinding {
1523 pub(crate) path: PathBuf,
1524 pub(super) _file: std::fs::File,
1527 pub(crate) identity: subc_os::RetainedFileIdentity,
1528}
1529
1530impl SpawnProgramBinding {
1531 pub(crate) fn capture(spec: &ModuleSpec) -> Result<Self, SuperviseError> {
1532 Self::capture_after_resolution(spec, |_| {})
1533 }
1534
1535 pub(super) fn capture_after_resolution(
1536 spec: &ModuleSpec,
1537 before_open: impl FnOnce(&std::path::Path),
1538 ) -> Result<Self, SuperviseError> {
1539 require_program_search_path(spec)?;
1540 #[cfg(windows)]
1541 let windows_capture =
1542 windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
1543 program: spec.program.clone(),
1544 source,
1545 cgroup_path: None,
1546 })?;
1547 #[cfg(windows)]
1548 let path = windows_capture.path().to_path_buf();
1549 #[cfg(not(windows))]
1550 let path = if spec.program.is_absolute() || spec.program.components().count() > 1 {
1551 spec.program.clone()
1552 } else {
1553 let path = spec
1554 .env
1555 .iter()
1556 .rev()
1557 .find(|(key, _)| key == "PATH")
1558 .map(|(_, path)| std::ffi::OsString::from(path))
1559 .or_else(|| std::env::var_os("PATH"))
1560 .unwrap_or_else(|| {
1561 if cfg!(target_os = "macos") {
1562 "/usr/bin:/bin".into()
1565 } else {
1566 Default::default()
1567 }
1568 });
1569 std::env::split_paths(&path)
1570 .map(|dir| dir.join(&spec.program))
1571 .find(|path| {
1572 if !path.is_file() {
1573 return false;
1574 }
1575 #[cfg(unix)]
1576 {
1577 rustix::fs::accessat(
1578 rustix::fs::CWD,
1579 path,
1580 rustix::fs::Access::EXEC_OK,
1581 rustix::fs::AtFlags::EACCESS,
1582 )
1583 .is_ok()
1584 }
1585 #[cfg(not(unix))]
1586 {
1587 true
1588 }
1589 })
1590 .ok_or_else(|| SuperviseError::Spawn {
1591 program: spec.program.clone(),
1592 source: io::Error::new(io::ErrorKind::NotFound, "executable not found in PATH"),
1593 cgroup_path: None,
1594 })?
1595 };
1596 let resolved = std::fs::canonicalize(&path).map_err(|source| SuperviseError::Spawn {
1597 program: spec.program.clone(),
1598 source,
1599 cgroup_path: None,
1600 })?;
1601 before_open(&resolved);
1602 let file =
1605 subc_os::open_regular_nofollow(&resolved).map_err(|source| SuperviseError::Spawn {
1606 program: spec.program.clone(),
1607 source: io::Error::other(source),
1608 cgroup_path: None,
1609 })?;
1610 let identity =
1611 subc_os::retained_file_identity(&file).map_err(|source| SuperviseError::Spawn {
1612 program: spec.program.clone(),
1613 source,
1614 cgroup_path: None,
1615 })?;
1616 Ok(Self {
1617 path,
1618 _file: file,
1619 identity,
1620 })
1621 }
1622 pub(super) fn current(&self) -> bool {
1623 #[cfg(unix)]
1624 {
1625 subc_os::file_identity(&self.path) == Some(self.identity)
1626 }
1627 #[cfg(windows)]
1628 {
1629 std::fs::canonicalize(&self.path)
1630 .ok()
1631 .and_then(|path| subc_os::open_regular_nofollow(&path).ok())
1632 .and_then(|file| subc_os::retained_file_identity(&file).ok())
1633 == Some(self.identity)
1634 }
1635 }
1636}
1637
1638pub(super) fn spawn_plan_stale(spec: &ModuleSpec) -> SuperviseError {
1639 SuperviseError::ConfigDeliveryDeferred {
1640 module_id: spec.module_id.clone(),
1641 }
1642}
1643
1644fn require_program_search_path(spec: &ModuleSpec) -> Result<(), SuperviseError> {
1645 if !cfg!(target_os = "macos")
1646 && !spec.program.is_absolute()
1647 && spec.program.components().count() == 1
1648 && !spec.env.iter().any(|(key, _)| {
1649 if cfg!(windows) {
1650 key.eq_ignore_ascii_case("PATH")
1651 } else {
1652 key == "PATH"
1653 }
1654 })
1655 && std::env::var_os("PATH").is_none()
1656 {
1657 return Err(SuperviseError::Spawn {
1660 program: spec.program.clone(),
1661 source: io::Error::new(io::ErrorKind::InvalidInput, "bare program requires PATH"),
1662 cgroup_path: None,
1663 });
1664 }
1665 Ok(())
1666}
1667
1668pub(super) async fn spawn_child_async(
1669 spec: &ModuleSpec,
1670 runtime: &SupervisorRuntimeConfig,
1671) -> Result<SupervisedChild, SuperviseError> {
1672 #[cfg(all(test, unix))]
1673 if let Some(source) = containment_tests::join_failure(spec, &runtime.child_roster) {
1674 containment::terminate_blocking(&runtime.child_roster.containment);
1675 return Err(SuperviseError::Spawn {
1676 program: spec.program.clone(),
1677 source,
1678 cgroup_path: None,
1679 });
1680 }
1681 let result = spawn_child_in_slot_async(spec, runtime, SpawnRole::Plain, false).await;
1682 if result
1683 .as_ref()
1684 .is_err_and(|error| !is_launch_deferral(error))
1685 {
1686 if runtime.child_roster.admission_pending(&spec.module_id) {
1687 containment::terminate_deferred(&runtime.child_roster.containment);
1688 } else {
1689 containment::terminate_blocking(&runtime.child_roster.containment);
1690 }
1691 }
1692 result
1693}
1694
1695pub(super) async fn spawn_child_in_slot_async(
1696 spec: &ModuleSpec,
1697 runtime: &SupervisorRuntimeConfig,
1698 role: SpawnRole,
1699 alternate_slot: bool,
1700) -> Result<SupervisedChild, SuperviseError> {
1701 let gate = runtime
1702 .config_delivery
1703 .as_ref()
1704 .map(|delivery| delivery.0.module_gate(&spec.module_id))
1705 .transpose()
1706 .map_err(|error| SuperviseError::InvalidSpec {
1707 reason: error.to_string(),
1708 })?;
1709 if gate.as_ref().is_some_and(|gate| gate.try_lock().is_err()) {
1710 return Err(SuperviseError::ConfigDeliveryDeferred {
1711 module_id: spec.module_id.clone(),
1712 });
1713 }
1714 let prepared_spec = spec.clone();
1715 let prepared_runtime = runtime.clone();
1716 let prepared = tokio::task::spawn_blocking(move || {
1717 let prepared = prepare_child_in_slot(
1718 &prepared_spec,
1719 prepared_runtime.connection_file_path.as_deref(),
1720 prepared_runtime.supervisor_handle.as_ref(),
1721 prepared_runtime.capture_logs_dir.as_deref(),
1722 &prepared_runtime.child_roster,
1723 prepared_runtime.spawn_delivery(),
1724 #[cfg(target_os = "linux")]
1725 prepared_runtime.cgroup_placement.as_ref(),
1726 role,
1727 alternate_slot,
1728 true,
1729 );
1730 prepared
1731 })
1732 .await
1733 .map_err(|_| SuperviseError::InvalidSpec {
1734 reason: "configuration launch preparation stopped".into(),
1735 })??;
1736 #[cfg(any(target_os = "linux", target_os = "macos"))]
1737 if let (Some(ticket), Some(launch)) =
1738 (&runtime.replacement_ticket, &prepared.registration_spawn)
1739 {
1740 ticket.bind(launch);
1741 }
1742 if let Some(registration) = &prepared.delivery_registration {
1743 if !registration.launch_current()? {
1744 return Err(spawn_plan_stale(spec));
1745 }
1746 }
1747 let _gate = match gate {
1748 Some(gate) => {
1749 Some(
1750 gate.try_lock_owned()
1751 .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
1752 module_id: spec.module_id.clone(),
1753 })?,
1754 )
1755 }
1756 None => None,
1757 };
1758 if let (Some(delivery), Some(admission)) = (runtime.spawn_delivery(), &prepared.spawn_admission)
1759 {
1760 delivery.check(spec, admission)?;
1761 }
1762 if prepared
1763 .spawn_admission
1764 .as_ref()
1765 .is_none_or(|admission| admission.launch.is_none())
1766 && prepared
1767 .program_binding
1768 .as_ref()
1769 .is_some_and(|binding| !binding.current())
1770 {
1771 return Err(spawn_plan_stale(spec));
1772 }
1773 let checked_base = prepared
1775 .spawn_admission
1776 .as_ref()
1777 .and_then(|admission| admission.approved_base())
1778 .cloned();
1779 let mut result = launch_child_in_slot(
1780 spec,
1781 &runtime.stderr_ring,
1782 &runtime.child_roster,
1783 prepared,
1784 runtime.register_timeout,
1785 );
1786 drop(_gate);
1787 if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
1788 (runtime.config_delivery.as_ref(), &result)
1789 {
1790 if let Some(base) = checked_base.filter(|_| code == "program_refused") {
1791 let module = spec.module_id.clone();
1792 let identity = subc_config::raw_digest(detail.as_bytes());
1793 let recorded = delivery
1794 .0
1795 .on_blocking(move |owner| owner.record_program_refusal(&module, &base, identity))
1796 .await;
1797 match recorded {
1798 Ok(true) => {}
1799 Ok(false) => result = Err(spawn_plan_stale(spec)),
1800 Err(error) => {
1801 result = Err(config_delivery::gate_hold_error(
1802 spec,
1803 error,
1804 Some(delivery),
1805 ))
1806 }
1807 }
1808 }
1809 }
1810 result
1811}
1812
1813fn validate_spawn_program(
1814 spec: &ModuleSpec,
1815 admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
1816 delivery: Option<config_delivery::SpawnDelivery<'_>>,
1817) -> Result<(), SuperviseError> {
1818 if let Some(admission) = admission {
1819 if let Some(program) = &admission.launch {
1820 if let Err(error) = program.validate_for_spawn() {
1821 if let (Some(context), Some(base)) = (delivery, admission.approved_base()) {
1825 if error.code == "program_refused"
1826 && !context.record_refusal(spec, base, &error.detail)?
1827 {
1828 return Err(spawn_plan_stale(spec));
1829 }
1830 }
1831 return Err(config_delivery::gate_hold_error(
1832 spec,
1833 error,
1834 delivery.map(|context| context.runtime()).as_ref(),
1835 ));
1836 }
1837 }
1838 }
1839 Ok(())
1840}
1841
1842#[allow(clippy::too_many_arguments)]
1843pub(super) fn prepare_child_in_slot(
1844 spec: &ModuleSpec,
1845 connection_file_path: Option<&std::path::Path>,
1846 handle: Option<&SupervisorHandle>,
1847 capture_logs_dir: Option<&std::path::Path>,
1848 roster: &ChildRoster,
1849 config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
1850 #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
1851 role: SpawnRole,
1852 alternate_slot: bool,
1853 asynchronous: bool,
1854) -> Result<PreparedChild, SuperviseError> {
1855 #[cfg(windows)]
1856 update_nonce_pipe_refusal(handle, spec, role, None);
1857 require_program_search_path(spec)?;
1858 let spawn_admission = config_delivery
1859 .map(|delivery| delivery.prepare(spec))
1860 .transpose()?;
1861 #[cfg(target_os = "macos")]
1862 let gated = spawn_admission
1863 .as_ref()
1864 .is_some_and(|admission| admission.approved_base().is_some());
1865 let mut launch_spec = spawn_admission
1866 .as_ref()
1867 .and_then(|admission| admission.launch.as_ref())
1868 .map(|launch| launch.spec.clone())
1869 .unwrap_or_else(|| spec.clone());
1870 if let Some(script) = &launch_spec.script {
1871 launch_spec.program =
1872 script::runner_path(script.runtime).map_err(|source| SuperviseError::Spawn {
1873 program: launch_spec.program.clone(),
1874 source,
1875 cgroup_path: None,
1876 })?;
1877 }
1878 let script_content = if let Some(entry) = &launch_spec.script {
1879 Some(
1880 spawn_admission
1881 .as_ref()
1882 .and_then(|admission| admission.launch.as_ref())
1883 .and_then(|launch| launch.script.clone())
1884 .map_or_else(|| script::ScriptBytes::read(&entry.path), Ok)
1885 .map_err(|error| config_delivery::gate_hold_error(&launch_spec, error, None))?,
1886 )
1887 } else {
1888 None
1889 };
1890 let spec = &launch_spec;
1891 if let Some(error) = recovery_block_error(spec, roster) {
1892 return Err(error);
1893 }
1894 if let Some((pid, reason)) = roster.previous_instance(&spec.module_id) {
1895 return Err(previous_instance_error(spec, pid, reason));
1896 }
1897 if roster.is_closed() {
1898 return Err(SuperviseError::Spawn {
1899 program: spec.program.clone(),
1900 source: io::Error::other("the daemon is shutting down; not starting a new process"),
1901 cgroup_path: None,
1902 });
1903 }
1904 let carried = containment::current(&roster.containment);
1905 let carrying = carries_containment(spec.carry_containment, carried.is_some());
1906 if role != SpawnRole::Plain && carrying {
1907 return Err(SuperviseError::InvalidSpec {
1908 reason: "a carried container cannot overlap a swap candidate".to_owned(),
1909 });
1910 }
1911 #[cfg(unix)]
1912 let launch_identity = if carrying && carried.is_none() {
1913 Some(
1914 containment::LaunchIdentity::capture().map_err(|source| SuperviseError::Spawn {
1915 program: spec.program.clone(),
1916 source,
1917 cgroup_path: None,
1918 })?,
1919 )
1920 } else {
1921 None
1922 };
1923 #[cfg(target_os = "linux")]
1924 let cgroup_placement = match &carried {
1925 Some(container) => container.cgroup().map(|(placement, _)| placement),
1926 None => cgroup_placement,
1927 };
1928 #[cfg(unix)]
1929 let group_target = if let Some(container) = carried
1930 .as_ref()
1931 .filter(|container| container.group().is_some())
1932 {
1933 containment::GroupTarget::Pinned(Arc::clone(container))
1934 } else {
1935 #[cfg(target_os = "linux")]
1936 let cgroup_container = carrying && cgroup_placement.is_some();
1937 #[cfg(not(target_os = "linux"))]
1938 let cgroup_container = false;
1939 if cgroup_container {
1940 containment::GroupTarget::NoGroup
1941 } else {
1942 containment::GroupTarget::OwnLeader
1943 }
1944 };
1945 #[cfg(target_os = "linux")]
1946 let cgroup_name = {
1947 if let Some((_, name)) = carried.as_ref().and_then(|container| container.cgroup()) {
1952 name.to_owned()
1953 } else if cgroup_placement.is_none() {
1954 swap::cgroup_name(&spec.module_id, alternate_slot)
1955 } else {
1956 let nonce = generate_launch_nonce()?;
1957 let suffix = u128::from_str_radix(&nonce[..32], 16).expect("hex launch nonce");
1958 cgroup_label::generation_label(&spec.module_id, alternate_slot, suffix)
1959 }
1960 };
1961 #[cfg(not(target_os = "linux"))]
1962 let _ = alternate_slot;
1963 #[cfg(windows)]
1964 let image_capture = windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
1965 program: spec.program.clone(),
1966 source,
1967 cgroup_path: None,
1968 })?;
1969 #[cfg(windows)]
1970 let program_binding = if asynchronous {
1971 let mut resolved = spec.clone();
1972 resolved.program = image_capture.path().to_path_buf();
1973 Some(SpawnProgramBinding::capture(&resolved)?)
1974 } else {
1975 None
1976 };
1977 #[cfg(not(windows))]
1978 let program_binding = (asynchronous || cfg!(target_os = "macos"))
1979 .then(|| SpawnProgramBinding::capture(spec))
1980 .transpose()?;
1981 #[cfg(target_os = "macos")]
1982 validate_spawn_program(spec, spawn_admission.as_ref(), config_delivery)?;
1983 #[cfg(target_os = "macos")]
1984 let (mut command, privacy_exec, exec_ack) = privacy_command(
1985 spec,
1986 program_binding
1987 .as_ref()
1988 .expect("macOS captures every launch"),
1989 roster,
1990 gated,
1994 )?;
1995 #[cfg(windows)]
1996 let mut command = Command::new(image_capture.path());
1997 #[cfg(not(any(target_os = "macos", windows)))]
1998 let mut command = Command::new(
1999 program_binding
2000 .as_ref()
2001 .map_or(spec.program.as_path(), |binding| binding.path.as_path()),
2002 );
2003 command.args(&spec.args);
2004 apply_child_env(&mut command, spec);
2034 if spec.script.is_some() {
2035 script::remove_runtime_env(&mut command, spec);
2036 }
2037 let origin_witness = crate::program_origin::LaunchWitness::capture_command(spec, &command)
2038 .map_err(|source| SuperviseError::Spawn {
2039 program: spec.program.clone(),
2040 source,
2041 cgroup_path: None,
2042 })?;
2043 command.current_dir(&origin_witness.working_directory);
2044 apply_spawn_role(&mut command, role);
2045 let nonce_handoff = apply_wire_spawn_args_for_admission(
2046 &mut command,
2047 spec,
2048 connection_file_path,
2049 handle,
2050 role,
2051 spawn_admission.as_ref(),
2052 )?;
2053 #[cfg(unix)]
2054 let mut slots = subc_os::registration_channel::ChildDescriptorSlots::default();
2055 command.env_remove(subc_os::script_pipe::SCRIPT_FD_ENV);
2056 let script_delivery = script_content
2057 .map(|content| {
2058 script::Delivery::prepare(
2059 content,
2060 &mut command,
2061 #[cfg(unix)]
2062 &mut slots,
2063 )
2064 })
2065 .transpose()
2066 .map_err(|source| SuperviseError::Spawn {
2067 program: spec.program.clone(),
2068 source,
2069 cgroup_path: None,
2070 })?;
2071 #[cfg(unix)]
2072 let registration_channel = if spec.protocol == ModuleProtocol::Subc {
2073 let (parent, child, metadata) = subc_os::registration_channel::registration_socketpair()
2074 .map_err(|source| SuperviseError::Spawn {
2075 program: spec.program.clone(),
2076 source,
2077 cgroup_path: None,
2078 })?;
2079 slots
2080 .channel(child)
2081 .map_err(|source| SuperviseError::Spawn {
2082 program: spec.program.clone(),
2083 source,
2084 cgroup_path: None,
2085 })?;
2086 command
2087 .env(subc_os::registration_channel::REGISTRATION_FD_ENV, metadata)
2088 .env(
2089 subc_os::registration_channel::DAEMON_PID_ENV,
2090 std::process::id().to_string(),
2091 );
2092 Some(parent)
2093 } else {
2094 None
2095 };
2096 #[cfg(windows)]
2097 let registration_channel = prepare_windows_registration_pipe(&mut command, spec)?;
2098 let binding_publication = if spawn_admission
2099 .as_ref()
2100 .is_some_and(|admission| admission.launch.is_some())
2101 {
2102 handle.and_then(|handle| handle.begin_program_binding(&spec.module_id, role))
2103 } else {
2104 None
2105 };
2106 let registration_spawn = (spec.protocol == ModuleProtocol::Subc)
2107 .then(|| {
2108 handle.map(|handle| {
2109 let spawn = RegistrationSpawn::new_with_binding_requirement(
2110 handle,
2111 &spec.module_id,
2112 role,
2113 binding_publication.clone(),
2114 spawn_admission
2115 .as_ref()
2116 .is_some_and(|admission| admission.launch.is_some()),
2117 );
2118 if let Some(admission) = &spawn_admission {
2119 admission.initialize_origin(&spawn.authority, &origin_witness);
2120 }
2121 handle.record_nonce_launch(&spawn);
2122 spawn
2123 })
2124 })
2125 .flatten();
2126
2127 #[cfg(target_os = "linux")]
2128 let cgroup_path = cgroup_placement
2129 .map(|placement| {
2130 if let Some(container) = &carried {
2131 let path = container
2132 .cgroup_path()
2133 .ok_or_else(|| io::Error::other("carried container has no cgroup path"))?;
2134 placement.existing_module_path(path)?.ok_or_else(|| {
2135 io::Error::new(
2136 io::ErrorKind::NotFound,
2137 "carried cgroup disappeared before replacement",
2138 )
2139 })
2140 } else {
2141 if carrying {
2142 containment::prepare_cgroup_path(placement, &cgroup_name)
2143 } else {
2144 placement.module_path(&cgroup_name)
2145 }
2146 }
2147 })
2148 .transpose()
2149 .map_err(|source| SuperviseError::Cgroup {
2150 module_id: spec.module_id.clone(),
2151 source,
2152 })?;
2153 #[cfg(not(target_os = "linux"))]
2154 let cgroup_path: Option<PathBuf> = None;
2155 #[cfg(target_os = "linux")]
2158 let cgroup_cleanup = PreparedCgroup(
2159 cgroup_placement
2160 .filter(|_| carried.is_none())
2161 .map(|placement| (placement.clone(), cgroup_name.clone())),
2162 );
2163 #[cfg(unix)]
2164 let mut admission_gate = if carrying {
2165 Some(
2166 admission::Gate::install(&mut command, spec, roster).map_err(|source| {
2167 SuperviseError::Spawn {
2168 program: spec.program.clone(),
2169 source,
2170 cgroup_path: cgroup_path.clone(),
2171 }
2172 })?,
2173 )
2174 } else {
2175 None
2176 };
2177 #[cfg(target_os = "linux")]
2178 if let Some(path) = &cgroup_path {
2179 apply_cgroup_placement(&mut command, spec, path)?;
2180 }
2181
2182 let output_sink = capture_sink(spec, capture_logs_dir);
2183
2184 command.stdout(Stdio::piped());
2185 command.stderr(Stdio::piped());
2186 command.kill_on_drop(!carrying);
2187 #[cfg(unix)]
2204 command.process_group(
2205 carried
2206 .as_ref()
2207 .map(|container| container.verified_join_group())
2208 .transpose()
2209 .map_err(|source| SuperviseError::Spawn {
2210 program: spec.program.clone(),
2211 source,
2212 cgroup_path: cgroup_path.clone(),
2213 })?
2214 .flatten()
2215 .unwrap_or(0) as i32,
2216 );
2217 command.stdin(Stdio::null());
2218 #[cfg(unix)]
2219 if let Some(gate) = &mut admission_gate {
2220 gate.install_placement(&mut command);
2221 }
2222 #[cfg(unix)]
2225 {
2226 if let Some(handoff) = nonce_handoff {
2227 slots.nonce(handoff);
2228 }
2229 #[cfg(target_os = "macos")]
2230 slots
2231 .acknowledgement(exec_ack.into_descriptor())
2232 .map_err(|source| SuperviseError::Spawn {
2233 program: spec.program.clone(),
2234 source,
2235 cgroup_path: cgroup_path.clone(),
2236 })?;
2237 slots.install(command.as_std_mut());
2238 }
2239 #[cfg(not(any(unix, windows)))]
2240 let _ = nonce_handoff;
2241
2242 #[cfg(windows)]
2247 {
2248 subc_jobobject::ensure_root_job().map_err(|source| SuperviseError::Spawn {
2249 program: spec.program.clone(),
2250 source,
2251 cgroup_path: None,
2252 })?;
2253 subc_jobobject::suspend_on_create_async(&mut command);
2254 }
2255 let spawned_at = Instant::now();
2259 let delivery_context = config_delivery;
2260 let config_delivery = config_delivery
2261 .map(|delivery| {
2262 delivery.spawned(
2263 spec,
2264 spawn_admission
2265 .as_ref()
2266 .expect("delivery prepares spawn admission"),
2267 spawned_at,
2268 role,
2269 registration_spawn
2270 .as_ref()
2271 .map(|spawn| spawn.authority.clone()),
2272 )
2273 })
2274 .transpose()?
2275 .flatten();
2276 let mut delivery_registration =
2277 delivery_context.map(|context| context.registration_guard(config_delivery.as_ref(), role));
2278 if let Some(registration) = &mut delivery_registration {
2279 registration.defer_cleanup();
2280 }
2281 if asynchronous {
2282 #[cfg(test)]
2283 if let Some(context) = delivery_context {
2284 context.pause_preflight_for_test();
2285 }
2286 }
2287 validate_spawn_program(spec, spawn_admission.as_ref(), delivery_context)?;
2288 Ok(PreparedChild {
2289 script_delivery,
2290 registration_spawn,
2291 registration_handle: handle.cloned(),
2292 #[cfg(any(unix, windows))]
2293 registration_channel,
2294 config_context: delivery_context.map(|delivery| delivery.runtime()),
2295 binding_publication,
2296 launch_spec,
2297 spawn_admission,
2298 command,
2299 carrying,
2300 carried: carried.clone(),
2301 #[cfg(unix)]
2302 launch_identity,
2303 #[cfg(unix)]
2304 group_target,
2305 #[cfg(target_os = "linux")]
2306 cgroup_placement: cgroup_placement.cloned(),
2307 #[cfg(target_os = "linux")]
2308 cgroup_cleanup,
2309 #[cfg(target_os = "linux")]
2310 cgroup_name,
2311 cgroup_path,
2312 #[cfg(unix)]
2313 admission_gate,
2314 output_sink,
2315 #[cfg(target_os = "macos")]
2316 privacy_exec,
2317 #[cfg(windows)]
2318 image_capture,
2319 #[cfg(windows)]
2320 nonce_handoff,
2321 #[cfg(windows)]
2322 role,
2323 spawned_at,
2324 config_delivery,
2325 delivery_registration,
2326 program_binding,
2327 })
2328}
2329
2330pub(super) fn launch_child_in_slot(
2331 _spec: &ModuleSpec,
2332 ring: &Arc<Mutex<StderrRing>>,
2333 roster: &ChildRoster,
2334 prepared: PreparedChild,
2335 register_timeout: Duration,
2336) -> Result<SupervisedChild, SuperviseError> {
2337 let launch_spec = prepared.launch_spec.clone();
2338 let registration_declaration = prepared
2339 .spawn_admission
2340 .as_ref()
2341 .and_then(|admission| admission.registration_declaration(&launch_spec.module_id));
2342 let admission_base = prepared
2343 .spawn_admission
2344 .as_ref()
2345 .and_then(|admission| admission.approved_base())
2346 .cloned();
2347 let spec = &launch_spec;
2348 let expected_image = prepared
2349 .spawn_admission
2350 .as_ref()
2351 .and_then(|admission| admission.launch.as_ref())
2352 .map(|launch| launch.image);
2353 let program_launch = prepared
2354 .spawn_admission
2355 .and_then(|admission| admission.launch);
2356 let config_owner = prepared
2357 .config_context
2358 .as_ref()
2359 .map(|context| context.0.clone());
2360 let binding_publication = prepared.binding_publication;
2361 #[cfg(test)]
2362 if let Some(context) = &prepared.config_context {
2363 context.0.before_spawn_exec_for_test();
2364 }
2365 #[cfg(feature = "test-support")]
2366 if let Some(context) = &prepared.config_context {
2367 context
2368 .0
2369 .pause_spawn_before_exec()
2370 .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(context)))?;
2371 }
2372 let mut command = prepared.command;
2373 let carrying = prepared.carrying;
2374 let carried = prepared.carried;
2375 #[cfg(unix)]
2376 let launch_identity = prepared.launch_identity;
2377 #[cfg(unix)]
2378 let group_target = prepared.group_target;
2379 #[cfg(target_os = "linux")]
2380 let cgroup_placement = prepared.cgroup_placement.as_ref();
2381 #[cfg(target_os = "linux")]
2382 let cgroup_name = prepared.cgroup_name;
2383 #[cfg(target_os = "linux")]
2384 let mut cgroup_cleanup = prepared.cgroup_cleanup;
2385 #[cfg(target_os = "linux")]
2386 let _ = cgroup_cleanup.0.take();
2387 let cgroup_path = prepared.cgroup_path;
2388 #[cfg(unix)]
2389 let admission_gate = prepared.admission_gate;
2390 let output_sink = prepared.output_sink;
2391 #[cfg(target_os = "macos")]
2392 let mut privacy_exec = prepared.privacy_exec;
2393 #[cfg(target_os = "macos")]
2394 if let Some(pending) = &mut privacy_exec {
2395 pending.admission_binding = binding_publication.clone();
2396 if expected_image.is_some() {
2397 pending.expected = expected_image;
2398 }
2399 }
2400 #[cfg(any(unix, windows))]
2401 let registration_channel = prepared.registration_channel;
2402 let registration_spawn = prepared.registration_spawn;
2403 let registration_handle = prepared.registration_handle;
2404 #[cfg(windows)]
2405 let image_capture = prepared.image_capture;
2406 #[cfg(windows)]
2407 let nonce_handoff = prepared.nonce_handoff;
2408 #[cfg(windows)]
2409 let role = prepared.role;
2410 let spawned_at = prepared.spawned_at;
2411 let config_delivery = prepared.config_delivery;
2412 let delivery_registration = prepared.delivery_registration;
2413 let _program_binding = prepared.program_binding;
2414 #[cfg(all(test, unix))]
2415 containment_tests::record_spawn_attempt(spec, &mut command);
2416 #[cfg(unix)]
2417 let spawned = match admission_gate {
2418 Some(gate) => gate
2419 .spawn(
2420 command,
2421 spec,
2422 roster,
2423 launch_identity,
2424 #[cfg(target_os = "linux")]
2425 cgroup_placement
2426 .zip(cgroup_path.as_ref())
2427 .map(|(placement, path)| {
2428 (placement.clone(), cgroup_name.clone(), path.clone())
2429 }),
2430 )
2431 .map(|(child, admitted)| (child, Some(admitted))),
2432 None => {
2433 let spawned =
2434 subc_os::child_spawn::tokio_spawn(&mut command).map(|child| (child, None));
2435 drop(command);
2438 spawned
2439 }
2440 };
2441 #[cfg(not(unix))]
2442 let spawned = subc_os::child_spawn::tokio_spawn(&mut command);
2443 let spawned = match spawned {
2444 Ok(child) => child,
2445 Err(source) => {
2446 if carried
2447 .as_ref()
2448 .and_then(|container| container.group())
2449 .is_some()
2450 {
2451 containment::terminate_blocking(&roster.containment);
2452 }
2453 #[cfg(target_os = "linux")]
2454 if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2455 remove_module_cgroup(placement, &cgroup_name);
2456 }
2457 return Err(SuperviseError::Spawn {
2458 program: spec.program.clone(),
2459 source,
2460 cgroup_path,
2461 });
2462 }
2463 };
2464 #[cfg(unix)]
2465 let (mut child, mut admitted) = spawned;
2466 #[cfg(unix)]
2467 let group_target = admitted
2468 .as_ref()
2469 .map(|attempt| attempt.group_target())
2470 .unwrap_or(group_target);
2471 #[cfg(not(unix))]
2472 let mut child = spawned;
2473 if let Some(delivery) = prepared.script_delivery {
2474 delivery.start(child.id().expect("spawned child has a pid"));
2475 }
2476 #[cfg(test)]
2477 spawn_record_tests::after_create(&child, spec);
2478
2479 #[cfg(windows)]
2484 let windows_image = match image_capture.bind_tokio(&child) {
2485 Ok(image) => Arc::new(image),
2486 Err(source) => {
2487 kill_and_reap_rejected_child(&mut child);
2488 return Err(SuperviseError::Spawn {
2489 program: spec.program.clone(),
2490 source,
2491 cgroup_path: None,
2492 });
2493 }
2494 };
2495 #[cfg(windows)]
2498 let job = contain_spawned_child(&mut child, spec, carried.as_ref())?;
2499 let spawned_at_ms = unix_ms_now();
2500 #[cfg(not(windows))]
2501 let spawned_from = spec.program.clone();
2502 #[cfg(windows)]
2503 let spawned_from = windows_image.path().to_path_buf();
2504 #[cfg(not(windows))]
2505 let spawned_file_identity = spawned_file_identity(&spawned_from);
2506 #[cfg(windows)]
2507 let spawned_file_identity = Some(SpawnedFileIdentity {
2508 device: 0,
2509 inode: 0,
2510 windows_image: Some(Arc::clone(&windows_image)),
2511 });
2512 let pid = child.id().ok_or_else(|| SuperviseError::Spawn {
2513 program: spec.program.clone(),
2514 source: io::Error::other("spawned child exposed no live pid"),
2515 cgroup_path: cgroup_path.clone(),
2516 })?;
2517 #[cfg(unix)]
2518 let plain_group = (!carrying
2519 && cgroup_path.is_none()
2520 && matches!(group_target, containment::GroupTarget::OwnLeader))
2521 .then(|| plain_group::PlainGroup::from_spawn(pid).map(Arc::new))
2522 .flatten();
2523 #[cfg(not(windows))]
2524 let process_start_time = admitted
2525 .as_ref()
2526 .map(|admitted| admitted.birth)
2527 .or_else(|| crate::provenance::process_start_time(pid));
2528 #[cfg(windows)]
2529 let process_start_time = Some(windows_image.start_time());
2530 let process_identity = process_start_time.map(|start_time| ProcessIdentity { pid, start_time });
2531 #[cfg(all(test, target_os = "macos"))]
2532 privacy_exec_boundary_tests::before_image_sample(spec, pid);
2533 #[cfg(all(test, target_os = "linux"))]
2534 assert!(roster.admission_event_for_test(&spec.module_id, "before_image_binding", Some(pid)));
2535 #[cfg(not(windows))]
2540 let recorded_image = observe_spawned_image(pid);
2541 #[cfg(all(test, target_os = "linux"))]
2542 let recorded_image = if roster.admission_event_for_test(
2543 &spec.module_id,
2544 "after_spawn_image_sample",
2545 Some(pid),
2546 ) {
2547 recorded_image
2548 } else {
2549 None
2550 };
2551 #[cfg(target_os = "linux")]
2552 let exited_before_binding = expected_image.is_some()
2555 && recorded_image.and_then(|image| image.executable) != expected_image
2556 && subc_os::child_exit::observe(pid).ok().flatten().is_some();
2557 #[cfg(target_os = "linux")]
2558 let unavailable_initial_image = expected_image.is_some()
2559 && recorded_image.and_then(|image| image.executable).is_none()
2560 && !exited_before_binding;
2561 #[cfg(not(target_os = "linux"))]
2562 let unavailable_initial_image = false;
2563 #[cfg(target_os = "linux")]
2564 if expected_image
2565 .is_some_and(|expected| recorded_image.and_then(|image| image.executable) != Some(expected))
2566 && !exited_before_binding
2567 && !unavailable_initial_image
2568 {
2569 kill_module_cgroup(cgroup_placement, &cgroup_name);
2570 kill_and_reap_rejected_child(&mut child, group_target.clone());
2571 return Err(SuperviseError::ConfigHeld {
2572 module_id: spec.module_id.clone(),
2573 code: "program_refused".into(),
2574 detail: format!(
2575 "spawned executable {:?} does not match hashed program {:?}",
2576 recorded_image.and_then(|image| image.executable),
2577 expected_image
2578 ),
2579 });
2580 }
2581 #[cfg(not(target_os = "linux"))]
2582 let _ = expected_image;
2583 #[cfg(target_os = "macos")]
2584 let binding_ready = privacy_exec.is_none();
2585 #[cfg(target_os = "linux")]
2586 let binding_ready = !exited_before_binding;
2587 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
2588 let binding_ready = cfg!(windows);
2589 #[cfg(target_os = "macos")]
2593 let recorded_image = if privacy_exec.is_some() {
2594 None
2595 } else {
2596 recorded_image
2597 };
2598 #[cfg(target_os = "linux")]
2599 let recorded_cgroup_name = cgroup_path.as_ref().map(|_| cgroup_name.clone());
2600 #[cfg(not(target_os = "linux"))]
2601 let recorded_cgroup_name = None;
2602 #[cfg(unix)]
2603 let preadmitted = admitted
2604 .as_mut()
2605 .and_then(|admitted| admitted.leader.take());
2606 #[cfg(not(unix))]
2607 let preadmitted: Option<crate::child_roster::RosterGuard> = None;
2608 #[cfg(all(test, windows))]
2609 spawn_record_tests::before_roster_admit(spec);
2610 let roster_guard = if let Some(guard) = preadmitted {
2611 Ok(guard)
2612 } else {
2613 roster.admit(
2614 spec.module_id.clone(),
2615 pid,
2616 spec.protocol,
2617 process_start_time,
2618 crate::child_roster::RecordedIdentity {
2619 #[cfg(target_os = "linux")]
2620 container: cgroup_path
2621 .clone()
2622 .filter(|_| !carrying)
2623 .map(ordinary_cgroup::recorded_identity),
2624 #[cfg(not(target_os = "linux"))]
2625 container: None,
2626 #[cfg(unix)]
2627 carried: None,
2628 #[cfg(unix)]
2629 plain_group: plain_group.as_ref().map(Arc::downgrade),
2630 #[cfg(not(windows))]
2631 start_time: recorded_image.map(|image| image.start_time),
2632 #[cfg(windows)]
2633 start_time: process_start_time,
2634 #[cfg(not(windows))]
2635 executable: recorded_image
2636 .and_then(|image| image.executable)
2637 .map(crate::live_children::ExecutableIdentity::from),
2638 #[cfg(windows)]
2639 executable: Some(crate::live_children::ExecutableIdentity::from(
2640 windows_image.identity(),
2641 )),
2642 cgroup_name: recorded_cgroup_name,
2643 #[cfg(target_os = "linux")]
2644 cgroup_placement: cgroup_placement.cloned(),
2645 },
2646 )
2647 };
2648 let roster_guard = match roster_guard {
2649 Ok(guard) => guard,
2650 Err(failure) => {
2651 return failure.with_cleanup(|source| {
2652 #[cfg(windows)]
2653 if let Some(job) = &job {
2654 let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
2655 }
2656 #[cfg(target_os = "linux")]
2657 kill_module_cgroup(cgroup_placement, &cgroup_name);
2658 #[cfg(unix)]
2659 let rejected_group = group_target.clone();
2660 kill_and_reap_rejected_child(
2661 &mut child,
2662 #[cfg(unix)]
2663 rejected_group,
2664 );
2665 #[cfg(target_os = "linux")]
2666 if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2667 remove_module_cgroup(placement, &cgroup_name);
2668 }
2669 Err(SuperviseError::Spawn {
2670 program: spec.program.clone(),
2671 source: io::Error::other(format!(
2672 "could not durably record module child: {source}"
2673 )),
2674 cgroup_path,
2675 })
2676 });
2677 }
2678 };
2679 #[cfg(unix)]
2680 if admitted.is_some() {
2681 if let Some(image) = recorded_image {
2682 if let Err(source) = roster_guard.confirm_executable(image) {
2683 kill_and_reap_rejected_child(&mut child, group_target.clone());
2684 return Err(SuperviseError::Spawn {
2685 program: spec.program.clone(),
2686 source,
2687 cgroup_path,
2688 });
2689 }
2690 }
2691 }
2692 if roster.is_closed() {
2697 if carrying {
2698 #[cfg(unix)]
2699 let rejected_group = admitted
2700 .as_ref()
2701 .map(|admitted| admitted.rejection_target())
2702 .unwrap_or_else(|| group_target.clone());
2703 #[cfg(windows)]
2704 if let Some(job) = &job {
2705 let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
2706 }
2707 kill_and_reap_rejected_child(
2708 &mut child,
2709 #[cfg(unix)]
2710 rejected_group,
2711 );
2712 #[cfg(all(test, unix))]
2713 let _ =
2714 roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
2715 drop(roster_guard);
2716 return Err(SuperviseError::Spawn {
2717 program: spec.program.clone(),
2718 source: io::Error::other(
2719 "the daemon began shutting down during carried admission; ended the container",
2720 ),
2721 cgroup_path,
2722 });
2723 }
2724 #[cfg(target_os = "linux")]
2726 kill_module_cgroup(cgroup_placement, &cgroup_name);
2727 if let Err(error) = child.start_kill() {
2728 debug!(module_id = %spec.module_id, pid, %error, "kill of a process spawned during daemon shutdown failed; it may already have exited");
2729 }
2730 #[cfg(target_os = "linux")]
2731 if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
2732 while matches!(child.try_wait(), Ok(None)) {
2736 std::thread::yield_now();
2737 }
2738 if matches!(
2739 subc_cgroup::kill_module(Some(placement), &cgroup_name),
2740 subc_cgroup::KillOutcome::Killed
2741 ) {
2742 if let Ok(path) = placement.module_path(&cgroup_name) {
2743 while std::fs::read_to_string(path.join("cgroup.events"))
2744 .ok()
2745 .is_some_and(|events| events.lines().any(|line| line == "populated 1"))
2746 {
2747 std::thread::yield_now();
2748 }
2749 }
2750 }
2751 remove_module_cgroup(placement, &cgroup_name);
2752 }
2753 drop(roster_guard);
2754 return Err(SuperviseError::Spawn {
2755 program: spec.program.clone(),
2756 source: io::Error::other(
2757 "the daemon began shutting down while this process was starting; ended it",
2758 ),
2759 cgroup_path,
2760 });
2761 }
2762
2763 let pumps = crate::child_output::start(
2764 &mut child,
2765 output_sink,
2766 ring,
2767 &spec.module_id,
2768 #[cfg(unix)]
2769 plain_group.is_some(),
2770 );
2771
2772 let exec = Arc::new(crate::activity::ExecOutcome::new());
2773 #[cfg(target_os = "macos")]
2774 let pending_exec = privacy_exec.is_some();
2775 #[cfg(not(target_os = "macos"))]
2776 let pending_exec = false;
2777 if !pending_exec {
2778 exec.finish(crate::activity::ExecState::CommittedExec);
2779 }
2780 #[cfg(windows)]
2781 let subtree_target = job
2782 .as_ref()
2783 .map(|job| crate::subtree_resources::Target::Job(Arc::downgrade(job)))
2784 .unwrap_or(crate::subtree_resources::Target::Unavailable("no_job"));
2785 #[cfg(target_os = "linux")]
2786 let subtree_target = cgroup_path
2787 .map(crate::subtree_resources::Target::Cgroup)
2788 .unwrap_or(crate::subtree_resources::Target::Unavailable("no_cgroup"));
2789 #[cfg(not(any(target_os = "linux", windows)))]
2790 let subtree_target = crate::subtree_resources::Target::Unavailable("unsupported_platform");
2791 let mut supervised = SupervisedChild {
2792 registration_spawn,
2793 #[cfg(any(unix, windows))]
2794 registration_channel,
2795 live_program_binding: None,
2796 registered_config_connection: None,
2797 admission_base,
2798 registration_declaration,
2799 _program_binding: binding_publication,
2800 subtree_target,
2801 child: containment::ProcessChild::plain(child, pid),
2802 exec: crate::activity::ExecOwner(exec),
2803 #[cfg(windows)]
2804 nonce_delivery: None,
2805 protocol: spec.protocol,
2806 #[cfg(target_os = "linux")]
2807 module_id: cgroup_name,
2808 #[cfg(target_os = "linux")]
2809 cgroup_placement: cgroup_placement.cloned(),
2810 #[cfg(target_os = "linux")]
2811 unresolved_cgroup: None,
2812 #[cfg(windows)]
2813 job,
2814 stdout_pump: pumps.stdout,
2815 stderr_pump: pumps.stderr,
2816 #[cfg(unix)]
2817 capture_stop: pumps.stop,
2818 #[cfg(unix)]
2819 late_output_lost: false,
2820 stderr_ring: Arc::clone(ring),
2821 spawned_at,
2822 config_delivery,
2823 registration_deadline: None,
2824 registration_watch: None,
2825 spawned_at_ms,
2826 spawned_from,
2827 launch_spec_digest: LaunchSpecDigest::from_spec(spec),
2828 spawned_file_identity,
2829 process_start_time,
2830 process_identity,
2831 pid,
2832 roster_guard: Some(roster_guard),
2833 #[cfg(target_os = "macos")]
2834 privacy_exec,
2835 #[cfg(target_os = "macos")]
2836 report_ready: Arc::new(OnceLock::new()),
2837 spawn_failure: None,
2838 admission_kill_sent: false,
2839 };
2840 #[cfg(unix)]
2841 {
2842 supervised.child.plain_group = plain_group;
2843 }
2844 if let Err(error) = containment::adopt(&mut supervised, spec, roster) {
2845 supervised.child.reject(
2846 #[cfg(unix)]
2847 group_target,
2848 );
2849 #[cfg(all(test, unix))]
2850 let _ = roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
2851 return Err(error);
2852 }
2853 if let (Some(launch), Some(owner), Some(base)) = (
2854 program_launch,
2855 config_owner,
2856 supervised.admission_base.clone(),
2857 ) {
2858 supervised.live_program_binding =
2859 content_binding::LiveProgramBinding::new(launch, &supervised, owner, base);
2860 if let (Some(publication), Some(live)) = (
2861 &supervised._program_binding,
2862 &supervised.live_program_binding,
2863 ) {
2864 publication.attach(live);
2865 }
2866 }
2867 #[cfg(unix)]
2868 if let Some(admitted) = admitted.take() {
2869 admitted.disarm();
2870 }
2871 #[cfg(windows)]
2872 {
2873 if let Some(handoff) = nonce_handoff {
2874 match handoff.serve(pid, REGISTRY_RELEASE_TIMEOUT) {
2878 Ok(delivery) => supervised.nonce_delivery = Some(delivery),
2879 Err(source) => {
2880 supervised.child.reject();
2881 update_nonce_pipe_refusal(
2882 registration_handle.as_ref(),
2883 spec,
2884 role,
2885 Some("launch_nonce_pipe_serve_failed"),
2886 );
2887 return Err(windows_nonce_pipe_error(spec, "start serving", source));
2888 }
2889 }
2890 }
2891 if let Err(error) = resume_suspended_child(pid, spec) {
2892 containment::terminate_blocking(&roster.containment);
2893 let _ = supervised.child.start_kill();
2894 return Err(error);
2895 }
2896 }
2897 if binding_ready {
2898 let checked = if unavailable_initial_image {
2902 Err(crate::config_gate::GateError::new(
2903 "config_delivery_deferred",
2904 "initial process image is unavailable",
2905 ))
2906 } else {
2907 match (
2908 &supervised._program_binding,
2909 &supervised.live_program_binding,
2910 ) {
2911 (Some(binding), _) => binding.verify(),
2912 (None, Some(live)) => live.check(),
2913 _ if supervised.admission_base.is_some() => {
2914 Err(crate::config_gate::GateError::new(
2915 "config_delivery_deferred",
2916 "live program witness is unavailable",
2917 ))
2918 }
2919 _ => Ok(()),
2920 }
2921 };
2922 #[cfg(all(test, target_os = "linux"))]
2923 let checked = if roster.admission_event_for_test(
2924 &spec.module_id,
2925 "after_content_witness_check",
2926 Some(pid),
2927 ) {
2928 checked
2929 } else {
2930 Err(crate::config_gate::GateError::new(
2931 "config_delivery_deferred",
2932 "current process image is unavailable",
2933 ))
2934 };
2935 if let Err(error) = checked {
2936 if let Some(binding) = &mut supervised._program_binding {
2937 binding.reject();
2938 }
2939 if error.code == "program_refused" || supervised.try_wait().ok().flatten().is_none() {
2942 supervised.spawn_failure = Some(format!("{}: {}", error.code, error.detail));
2943 #[cfg(all(test, target_os = "linux"))]
2944 assert!(roster.admission_event_for_test(
2945 &spec.module_id,
2946 if unavailable_initial_image {
2947 "before_initial_image_kill"
2948 } else {
2949 "before_content_witness_kill"
2950 },
2951 Some(pid),
2952 ));
2953 let _ = supervised.start_admission_kill();
2954 #[cfg(all(test, target_os = "linux"))]
2955 if supervised.admission_kill_sent {
2956 assert!(roster.admission_event_for_test(
2957 &spec.module_id,
2958 "after_admission_kill_sent",
2959 Some(pid),
2960 ));
2961 }
2962 }
2963 }
2964 }
2965 if let Some(registration) = delivery_registration {
2966 registration.commit();
2967 }
2968 if let Some(spawn) = &supervised.registration_spawn {
2969 if let Some(record) = supervised
2970 .roster_guard
2971 .as_ref()
2972 .and_then(crate::child_roster::RosterGuard::resume_token_record)
2973 {
2974 let _ = spawn.resume_token_record.set(record);
2975 }
2976 if let Some(identity) = supervised.process_identity {
2977 let _ = spawn.identity.set(identity);
2978 }
2979 if supervised.spawn_failure.is_some() {
2980 spawn.refuse();
2981 } else if binding_ready {
2982 spawn.ready();
2983 }
2984 #[cfg(any(unix, windows))]
2985 if let (Some(handle), Some(channel)) =
2986 (registration_handle, supervised.registration_channel.take())
2987 {
2988 handle.serve_registration(channel, spawn.clone(), pid, spawned_at + register_timeout);
2989 }
2990 }
2991 Ok(supervised)
2992}
2993
2994#[cfg(target_os = "linux")]
2995pub(crate) fn kill_module_cgroup(placement: Option<&subc_cgroup::Placement>, module_id: &str) {
2996 use subc_cgroup::KillOutcome;
2997 match subc_cgroup::kill_module(placement, module_id) {
2998 KillOutcome::Killed => {}
2999 KillOutcome::NotPlaced | KillOutcome::Unsupported => {
3000 debug!(
3001 module_id,
3002 "cgroup tree kill unavailable; using direct-child kill"
3003 );
3004 }
3005 KillOutcome::IoError { path, error } => {
3006 warn!(module_id, path = %path.display(), %error, "cgroup tree kill failed; using direct-child kill");
3007 }
3008 }
3009}
3010
3011#[cfg(windows)]
3019fn contain_spawned_child(
3020 child: &mut Child,
3021 spec: &ModuleSpec,
3022 carried: Option<&Arc<containment::CarriedContainment>>,
3023) -> Result<Option<Arc<Mutex<subc_jobobject::JobObject>>>, SuperviseError> {
3024 let assignment = || {
3025 let job = match carried {
3026 Some(container) => container.job(),
3027 None => Arc::new(Mutex::new(subc_jobobject::JobObject::new()?)),
3028 };
3029 #[cfg(test)]
3030 spawn_record_tests::assignment_failpoint(spec)?;
3031 job.lock()
3032 .unwrap_or_else(|p| p.into_inner())
3033 .assign(child)?;
3034 Ok::<_, io::Error>(job)
3035 };
3036 match assignment() {
3037 Ok(job) => Ok(Some(job)),
3038 Err(source) => {
3039 kill_and_reap_rejected_child(child);
3040 Err(SuperviseError::Spawn {
3041 program: spec.program.clone(),
3042 source: io::Error::other(format!(
3043 "Windows module job containment failed: {source}"
3044 )),
3045 cgroup_path: None,
3046 })
3047 }
3048 }
3049}
3050
3051pub(super) fn kill_and_reap_rejected_child(
3054 child: &mut Child,
3055 #[cfg(unix)] group: containment::GroupTarget,
3056) {
3057 #[cfg(unix)]
3058 group.signal_rejected(child);
3059 let _ = child.start_kill();
3060 while matches!(child.try_wait(), Ok(None)) {
3061 std::thread::yield_now();
3062 }
3063}
3064
3065#[cfg(windows)]
3070fn resume_suspended_child(pid: u32, spec: &ModuleSpec) -> Result<(), SuperviseError> {
3071 if let Err(source) = subc_jobobject::resume_main_thread(pid) {
3072 let _ = subc_os::child_spawn::status(
3076 std::process::Command::new("taskkill.exe")
3077 .args(["/PID", &pid.to_string(), "/T", "/F"])
3078 .stdin(Stdio::null())
3079 .stdout(Stdio::null())
3080 .stderr(Stdio::null()),
3081 );
3082 return Err(SuperviseError::Spawn {
3083 program: spec.program.clone(),
3084 source,
3085 cgroup_path: None,
3086 });
3087 }
3088 Ok(())
3089}
3090
3091#[cfg(target_os = "linux")]
3092pub(super) fn remove_module_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
3093 match placement.remove_module(module_id) {
3094 Ok(()) => debug!(module_id, "removed module cgroup after process exit"),
3095 Err(error) => warn!(
3096 module_id,
3097 error = %error,
3098 "could not remove module cgroup after process exit; continuing teardown"
3099 ),
3100 }
3101}
3102
3103#[cfg(target_os = "linux")]
3104pub(super) fn apply_cgroup_placement(
3105 command: &mut Command,
3106 spec: &ModuleSpec,
3107 path: &std::path::Path,
3108) -> Result<(), SuperviseError> {
3109 subc_cgroup::apply(command, path).map_err(|source| SuperviseError::Cgroup {
3110 module_id: spec.module_id.clone(),
3111 source,
3112 })
3113}
3114
3115fn capture_retention(spec: &ModuleSpec) -> Retention {
3116 let defaults = Retention::default();
3117 let value = |name: &str| {
3118 spec.env
3119 .iter()
3120 .rev()
3121 .find_map(|(key, value)| (key == name).then_some(value.as_str()))
3122 };
3123 Retention {
3124 max_file_mb: value(CAPTURE_MAX_FILE_MB_ENV)
3125 .and_then(|value| value.parse().ok())
3126 .unwrap_or(defaults.max_file_mb),
3127 keep: value(CAPTURE_KEEP_ENV)
3128 .and_then(|value| value.parse().ok())
3129 .unwrap_or(defaults.keep),
3130 max_age_days: value(CAPTURE_MAX_AGE_DAYS_ENV)
3131 .and_then(|value| value.parse().ok())
3132 .unwrap_or(defaults.max_age_days),
3133 }
3134}
3135
3136pub(super) fn capture_sink(
3137 spec: &ModuleSpec,
3138 logs_dir: Option<&std::path::Path>,
3139) -> ChildOutputSink {
3140 let Some(logs_dir) = logs_dir else {
3141 return ChildOutputSink::Stderr;
3142 };
3143 let path = logs_dir.join(format!("{}.stderr.log", spec.module_id));
3144 match ChildOutputSink::open(&path, capture_retention(spec)) {
3145 Ok(sink) => sink,
3146 Err(error) => {
3147 warn!(module_id = %spec.module_id, path = %path.display(), %error,
3148 "could not open child output capture file; forwarding to stderr");
3149 ChildOutputSink::Stderr
3150 }
3151 }
3152}
3153
3154fn generate_launch_nonce() -> Result<String, SuperviseError> {
3157 let mut bytes = [0u8; 32];
3158 getrandom::getrandom(&mut bytes).map_err(|source| SuperviseError::LaunchNonce {
3159 reason: source.to_string(),
3160 })?;
3161 let mut hex = String::with_capacity(64);
3162 for b in bytes {
3163 use std::fmt::Write;
3164 let _ = write!(hex, "{b:02x}");
3165 }
3166 Ok(hex)
3167}
3168
3169#[cfg(not(windows))]
3173pub(super) fn observe_spawned_image(pid: u32) -> Option<subc_os::Observation> {
3174 let process = subc_os::Process::open(pid).ok().flatten()?;
3175 #[cfg(target_os = "linux")]
3176 return sample_after_linux_exec(
3177 || {
3178 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
3179 let committed = linux_exec_committed(&stat);
3180 #[cfg(test)]
3181 spawn_image_tests::report_exec_state(committed);
3182 committed
3183 },
3184 || process.observe(),
3185 );
3186 #[cfg(not(target_os = "linux"))]
3187 process.observe()
3188}
3189
3190#[cfg(target_os = "linux")]
3194pub(super) fn linux_exec_committed(stat: &str) -> Option<bool> {
3195 const PF_FORKNOEXEC: u64 = 0x40;
3196 let flags = stat.rsplit_once(')')?.1.split_whitespace().nth(6)?;
3197 Some(flags.parse::<u64>().ok()? & PF_FORKNOEXEC == 0)
3198}
3199
3200#[cfg(target_os = "linux")]
3201pub(super) fn sample_after_linux_exec(
3202 mut exec_committed: impl FnMut() -> Option<bool>,
3203 observe: impl FnOnce() -> Option<subc_os::Observation>,
3204) -> Option<subc_os::Observation> {
3205 let deadline = std::time::Instant::now() + Duration::from_secs(1);
3206 while !exec_committed()? {
3207 if std::time::Instant::now() >= deadline {
3211 return None;
3212 }
3213 std::thread::sleep(Duration::from_micros(50));
3214 }
3215 observe()
3216}
3217
3218#[cfg(windows)]
3221pub(crate) fn windows_spawn_capture(spec: &ModuleSpec) -> io::Result<subc_os::ExecutableCapture> {
3222 if let Err(error) = require_program_search_path(spec) {
3223 return Err(match error {
3224 SuperviseError::Spawn { source, .. } => source,
3225 error => io::Error::other(error),
3226 });
3227 }
3228 let mut program = spec.program.clone();
3229 if program.is_absolute() || program.components().count() > 1 {
3230 match subc_os::ExecutableCapture::open(&program) {
3233 Ok(capture) => return Ok(capture),
3234 Err(error)
3235 if error.kind() == io::ErrorKind::NotFound && program.extension().is_none() => {}
3236 Err(error) => return Err(error),
3237 }
3238 program.set_extension("exe");
3239 return subc_os::ExecutableCapture::open(&program);
3240 }
3241 if program.extension().is_none() {
3242 program.set_extension("exe");
3243 }
3244 let custom_path = spec
3245 .env
3246 .iter()
3247 .rev()
3248 .find(|(key, _)| key.eq_ignore_ascii_case("PATH"));
3249 let mut directories = Vec::new();
3250 if let Some(parent) = std::env::current_exe()?.parent() {
3253 directories.push(parent.to_path_buf());
3254 }
3255 directories.push(std::env::current_dir()?);
3256 if let Some(windows) = std::env::var_os("SystemRoot") {
3257 let windows = PathBuf::from(windows);
3258 directories.push(windows.join("System32"));
3259 directories.push(windows.clone());
3260 }
3261 let path = custom_path
3262 .map(|(_, value)| std::ffi::OsString::from(value))
3263 .or_else(|| std::env::var_os("PATH"));
3264 if let Some(path) = path {
3265 directories.extend(std::env::split_paths(&path));
3266 }
3267 for directory in directories {
3268 match subc_os::ExecutableCapture::open(&directory.join(&program)) {
3269 Ok(capture) => return Ok(capture),
3270 Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
3271 Err(error) => return Err(error),
3272 }
3273 }
3274 Err(io::Error::new(
3275 io::ErrorKind::NotFound,
3276 "resolved executable not found",
3277 ))
3278}
3279
3280#[cfg(test)]
3281pub(super) fn spawn_and_mark_running(
3282 spec: &ModuleSpec,
3283 runtime: &SupervisorRuntimeConfig,
3284 snapshot: &SharedSnapshot,
3285) -> Result<SupervisedChild, SuperviseError> {
3286 let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
3287 let registration_watch = watch_registration(&runtime.registry, spec);
3288 #[cfg(unix)]
3289 let joining_group = containment::current(&runtime.child_roster.containment)
3290 .is_some_and(|container| container.group().is_some());
3291 let spawn = || {
3292 spawn_child(
3293 spec,
3294 runtime.connection_file_path.as_deref(),
3295 runtime.supervisor_handle.as_ref(),
3296 &runtime.stderr_ring,
3297 runtime.capture_logs_dir.as_deref(),
3298 &runtime.child_roster,
3299 runtime.spawn_delivery(),
3300 #[cfg(target_os = "linux")]
3301 runtime.cgroup_placement.as_ref(),
3302 runtime.register_timeout,
3303 )
3304 };
3305 let result = spawn();
3306 #[cfg(unix)]
3307 let result = match result {
3308 Err(error)
3309 if joining_group
3310 && !is_launch_deferral(&error)
3311 && !runtime.child_roster.is_closed()
3312 && lock_snapshot(snapshot).is_ok_and(|state| state.enabled)
3313 && runtime
3314 .child_roster
3315 .previous_instance(&spec.module_id)
3316 .is_none() =>
3317 {
3318 warn!(module_id = %spec.module_id, %error, "carried process-group spawn failed; trying one fresh container");
3322 spawn()
3323 }
3324 other => other,
3325 };
3326 let child = result?;
3327 let mut child = child;
3328 arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
3329 if let Err(error) = set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events) {
3330 containment::terminate_blocking(&runtime.child_roster.containment);
3331 return Err(error);
3332 }
3333 if let Some(spawn) = activity_spawn {
3334 spawn.complete(snapshot);
3335 }
3336 Ok(child)
3337}
3338
3339pub(super) fn set_running(
3340 snapshot: &SharedSnapshot,
3341 child: &SupervisedChild,
3342 module_id: &str,
3343 spawn_events: &SpawnEventFeed,
3344) -> Result<(), SuperviseError> {
3345 let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
3346 module_id: Some(module_id.to_string()),
3347 })?;
3348 state.spawn_generation = spawn_events.emit_spawned(
3349 module_id,
3350 child
3351 .registration_spawn
3352 .as_ref()
3353 .map(|spawn| spawn.authority.spawn_number()),
3354 child.pid,
3355 child.spawned_at_ms,
3356 );
3357 if std::mem::take(&mut state.coalesced_restart_pending) {
3358 let generation = state.spawn_generation;
3359 info!(module_id, "restart already satisfied by generation {generation}; coalesced pending request completed");
3360 }
3361 state.drain_disposition_detail = None;
3362 state.spawn_failure = None;
3363 state.admission_refused = None;
3364 #[cfg(windows)]
3365 {
3366 state.nonce_pipe_refusal = None;
3367 }
3368 state.config_hold_parked = false;
3369 state.config_hold_daemon_initiated = false;
3370 state.config_hold_approval = None;
3371 state.legacy_registration_spawn =
3372 child.registration_spawn.is_some() && child.admission_base.is_none();
3373 state.registration_declaration = child.registration_declaration.clone();
3374 state.stop_reason = None;
3375 state.config_exit_failed_approval = None;
3376 state.waiting_for_previous_pid = None;
3377 state.waiting_for_previous_detail = None;
3378 state.in_alternate_slot = false;
3381 state.configuration_updated_since_spawn = false;
3382 state.spawned_protocol = Some(child.protocol);
3383 state.state = ModuleState::Running;
3384 state.approved_start_failure = None;
3385 state.enabled = true;
3386 state.process_alive = true;
3387 state.pid = child.id();
3388 state.subtree_target = child.subtree_target.clone();
3389 state.health.status = SupervisorHealthStatus::Unknown;
3392 state.last_probe_evidence = None;
3393 state.health.consecutive_failures = 0;
3394 state.health.detail = None;
3395 state.health.metrics = None;
3396 state.health.last_probe_ms = None;
3397 state.failed_retry.healthy_since = None;
3398 state.failed_retry.failed_at = None;
3399 state.failed_retry.running_since = Some(child.spawned_at);
3400 #[cfg(windows)]
3401 {
3402 state.pipe_consumed = child
3403 .nonce_delivery
3404 .as_ref()
3405 .map(|delivery| delivery.consumed());
3406 }
3407 #[cfg(target_os = "macos")]
3408 {
3409 state.report_ready = Some(Arc::clone(&child.report_ready));
3410 }
3411 state.spawned_at_ms = Some(child.spawned_at_ms);
3412 state.exec_outcome = Some(Arc::clone(&child.exec.0));
3413 state.spawned_from = Some(child.spawned_from.clone());
3414 state.launch_spec_digest = Some(child.launch_spec_digest.clone());
3415 state.spawned_file_identity = child.spawned_file_identity.clone();
3416 state.process_start_time = child.process_start_time;
3417 Ok(())
3418}