1#[cfg(all(test, target_os = "linux"))]
6#[path = "supervise/audit_identity_tests.rs"]
7mod audit_identity_tests;
8
9mod spawn;
10#[cfg(target_os = "linux")]
11#[cfg(test)]
12use spawn::apply_cgroup_placement;
13pub(crate) use spawn::apply_child_env;
14#[cfg(test)]
15use spawn::apply_spawn_role;
16#[cfg(test)]
17use spawn::apply_wire_spawn_args;
18#[cfg(all(test, any(unix, windows)))]
19use spawn::apply_wire_spawn_args_for_admission;
20use spawn::carries_containment;
21#[cfg(unix)]
22use spawn::is_launch_deferral;
23use spawn::kill_and_reap_rejected_child;
24#[cfg(target_os = "linux")]
25pub(crate) use spawn::kill_module_cgroup;
26#[cfg(all(test, target_os = "linux"))]
27use spawn::launch_child_in_slot;
28#[cfg(target_os = "linux")]
29#[cfg(test)]
30use spawn::linux_exec_committed;
31#[cfg(not(windows))]
32use spawn::observe_spawned_image;
33use spawn::observed_launch_nonce_source;
34#[cfg(all(test, target_os = "linux"))]
35use spawn::prepare_child_in_slot;
36#[cfg(all(test, windows))]
37use spawn::prepare_windows_registration_pipe;
38use spawn::previous_instance_error;
39use spawn::recovery_block_error;
40#[cfg(target_os = "linux")]
41#[cfg(test)]
42use spawn::remove_module_cgroup;
43#[cfg(target_os = "linux")]
44#[cfg(test)]
45use spawn::sample_after_linux_exec;
46use spawn::set_running;
47#[cfg(test)]
48use spawn::spawn_and_mark_running;
49#[cfg(all(test, unix))]
50use spawn::spawn_child;
51use spawn::spawn_child_async;
52#[cfg(all(test, unix))]
53use spawn::spawn_child_in_slot;
54use spawn::spawn_child_in_slot_async;
55#[cfg(all(test, target_os = "linux"))]
56use spawn::spawn_plan_stale;
57pub(crate) use spawn::validate_spec;
58#[cfg(windows)]
59pub(crate) use spawn::windows_spawn_capture;
60#[cfg(test)]
61use spawn::AfterFirstSpawnHook;
62#[cfg(test)]
63use spawn::CapturedRegistrationChannels;
64#[cfg(test)]
65use spawn::CapturedRegistrationEndpoint;
66pub(crate) use spawn::LaunchSpecDigest;
67pub use spawn::ModuleOverlap;
68pub use spawn::ModuleSpec;
69#[cfg(all(test, unix))]
70use spawn::RegisteredConfiguredModule;
71pub use spawn::ScriptEntry;
72pub use spawn::ScriptRuntime;
73pub(crate) use spawn::SpawnProgramBinding;
74#[cfg(any(unix, windows))]
75use spawn::SpawnRegistrationChannel;
76use spawn::SpawnRole;
77#[cfg(unix)]
79use spawn::ADMISSION_TIMEOUT;
80#[cfg(feature = "test-support")]
81pub use spawn::CHILD_ADMISSION_TIMEOUT;
82pub use spawn::SPAWN_ROLE_SWAP_CANDIDATE;
83pub use spawn::SUBC_ARG;
84pub use spawn::SUBC_SPAWN_ROLE_ENV;
85
86mod privacy_exec;
87#[cfg(target_os = "macos")]
88use privacy_exec::privacy_command;
89#[cfg(all(test, target_os = "macos"))]
90use privacy_exec::probe_privacy_trampoline;
91#[cfg(all(test, target_os = "macos"))]
92pub(crate) use privacy_exec::test_privacy_trampoline;
93#[cfg(target_os = "macos")]
94use privacy_exec::PrivacyExec;
95
96mod actor;
97#[cfg(all(test, unix))]
98use actor::handle_supervisor_command;
99use actor::supervise_loop;
100#[cfg(all(test, unix))]
101use actor::supervisor_sleep;
102#[cfg(test)]
103use actor::ActorSelectCheckpoint;
104use actor::NextAction;
105use actor::SupervisorCommand;
106
107mod restart;
108use restart::finish_reload_child;
109use restart::reload_child;
110use restart::restart_child;
111use restart::restart_child_with_budget_policy;
112use restart::set_child_enabled;
113use restart::set_child_enabled_with_budget_policy;
114#[cfg(test)]
115use restart::ReloadExitRecordGate;
116
117mod health_probe;
118#[cfg(test)]
119use health_probe::handle_health_probe_failure;
120#[cfg(all(test, unix))]
121use health_probe::handle_health_report;
122#[cfg(test)]
123use health_probe::health_restart_child;
124#[cfg(test)]
125use health_probe::jittered_health_delay;
126pub(crate) use health_probe::parse_http_probe_url;
127use health_probe::probe_endpoint_health;
128#[cfg(all(test, unix))]
129use health_probe::probe_http_health;
130use health_probe::probe_module_health;
131use health_probe::record_health_action;
132use health_probe::run_health_probe_cycle;
133use health_probe::running_protocol;
134pub use health_probe::HealthAction;
135pub use health_probe::HealthConfig;
136#[cfg(test)]
137use health_probe::HealthProbeError;
138use health_probe::HealthProbeEvidence;
139use health_probe::HealthProbeRuntime;
140pub use health_probe::ModuleHealthStatus;
141
142mod drain;
143use drain::begin_forwarding_drain;
144use drain::begin_forwarding_drain_if_configured;
145use drain::begin_forwarding_drain_with;
146use drain::begin_forwarding_drain_with_timeout;
147#[cfg(test)]
148use drain::busy_gauge_observation;
149use drain::control_flags;
150pub(crate) use drain::declared_busy_gauges;
151#[cfg(test)]
152use drain::drain_busy_reprobe_interval;
153#[cfg(test)]
154use drain::drain_child_to_state;
155use drain::drain_optional_child;
156#[cfg(test)]
157use drain::drained_after_quiescence_wait;
158#[cfg(test)]
159use drain::gauge_verdicts;
160use drain::request_graceful_stop;
161use drain::terminal_disposition;
162#[cfg(test)]
163use drain::wait_for_forwarding_quiescence;
164#[cfg(test)]
165use drain::warn_drain_timed_out;
166#[cfg(test)]
167use drain::BusyGaugeObservation;
168#[cfg(test)]
169use drain::DrainGaugeTrace;
170use drain::DrainScope;
171use drain::ForwardingDrainContext;
172#[cfg(test)]
173use drain::GaugeVerdict;
174use drain::StopNotice;
175pub use drain::DEFAULT_DRAIN_TIMEOUT;
176
177mod exit;
178#[cfg(test)]
179use exit::apply_deliberate_severance_marker;
180use exit::classify_exit;
181use exit::classify_reaped_child_exit;
182use exit::clear_current_process_facts;
183use exit::durable_terminal_history_of;
184use exit::fail_after_wait_error;
185use exit::fail_snapshot;
186#[cfg(test)]
187use exit::on_child_exit;
188use exit::on_child_exit_with_detail;
189use exit::publish_after_terminal_record;
190#[cfg(test)]
191use exit::record_deliberate_severance;
192#[cfg(test)]
193use exit::record_terminal;
194use exit::record_terminal_with_detail;
195#[cfg(test)]
196use exit::record_wait_error_terminal;
197#[cfg(any(unix, test))]
198use exit::settle_stderr_pump;
199#[cfg(any(unix, test))]
200use exit::settle_stdout_pump;
201use exit::untrack_if_registration_released;
202use exit::wait_error_exit_report;
203
204mod spawn_events;
205use spawn_events::SpawnEventFeed;
206pub(crate) use spawn_events::SpawnSubscribeRefusal;
207pub use spawn_events::SPAWN_EVENT_RING_CAPACITY;
208#[cfg(test)]
209use spawn_events::SPAWN_SUBSCRIBER_BUFFER;
210#[cfg(test)]
211use spawn_events::SPAWN_SUBSCRIBER_LAGGED_CODE;
212
213mod roster;
214pub use roster::ModuleProcessLiveness;
215pub use roster::SupervisorProcessLiveness;
216mod resource_launch;
217pub(crate) use resource_launch::{ResourceCommitError, ResourceLaunch};
218
219use std::{
220 collections::{HashMap, HashSet, VecDeque},
221 error::Error,
222 fmt, io,
223 path::PathBuf,
224 process::{ExitStatus, Stdio},
225 sync::{Arc, Mutex, OnceLock},
226 time::{Duration, SystemTime, UNIX_EPOCH},
227};
228
229use cortexkit_log::Retention;
230use serde_json::Value;
231use sha2::{Digest, Sha256};
232use subc_control::{
233 ClientControlPush, LiveSpawn, ModuleProtocol, RouteCloseReason, SpawnCursor, SpawnEvent,
234 SpawnEventKind, SpawnSnapshot, SupervisorHealthStatus, TerminalDisposition, TerminalExitKind,
235};
236use subc_protocol::{
237 manifest::{SelfSignalKind, SignalAnchor},
238 session::{
239 HealthReport, HealthStatus, ModuleControlCommand, ModuleControlRequest,
240 MODULE_CONTROL_OP_HEALTH_CHECK,
241 },
242 Flags, FrameType, Principal, Priority, SUBC_LAUNCH_NONCE_ENV, SUBC_MODULE_ID_ENV,
243};
244use tokio::{
245 process::{Child, Command},
246 sync::{mpsc, oneshot, watch, Mutex as AsyncMutex},
247 task::JoinHandle,
248 time::{sleep, sleep_until, timeout, timeout_at, Instant},
249};
250use tracing::{debug, error, info, warn};
251
252use crate::{
253 child_output::StderrPump,
254 child_roster::ChildRoster,
255 daemon_config::{
256 CAPTURE_KEEP_ENV, CAPTURE_MAX_AGE_DAYS_ENV, CAPTURE_MAX_FILE_MB_ENV, CK_LOG_ENV,
257 },
258 forwarding::{
259 CloseReason, ForwardingError, ForwardingTable, GoodbyeTarget, ModuleControlRpcOutcome,
260 ModuleDrainTarget, PendingModuleControlRpc,
261 },
262 provenance::{ExecutableIdentityProbe, SpawnedFileIdentity},
263 registry::{ConnectionId, RegistrationEndReason, RegistryError},
264 stderr_tail::{ChildOutputSink, StderrRing, StderrTailConfig, StderrTailSnapshot},
265 terminal_ring::{TerminalHistorySnapshot, TerminalRecord, TerminalRing, TerminalRingConfig},
266 Frame, FrameSink, Registry,
267};
268
269#[cfg(not(windows))]
270use crate::provenance::spawned_file_identity;
271
272#[path = "supervise_swap.rs"]
273mod swap;
274use swap::OpenSwap;
275use swap::PromotionObserverSlot;
276pub(crate) use swap::SwapHelloAdmission;
277pub(crate) use swap::SwapPromotionObserver;
278pub use swap::DEFAULT_SWAP_READY_TIMEOUT;
279
280#[path = "supervise_activity.rs"]
281mod activity;
282
283#[cfg(unix)]
284#[path = "supervise/admission.rs"]
285mod admission;
286mod admission_exit;
287#[cfg(all(test, target_os = "linux"))]
288mod async_spawn_tests;
289#[cfg(all(test, windows))]
290mod carried_job_tests;
291mod config_delivery;
292use config_delivery::cancel_deferred_reload;
293use config_delivery::defer_config_spawn;
294use config_delivery::hold_config_respawn;
295use config_delivery::hold_config_spawn;
296use config_delivery::record_approved_attempt_failure;
297use config_delivery::try_park_config_attempt;
298use config_delivery::CONFIG_ADMISSION_RETRY_DELAY;
299mod content_binding;
300mod program_binding;
301mod registration;
302use registration::arm_registration_deadline;
303use registration::constant_time_eq;
304use registration::handle_reload_child_registration_failure;
305use registration::handle_reload_spawn_failure;
306pub(crate) use registration::notify_registration_release;
307use registration::registration_child_is_running;
308use registration::registration_failure_exit_report;
309use registration::release_dead_registration;
310use registration::wait_for_registration_after_reload;
311use registration::wait_for_registration_release;
312use registration::wait_for_slot_registration_release;
313use registration::watch_registration;
314#[cfg(test)]
315use registration::IdentitySamplePause;
316use registration::RegistrationWaitOutcome;
317use registration::RegistrationWatch;
318use registration::ReloadRegistrationFailure;
319pub(crate) use registration::ReservedHelloRejection;
320pub(crate) use registration::ReservedHelloVerification;
321pub(crate) use registration::DEFAULT_REGISTER_TIMEOUT;
322use registration::REGISTRY_RELEASE_POLL;
323use registration::REGISTRY_RELEASE_TIMEOUT;
324pub(crate) mod script;
325type NonceLaunches = HashMap<String, (String, std::sync::Weak<RegistrationSpawn>)>;
327pub(crate) use registration::NonceAttestation;
328#[cfg(all(test, unix))]
329pub(crate) use registration::RegistrationProof;
330pub(crate) use registration::RegistrationSpawn;
331pub(crate) use registration::REGISTRATION_CHANNEL_CLOSED;
332#[cfg(all(test, unix))]
333pub(crate) mod unix_channel_placement_tests;
334use program_binding::ProgramBindingPublication;
335mod config_exit_failure;
336#[cfg(all(test, any(target_os = "linux", windows)))]
337mod missing_path_tests;
338#[cfg(all(test, unix))]
339mod program_binding_tests;
340#[cfg(all(test, windows))]
341mod program_binding_windows_tests;
342#[cfg(all(test, windows))]
343mod windows_channel_tests;
344pub use config_exit_failure::ModuleStopReason;
345mod unregistered_stop;
346use unregistered_stop::stop_unregistered_child;
347#[cfg(target_os = "linux")]
348#[path = "supervise/cgroup_label.rs"]
349mod cgroup_label;
350#[cfg(all(test, unix))]
351mod config_exit_hold_tests;
352pub(crate) mod containment;
353#[cfg(all(test, unix))]
354mod containment_tests;
355#[cfg(target_os = "linux")]
356mod ordinary_cgroup;
357#[cfg(unix)]
358pub(crate) mod plain_group;
359#[cfg(all(test, target_os = "linux"))]
360mod plain_group_regression;
361mod slow_retry;
362use slow_retry::{FailedRetry, FailureContext};
363mod host_health;
364use host_health::HostHealth;
365
366#[cfg(test)]
367mod crash_admission_tests;
368mod crash_budget;
369use crash_budget::budgeted_restart_child;
370use crash_budget::daemon_will_restart;
371use crash_budget::log_crash_respawn;
372use crash_budget::reset_restart_count;
373use crash_budget::respawn_still_pending;
374use crash_budget::schedule_respawn;
375use crash_budget::CrashRestartSchedule;
376pub use crash_budget::RestartPolicy;
377#[cfg(all(test, unix))]
378mod mark_readiness_tests;
379#[cfg(all(test, unix))]
380mod slow_retry_tests;
381use crash_budget::{admit_running_child_async, spawn_and_mark_running_async};
382
383struct SupervisedChild {
384 registration_spawn: Option<Arc<RegistrationSpawn>>,
385 #[cfg(any(unix, windows))]
387 registration_channel: Option<SpawnRegistrationChannel>,
388 live_program_binding: Option<Arc<content_binding::LiveProgramBinding>>,
389 registered_config_connection: Option<ConnectionId>,
390 admission_base: Option<subc_config::Digest>,
391 registration_declaration: Option<String>,
392 _program_binding: Option<ProgramBindingPublication>,
393 subtree_target: crate::subtree_resources::Target,
394 child: containment::ProcessChild,
395 exec: crate::activity::ExecOwner,
396 #[cfg(windows)]
397 nonce_delivery: Option<subc_os::LaunchNoncePipeDelivery>,
398 #[cfg(target_os = "macos")]
399 privacy_exec: Option<PrivacyExec>,
400 #[cfg(target_os = "macos")]
407 report_ready: Arc<OnceLock<()>>,
408 spawn_failure: Option<String>,
411 admission_kill_sent: bool,
414 protocol: ModuleProtocol,
419 #[cfg(target_os = "linux")]
426 module_id: String,
427 #[cfg(target_os = "linux")]
428 cgroup_placement: Option<subc_cgroup::Placement>,
429 #[cfg(target_os = "linux")]
430 unresolved_cgroup: Option<ordinary_cgroup::Unresolved>,
431 #[cfg(windows)]
454 job: Option<Arc<Mutex<subc_jobobject::JobObject>>>,
455 stdout_pump: Option<tokio::sync::oneshot::Receiver<()>>,
456 stderr_pump: Option<StderrPump>,
457 #[cfg(unix)]
458 capture_stop: Option<crate::child_output::StopReaders>,
459 #[cfg(unix)]
460 late_output_lost: bool,
461 stderr_ring: Arc<Mutex<StderrRing>>,
462 spawned_at: Instant,
465 config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
466 registration_deadline: Option<Instant>,
469 registration_watch: Option<RegistrationWatch>,
470 spawned_at_ms: u64,
471 spawned_from: PathBuf,
472 launch_spec_digest: LaunchSpecDigest,
473 spawned_file_identity: Option<SpawnedFileIdentity>,
474 process_start_time: Option<u64>,
475 process_identity: Option<ProcessIdentity>,
476 pid: u32,
477 roster_guard: Option<crate::child_roster::RosterGuard>,
480}
481
482impl SupervisedChild {}
483
484#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486pub enum ModuleState {
487 Starting,
488 Running,
489 Unresponsive,
490 Restarting,
491 Draining,
492 Stopped,
493 Failed,
494 Disabled,
495}
496
497impl fmt::Display for ModuleState {
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499 f.write_str(match self {
500 Self::Starting => "starting",
501 Self::Running => "running",
502 Self::Unresponsive => "unresponsive",
503 Self::Restarting => "restarting",
504 Self::Draining => "draining",
505 Self::Stopped => "stopped",
506 Self::Failed => "failed",
507 Self::Disabled => "disabled",
508 })
509 }
510}
511
512#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub enum ExitKind {
515 Clean,
516 Crash,
517 DeliberateSeverance,
518}
519
520impl From<ExitKind> for TerminalExitKind {
521 fn from(kind: ExitKind) -> Self {
522 match kind {
523 ExitKind::Clean => Self::Clean,
524 ExitKind::Crash => Self::Crash,
525 ExitKind::DeliberateSeverance => Self::DeliberateSeverance,
526 }
527 }
528}
529
530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
533pub(crate) struct ProcessIdentity {
534 pub(crate) pid: u32,
535 pub(crate) start_time: u64,
536}
537
538#[derive(Debug, Clone, PartialEq, Eq)]
540pub struct ExitReport {
541 pub kind: ExitKind,
542 pub code: Option<i32>,
543 pub signal: Option<i32>,
544 pub at_ms: u64,
545}
546
547#[derive(Debug, Clone, PartialEq)]
550pub struct ModuleStatus {
551 pub(crate) admission_refused: Option<String>,
552 pub(crate) legacy_registration_spawn: bool,
553 pub(crate) registration_declaration: Option<String>,
554 pub module_id: String,
555 pub stop_reason: Option<ModuleStopReason>,
558 pub waiting_for_previous_pid: Option<u32>,
560 pub waiting_for_previous_detail: Option<String>,
562 pub launch_nonce_source: Option<String>,
567 pub state: ModuleState,
568 pub enabled: bool,
569 pub process_alive: bool,
570 pub registration_active: bool,
571 pub protocol: ModuleProtocol,
576 pub live: bool,
587 pub restart_count: u32,
591 pub lifetime_restarts: u32,
595 pub spawn_generation: u64,
596 pub swap_outcome: Option<SwapOutcome>,
598 pub max_restarts: u32,
603 pub restart_window: Duration,
607 pub drain_timeout: Duration,
611 pub restart_backoff: Duration,
612 pub restart_max_backoff: Duration,
613 pub pid: Option<u32>,
618 pub spawned_at_ms: Option<u64>,
619 pub spawned_from: Option<PathBuf>,
620 pub(crate) launch_spec_digest: Option<LaunchSpecDigest>,
621 pub process_start_time: Option<u64>,
622 pub last_exit: Option<ExitReport>,
623 pub health: ModuleHealthStatus,
624}
625
626#[derive(Debug, Clone, PartialEq)]
627struct SupervisorSnapshot {
628 admission_refused: Option<String>,
629 config_hold_parked: bool,
631 config_hold_daemon_initiated: bool,
634 config_hold_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
636 approved_start_failure: Option<(crate::config_gate::runtime::ApprovalIdentity, String)>,
638 legacy_registration_spawn: bool,
639 registration_declaration: Option<String>,
640 stop_reason: Option<ModuleStopReason>,
641 config_exit_failed_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
642 subtree_target: crate::subtree_resources::Target,
643 failed_retry: FailedRetry,
644 exec_outcome: Option<Arc<crate::activity::ExecOutcome>>,
645 #[cfg(windows)]
646 pipe_consumed: Option<Arc<OnceLock<()>>>,
647 #[cfg(test)]
649 actor_turns: u64,
650 #[cfg(test)]
653 actor_select: Option<ActorSelectCheckpoint>,
654 state: ModuleState,
655 enabled: bool,
656 process_alive: bool,
657 spawned_protocol: Option<ModuleProtocol>,
658 spawn_failure: Option<String>,
659 waiting_for_previous_pid: Option<u32>,
660 waiting_for_previous_detail: Option<String>,
661 crash_restarts: VecDeque<Instant>,
667 lifetime_restarts: u32,
668 spawn_generation: u64,
677 swap_outcome: Option<SwapOutcome>,
678 pid: Option<u32>,
679 #[cfg(target_os = "macos")]
680 report_ready: Option<Arc<OnceLock<()>>>,
681 reaped_pid: Option<u32>,
683 respawn_pending: bool,
685 coalesced_restart_pending: bool,
687 spawned_at_ms: Option<u64>,
688 spawned_from: Option<PathBuf>,
689 launch_spec_digest: Option<LaunchSpecDigest>,
690 spawned_file_identity: Option<SpawnedFileIdentity>,
691 process_start_time: Option<u64>,
692 deliberate_severance: Option<ProcessIdentity>,
693 last_exit: Option<ExitReport>,
694 drain_disposition_detail: Option<String>,
696 health: ModuleHealthStatus,
697 last_probe_evidence: Option<HealthProbeEvidence>,
698 in_alternate_slot: bool,
703 draining_to_replace: bool,
710 configuration_updated_since_spawn: bool,
716}
717
718impl SupervisorSnapshot {
719 fn reported_pid(&self) -> Option<u32> {
724 #[cfg(target_os = "macos")]
725 if self
726 .report_ready
727 .as_ref()
728 .is_some_and(|ready| ready.get().is_none())
729 {
730 return None;
731 }
732 self.pid
733 }
734
735 fn starting() -> Self {
736 Self::new(ModuleState::Starting, true)
737 }
738
739 fn disabled() -> Self {
740 Self::new(ModuleState::Disabled, false)
741 }
742
743 fn clear_crash_restarts(&mut self) {
748 self.crash_restarts.clear();
749 }
750
751 fn new(state: ModuleState, enabled: bool) -> Self {
752 Self {
753 admission_refused: None,
754 config_hold_parked: false,
755 config_hold_daemon_initiated: false,
756 config_hold_approval: None,
757 approved_start_failure: None,
758 legacy_registration_spawn: false,
759 registration_declaration: None,
760 stop_reason: None,
761 config_exit_failed_approval: None,
762 subtree_target: crate::subtree_resources::Target::Unavailable("not_running"),
763 failed_retry: FailedRetry::default(),
764 exec_outcome: None,
765 #[cfg(test)]
766 actor_turns: 0,
767 #[cfg(test)]
768 actor_select: None,
769 state,
770 enabled,
771 process_alive: false,
772 #[cfg(windows)]
773 pipe_consumed: None,
774 spawned_protocol: None,
775 spawn_failure: None,
776 waiting_for_previous_pid: None,
777 waiting_for_previous_detail: None,
778 crash_restarts: VecDeque::new(),
779 lifetime_restarts: 0,
780 spawn_generation: 0,
781 swap_outcome: None,
782 pid: None,
783 #[cfg(target_os = "macos")]
784 report_ready: None,
785 reaped_pid: None,
786 respawn_pending: false,
787 coalesced_restart_pending: false,
788 spawned_at_ms: None,
789 spawned_from: None,
790 launch_spec_digest: None,
791 spawned_file_identity: None,
792 process_start_time: None,
793 deliberate_severance: None,
794 last_exit: None,
795 drain_disposition_detail: None,
796 health: ModuleHealthStatus::default(),
797 last_probe_evidence: None,
798 in_alternate_slot: false,
799 draining_to_replace: false,
800 configuration_updated_since_spawn: false,
801 }
802 }
803}
804
805type SharedSnapshot = Arc<Mutex<SupervisorSnapshot>>;
806
807#[derive(Debug, Clone, Copy)]
808enum RespawnKind {
809 Spawn,
810 CrashRestart,
811 Reload,
812}
813
814#[derive(Debug, Clone)]
815struct PendingRespawn {
816 deadline: Instant,
817 kind: RespawnKind,
818 daemon_initiated: bool,
819 approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
820}
821
822impl PendingRespawn {
823 fn failure_context(&self, runtime: &SupervisorRuntimeConfig) -> FailureContext {
824 FailureContext {
825 approval: self.approval.clone(),
826 ..runtime.failure_context(self.daemon_initiated)
827 }
828 }
829}
830
831type ReloadReply = oneshot::Sender<Result<(), SuperviseError>>;
832
833#[derive(Debug, Clone)]
834struct SupervisorRuntimeConfig {
835 registry: Arc<Registry>,
836 config_delivery: Option<config_delivery::ConfigDelivery>,
837 recovery_is_daemon: bool,
839 start_requester: Option<Principal>,
840 pending_activity_restart: bool,
841 provenance_probe: ExecutableIdentityProbe,
842 scheduled_respawn: Arc<Mutex<Option<PendingRespawn>>>,
844 deferred_reload_reply: Arc<Mutex<Option<ReloadReply>>>,
846 restart_policy: RestartPolicy,
847 register_timeout: Duration,
848 drain_timeout: Duration,
851 effective_drain_timeout: Arc<Mutex<Duration>>,
854 default_drain_timeout: Duration,
857 health: HealthConfig,
858 host_health: HostHealth,
859 connection_file_path: Option<PathBuf>,
860 capture_logs_dir: Option<PathBuf>,
861 forwarding: Option<Arc<ForwardingTable>>,
862 supervisor_handle: Option<SupervisorHandle>,
865 stderr_ring: Arc<Mutex<StderrRing>>,
872 terminal_ring: Arc<Mutex<TerminalRing>>,
873 spawn_events: SpawnEventFeed,
874 child_roster: ChildRoster,
875 #[cfg(target_os = "linux")]
876 cgroup_placement: Option<subc_cgroup::Placement>,
877 #[cfg(test)]
878 test_seed_stale_facts_before_enable_spawn: bool,
879 #[cfg(test)]
880 test_reload_exit_record_gate: Option<Arc<ReloadExitRecordGate>>,
881}
882
883impl SupervisorRuntimeConfig {
884 fn failure_context(&self, daemon_initiated: bool) -> FailureContext {
885 FailureContext {
886 daemon_initiated,
887 approval: None,
888 shutdown: self.child_roster.shutdown_flag(),
889 }
890 }
891}
892
893#[derive(Debug, Clone, PartialEq, Eq)]
894struct SupervisedConfiguration {
895 spec: ModuleSpec,
896 enabled: bool,
897 health: HealthConfig,
898 register_timeout: Duration,
899 restart_policy: RestartPolicy,
900}
901
902#[derive(Debug, Clone, Default)]
908pub struct SupervisorHandle {
909 #[cfg(test)]
910 resource_commit_pause: Arc<Mutex<Option<resource_launch::ResourceCommitPause>>>,
911 #[cfg(test)]
912 registration_test_channels: CapturedRegistrationChannels,
913 registration_service: Arc<Mutex<Option<registration::RegistrationService>>>,
914 registration_connections: Arc<Mutex<HashMap<ConnectionId, Arc<RegistrationSpawn>>>>,
915 registration_launches: Arc<Mutex<Vec<std::sync::Weak<RegistrationSpawn>>>>,
916 gate_runtime: Arc<Mutex<Option<std::sync::Weak<crate::config_gate::runtime::RuntimeOwner>>>>,
917 program_bindings: program_binding::ProgramBindings,
918 #[cfg(test)]
919 identity_sample_pause: Arc<Mutex<Option<IdentitySamplePause>>>,
920 #[cfg(all(test, unix))]
921 plain_identity_policy_pause: Arc<Mutex<Option<(String, IdentitySamplePause)>>>,
922 host_health: HostHealth,
923 restart_intent: Arc<Mutex<DaemonRestartIntent>>,
924 activity: Arc<Mutex<Option<crate::activity::ActivityLedger>>>,
925 activity_images: Arc<Mutex<HashMap<String, activity::ActivityImage>>>,
926 modules: Arc<Mutex<HashMap<String, SupervisedModule>>>,
927 configured_ids: Arc<Mutex<HashSet<String>>>,
939 spawn_events: SpawnEventFeed,
940 reserved_nonces: Arc<Mutex<HashMap<String, Option<String>>>>,
951 implicit_protocol_none: Arc<Mutex<HashSet<String>>>,
955 removal_tombstones: Arc<Mutex<HashMap<String, u64>>>,
961 spawn_nonces: Arc<Mutex<HashMap<String, String>>>,
965 nonce_launches: Arc<Mutex<NonceLaunches>>,
971 reserved_prefix_owners: Arc<Mutex<HashMap<String, String>>>,
979 swaps: Arc<Mutex<HashMap<String, OpenSwap>>>,
985 promotion_observer: PromotionObserverSlot,
987 operation_lock: Arc<AsyncMutex<()>>,
991}
992
993#[derive(Debug)]
994struct DaemonRestartIntent {
995 expires: Option<Duration>,
996 window: Duration,
997}
998
999impl Default for DaemonRestartIntent {
1000 fn default() -> Self {
1001 Self {
1002 expires: None,
1003 window: Duration::from_secs(120),
1004 }
1005 }
1006}
1007
1008impl SupervisorHandle {
1009 pub(crate) fn module_is_gated(&self, module: &str) -> bool {
1010 let runtime = {
1011 let Ok(runtime) = self.gate_runtime.lock() else {
1012 return true;
1013 };
1014 runtime.clone()
1015 };
1016 runtime.is_some_and(|runtime| {
1017 runtime
1018 .upgrade()
1019 .is_none_or(|owner| owner.module_is_gated(module))
1020 })
1021 }
1022 pub(crate) fn announce_daemon_restart(&self) -> u64 {
1023 let mut intent = self
1024 .restart_intent
1025 .lock()
1026 .unwrap_or_else(|p| p.into_inner());
1027 intent.expires = Some(subc_uptime::suspend_inclusive_now() + intent.window);
1028 unix_ms_now().saturating_add(intent.window.as_millis() as u64)
1029 }
1030
1031 #[cfg(feature = "test-support")]
1032 pub(crate) fn set_shutdown_intent_window(&self, window: Duration) {
1033 self.restart_intent
1034 .lock()
1035 .unwrap_or_else(|p| p.into_inner())
1036 .window = window;
1037 }
1038
1039 #[cfg(unix)]
1040 fn take_daemon_shutdown_reason(&self) -> RouteCloseReason {
1041 let expiry = self
1042 .restart_intent
1043 .lock()
1044 .unwrap_or_else(|p| p.into_inner())
1045 .expires
1046 .take();
1047 if expiry.is_some_and(|expiry| subc_uptime::suspend_inclusive_now() < expiry) {
1048 RouteCloseReason::Restart
1049 } else {
1050 RouteCloseReason::Disable
1051 }
1052 }
1053
1054 pub fn new() -> Self {
1055 Self::default()
1056 }
1057
1058 pub(crate) fn operation_lock(&self) -> Arc<AsyncMutex<()>> {
1059 Arc::clone(&self.operation_lock)
1060 }
1061}
1062
1063#[derive(Debug, Clone)]
1065pub struct Supervisor {
1066 registry: Arc<Registry>,
1067 config_delivery: Option<config_delivery::ConfigDelivery>,
1068 restart_policy: RestartPolicy,
1069 drain_timeout: Duration,
1070 connection_file_path: Option<PathBuf>,
1071 capture_logs_dir: Option<PathBuf>,
1072 forwarding: Option<Arc<ForwardingTable>>,
1073 process_liveness: Arc<SupervisorProcessLiveness>,
1074 supervisor_handle: Option<SupervisorHandle>,
1075 health: HealthConfig,
1076 host_health: HostHealth,
1077 daemon_start_clock: crate::clock::StartClock,
1078 terminal_journal: Option<Arc<crate::terminal_journal::TerminalJournal>>,
1079 spawn_events: SpawnEventFeed,
1080 provenance_probe: ExecutableIdentityProbe,
1081 child_roster: ChildRoster,
1084 #[cfg(target_os = "linux")]
1085 cgroup_placement: Option<subc_cgroup::Placement>,
1086 #[cfg(test)]
1087 test_after_first_spawn: AfterFirstSpawnHook,
1088}
1089
1090impl Supervisor {
1091 pub fn new(registry: Arc<Registry>, restart_policy: RestartPolicy) -> Self {
1092 Self {
1093 registry,
1094 config_delivery: None,
1095 restart_policy,
1096 drain_timeout: DEFAULT_DRAIN_TIMEOUT,
1097 connection_file_path: None,
1098 capture_logs_dir: None,
1099 forwarding: None,
1100 process_liveness: Arc::new(SupervisorProcessLiveness::default()),
1101 supervisor_handle: None,
1102 health: HealthConfig::default(),
1103 host_health: HostHealth::default(),
1104 daemon_start_clock: crate::clock::StartClock::capture(),
1105 terminal_journal: None,
1106 spawn_events: SpawnEventFeed::default(),
1107 provenance_probe: ExecutableIdentityProbe::default(),
1108 child_roster: ChildRoster::default(),
1109 #[cfg(target_os = "linux")]
1110 cgroup_placement: None,
1111 #[cfg(test)]
1112 test_after_first_spawn: AfterFirstSpawnHook::default(),
1113 }
1114 }
1115
1116 pub fn with_drain_timeout(mut self, drain_timeout: Duration) -> Self {
1117 self.drain_timeout = drain_timeout;
1118 self
1119 }
1120
1121 pub(crate) fn default_drain_timeout(&self) -> Duration {
1123 self.drain_timeout
1124 }
1125
1126 pub fn with_process_liveness(
1127 mut self,
1128 process_liveness: Arc<SupervisorProcessLiveness>,
1129 ) -> Self {
1130 self.process_liveness = process_liveness;
1131 self
1132 }
1133
1134 pub fn with_config_runtime(
1136 mut self,
1137 owner: Arc<crate::config_gate::runtime::RuntimeOwner>,
1138 ) -> Self {
1139 if let Some(handle) = &self.supervisor_handle {
1140 handle.install_binding_retirement(&owner);
1141 }
1142 self.config_delivery = Some(config_delivery::ConfigDelivery(owner));
1143 self
1144 }
1145
1146 pub fn with_connection_file_path(mut self, connection_file_path: impl Into<PathBuf>) -> Self {
1147 self.connection_file_path = Some(connection_file_path.into());
1148 self
1149 }
1150
1151 pub fn with_capture_logs_dir(mut self, logs_dir: impl Into<PathBuf>) -> Self {
1153 self.capture_logs_dir = Some(logs_dir.into());
1154 self
1155 }
1156
1157 pub fn with_daemon_incarnation(self, daemon_incarnation: String) -> Self {
1160 self.spawn_events.configure_incarnation(daemon_incarnation);
1164 self
1165 }
1166
1167 pub fn with_terminal_journal(self, path: PathBuf, daemon_incarnation: String) -> Self {
1170 let mut this = self.with_daemon_incarnation(daemon_incarnation.clone());
1171 this.terminal_journal = Some(Arc::new(crate::terminal_journal::TerminalJournal::open(
1172 path,
1173 daemon_incarnation,
1174 )));
1175 this
1176 }
1177
1178 pub fn with_forwarding(mut self, forwarding: Arc<ForwardingTable>) -> Self {
1179 self.child_roster.counters = forwarding.counters();
1180 self.forwarding = Some(forwarding);
1181 self
1182 }
1183
1184 pub fn with_handle(mut self, supervisor_handle: SupervisorHandle) -> Self {
1185 if let Some(delivery) = &self.config_delivery {
1186 supervisor_handle.install_binding_retirement(&delivery.0);
1187 }
1188 self.host_health = supervisor_handle.host_health.clone();
1189 self.spawn_events = supervisor_handle.spawn_events.clone();
1190 self.supervisor_handle = Some(supervisor_handle);
1191 self
1192 }
1193
1194 pub fn with_health_config(mut self, health: HealthConfig) -> Self {
1195 self.health = health;
1196 self
1197 }
1198
1199 pub fn with_live_children_record(self, path: impl Into<PathBuf>) -> Self {
1203 self.child_roster.record_to(path.into());
1204 self
1205 }
1206
1207 #[cfg(target_os = "linux")]
1208 pub fn with_cgroup_placement(
1209 mut self,
1210 cgroup_placement: Option<subc_cgroup::Placement>,
1211 ) -> Self {
1212 self.child_roster
1213 .set_cgroup_placement(cgroup_placement.clone());
1214 self.cgroup_placement = cgroup_placement;
1215 self
1216 }
1217}
1218
1219impl Default for Supervisor {
1220 fn default() -> Self {
1221 Self::new(Arc::new(Registry::default()), RestartPolicy::default())
1222 }
1223}
1224
1225#[derive(Clone)]
1227pub struct SupervisedModule {
1228 inner: Arc<SupervisedModuleInner>,
1229}
1230
1231struct SupervisedModuleInner {
1232 retained: crate::child_roster::RetainedView,
1233 module_id: String,
1234 registry: Arc<Registry>,
1235 snapshot: SharedSnapshot,
1236 configuration: Arc<Mutex<SupervisedConfiguration>>,
1237 stderr_ring: Arc<Mutex<StderrRing>>,
1238 terminal_ring: Arc<Mutex<TerminalRing>>,
1239 commands: mpsc::Sender<SupervisorCommand>,
1240 monitor: Mutex<Option<JoinHandle<()>>>,
1241 effective_drain_timeout: Arc<Mutex<Duration>>,
1242 provenance_probe: ExecutableIdentityProbe,
1243}
1244
1245impl fmt::Debug for SupervisedModule {
1246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1247 f.debug_struct("SupervisedModule")
1248 .field("module_id", &self.inner.module_id)
1249 .field("status", &self.status())
1250 .finish_non_exhaustive()
1251 }
1252}
1253
1254impl SupervisedModule {
1255 pub fn module_id(&self) -> &str {
1256 &self.inner.module_id
1257 }
1258
1259 pub fn state(&self) -> Result<ModuleState, SuperviseError> {
1260 Ok(lock_snapshot(&self.inner.snapshot)?.state)
1261 }
1262
1263 pub(crate) fn registration_end_reason(
1264 &self,
1265 ) -> Result<Option<RegistrationEndReason>, SuperviseError> {
1266 let snapshot = lock_snapshot(&self.inner.snapshot)?;
1267 Ok(match snapshot.state {
1268 ModuleState::Draining if snapshot.draining_to_replace => {
1269 Some(RegistrationEndReason::SupervisorRestart)
1270 }
1271 ModuleState::Draining => Some(RegistrationEndReason::SupervisorStop),
1272 ModuleState::Restarting if snapshot.draining_to_replace => {
1273 Some(RegistrationEndReason::SupervisorRestart)
1274 }
1275 _ => None,
1276 })
1277 }
1278
1279 pub fn stderr_tail(
1286 &self,
1287 max_lines: Option<usize>,
1288 max_bytes: Option<usize>,
1289 ) -> StderrTailSnapshot {
1290 self.inner
1291 .stderr_ring
1292 .lock()
1293 .unwrap_or_else(|poisoned| poisoned.into_inner())
1294 .snapshot(max_lines, max_bytes)
1295 }
1296
1297 pub fn terminal_history(&self) -> TerminalHistorySnapshot {
1302 self.inner
1303 .terminal_ring
1304 .lock()
1305 .unwrap_or_else(|poisoned| poisoned.into_inner())
1306 .snapshot()
1307 }
1308
1309 pub fn durable_terminal_history(&self) -> subc_control::TerminalHistory {
1314 durable_terminal_history_of(&self.inner.terminal_ring, &self.inner.module_id)
1315 }
1316
1317 pub(crate) async fn read_durable_terminal_history(
1322 &self,
1323 ) -> Result<subc_control::TerminalHistory, tokio::task::JoinError> {
1324 let terminal_ring = Arc::clone(&self.inner.terminal_ring);
1325 let module_id = self.inner.module_id.clone();
1326 tokio::task::spawn_blocking(move || durable_terminal_history_of(&terminal_ring, &module_id))
1327 .await
1328 }
1329
1330 pub fn status(&self) -> Result<ModuleStatus, SuperviseError> {
1331 self.status_with_snapshot_lock(&self.inner.snapshot, None)
1332 .map(|(status, _)| status)
1333 }
1334
1335 pub(crate) fn next_retry_at_ms(&self) -> Result<Option<u64>, SuperviseError> {
1336 let state = lock_snapshot(&self.inner.snapshot)?;
1337 Ok(state
1338 .failed_retry
1339 .pending
1340 .filter(|_| state.state == ModuleState::Failed && state.enabled)
1341 .map(|retry| {
1342 unix_ms_now().saturating_add(
1343 u64::try_from(
1344 retry
1345 .deadline
1346 .saturating_duration_since(Instant::now())
1347 .as_millis(),
1348 )
1349 .unwrap_or(u64::MAX),
1350 )
1351 }))
1352 }
1353
1354 #[cfg(all(test, unix))]
1355 pub(crate) fn retry_deadline_for_test(&self) -> Option<Instant> {
1356 lock_snapshot(&self.inner.snapshot)
1357 .unwrap()
1358 .failed_retry
1359 .pending
1360 .map(|retry| retry.deadline)
1361 }
1362
1363 pub(crate) fn status_for_control(
1368 &self,
1369 caller: &'static str,
1370 ) -> Result<ModuleStatus, SuperviseError> {
1371 self.status_with_snapshot_lock(&self.inner.snapshot, Some(caller))
1372 .map(|(status, _)| status)
1373 }
1374
1375 fn status_with_snapshot_lock(
1376 &self,
1377 snapshot: &SharedSnapshot,
1378 caller: Option<&'static str>,
1379 ) -> Result<(ModuleStatus, Option<SpawnedFileIdentity>), SuperviseError> {
1380 let restart_policy = self
1381 .inner
1382 .configuration
1383 .lock()
1384 .map_err(|_| SuperviseError::StatePoisoned {
1385 module_id: Some(self.inner.module_id.clone()),
1386 })?
1387 .restart_policy;
1388 let mut guard = match caller {
1389 Some(caller) => lock_snapshot_for_control(snapshot, &self.inner.module_id, caller)?,
1390 None => lock_snapshot(snapshot)?,
1391 };
1392 let restart_count = guard.crash_restarts_in_window(restart_policy.window, Instant::now());
1395 let snapshot = guard.clone();
1396 drop(guard);
1397 let drain_timeout = *self.inner.effective_drain_timeout.lock().map_err(|_| {
1398 SuperviseError::StatePoisoned {
1399 module_id: Some(self.inner.module_id.clone()),
1400 }
1401 })?;
1402 let registration_active = self
1403 .inner
1404 .registry
1405 .get_module(&self.inner.module_id)
1406 .map_err(SuperviseError::Registry)?
1407 .is_some();
1408 let protocol = snapshot
1409 .spawned_protocol
1410 .unwrap_or(self.declared_protocol()?);
1411 let running_process =
1412 snapshot.enabled && snapshot.state == ModuleState::Running && snapshot.process_alive;
1413 let live = match protocol {
1419 ModuleProtocol::Subc => running_process && registration_active,
1420 ModuleProtocol::None => running_process,
1421 };
1422 let retained = self.inner.retained.waiting_detail(&self.inner.module_id);
1425 let carry_configured = self
1426 .inner
1427 .configuration
1428 .lock()
1429 .map_err(|_| SuperviseError::StatePoisoned {
1430 module_id: Some(self.inner.module_id.clone()),
1431 })?
1432 .spec
1433 .carry_containment;
1434 let recovery_block = carries_containment(
1435 carry_configured,
1436 self.inner
1437 .retained
1438 .has_carried_container(&self.inner.module_id),
1439 )
1440 .then(|| self.inner.retained.recovery_block())
1441 .flatten();
1442 let launch_nonce_source = observed_launch_nonce_source(&snapshot);
1443 let pid = snapshot.reported_pid();
1444 let mut health = snapshot.health;
1445 if let Some(detail) = recovery_block
1446 .as_ref()
1447 .or_else(|| retained.as_ref().map(|(_, detail)| detail))
1448 {
1449 health.detail = Some(match health.detail {
1450 Some(previous) => format!("{previous}; {detail}"),
1451 None => detail.clone(),
1452 });
1453 }
1454
1455 Ok((
1456 ModuleStatus {
1457 admission_refused: snapshot.admission_refused,
1458 legacy_registration_spawn: snapshot.legacy_registration_spawn,
1459 registration_declaration: snapshot.registration_declaration.clone(),
1460 stop_reason: snapshot.stop_reason,
1461 waiting_for_previous_pid: retained
1462 .as_ref()
1463 .map(|(pid, _)| *pid)
1464 .filter(|pid| *pid > 0)
1465 .or(snapshot.waiting_for_previous_pid),
1466 waiting_for_previous_detail: recovery_block
1467 .or_else(|| retained.map(|(_, detail)| detail))
1468 .or(snapshot.waiting_for_previous_detail),
1469 module_id: self.inner.module_id.clone(),
1470 launch_nonce_source,
1471 state: snapshot.state,
1472 enabled: snapshot.enabled,
1473 process_alive: snapshot.process_alive,
1474 registration_active,
1475 protocol,
1476 live,
1477 restart_count,
1478 lifetime_restarts: snapshot.lifetime_restarts,
1479 spawn_generation: snapshot.spawn_generation,
1480 swap_outcome: snapshot.swap_outcome,
1481 max_restarts: restart_policy.max_restarts,
1482 restart_window: restart_policy.window,
1483 drain_timeout,
1484 restart_backoff: restart_policy.backoff,
1485 restart_max_backoff: restart_policy.max_backoff,
1486 pid,
1487 spawned_at_ms: snapshot.spawned_at_ms,
1488 spawned_from: snapshot.spawned_from,
1489 launch_spec_digest: snapshot.launch_spec_digest,
1490 process_start_time: snapshot.process_start_time,
1491 last_exit: snapshot.last_exit,
1492 health,
1493 },
1494 snapshot.spawned_file_identity.clone(),
1495 ))
1496 }
1497
1498 #[cfg(test)]
1499 pub(crate) fn hold_snapshot_for_test(
1500 &self,
1501 acquired: std::sync::mpsc::Sender<()>,
1502 hold: Duration,
1503 ) -> std::thread::JoinHandle<()> {
1504 let snapshot = Arc::clone(&self.inner.snapshot);
1505 std::thread::spawn(move || {
1506 let _guard = snapshot.lock().expect("test snapshot lock is not poisoned");
1507 acquired
1508 .send(())
1509 .expect("test receiver waits for snapshot lock");
1510 std::thread::sleep(hold);
1511 })
1512 }
1513
1514 pub(crate) async fn status_and_running_image_agreement(
1520 &self,
1521 ) -> Result<(ModuleStatus, subc_control::RunningImageAgreement), SuperviseError> {
1522 let (status, identity) = self.status_with_snapshot_lock(&self.inner.snapshot, None)?;
1523 let image = self
1524 .inner
1525 .provenance_probe
1526 .observe(
1527 status.pid,
1528 status.spawned_from.as_deref(),
1529 identity,
1530 status.process_start_time,
1531 )
1532 .await;
1533 Ok((status, image))
1534 }
1535
1536 pub(crate) async fn running_image_agreement(&self) -> subc_control::RunningImageAgreement {
1537 let snapshot = match lock_snapshot(&self.inner.snapshot) {
1538 Ok(snapshot) => snapshot.clone(),
1539 Err(_) => {
1540 return subc_control::RunningImageAgreement::Unavailable {
1541 reason: subc_control::RunningImageUnavailableReason::NotRunning,
1542 };
1543 }
1544 };
1545 self.inner
1546 .provenance_probe
1547 .observe(
1548 snapshot.reported_pid(),
1549 snapshot.spawned_from.as_deref(),
1550 snapshot.spawned_file_identity.clone(),
1551 snapshot.process_start_time,
1552 )
1553 .await
1554 }
1555
1556 pub(crate) fn child_resource_usage(&self) -> subc_control::ChildResourceUsage {
1559 #[cfg(windows)]
1560 {
1561 let image = lock_snapshot(&self.inner.snapshot)
1562 .ok()
1563 .and_then(|snapshot| {
1564 snapshot
1565 .spawned_file_identity
1566 .as_ref()
1567 .and_then(|identity| identity.windows_image.clone())
1568 });
1569 match image {
1570 Some(image) => {
1571 crate::child_resources::read_windows_handle(image.process(), image.start_time())
1572 }
1573 None => subc_control::ChildResourceUsage::Unavailable {
1574 reason: subc_control::ChildResourceUnavailableReason::NotRunning,
1575 },
1576 }
1577 }
1578 #[cfg(not(windows))]
1579 {
1580 let (pid, start_time) = match lock_snapshot(&self.inner.snapshot) {
1581 Ok(snapshot) => (snapshot.reported_pid(), snapshot.process_start_time),
1582 Err(_) => {
1583 return subc_control::ChildResourceUsage::Unavailable {
1584 reason: subc_control::ChildResourceUnavailableReason::Unreadable,
1585 }
1586 }
1587 };
1588 crate::child_resources::read(pid, start_time)
1589 }
1590 }
1591
1592 #[cfg(all(test, any(target_os = "linux", windows)))]
1593 pub(crate) fn subtree_target(&self) -> crate::subtree_resources::Target {
1594 self.inner
1595 .snapshot
1596 .try_lock()
1597 .map(|snapshot| snapshot.subtree_target.clone())
1598 .unwrap_or(crate::subtree_resources::Target::Unavailable("read_failed"))
1599 }
1600
1601 #[cfg(test)]
1602 pub(crate) fn set_subtree_target_for_test(&self, target: crate::subtree_resources::Target) {
1603 self.inner.snapshot.lock().unwrap().subtree_target = target;
1604 }
1605
1606 pub(crate) fn will_recover_after_connection_loss(&self) -> Result<bool, SuperviseError> {
1607 let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
1608 Ok(match snapshot.state {
1609 ModuleState::Restarting => true,
1610 ModuleState::Failed | ModuleState::Disabled => false,
1611 _ if snapshot.enabled && snapshot.respawn_pending => true,
1612 _ => daemon_will_restart(
1613 &mut snapshot,
1614 &self
1615 .inner
1616 .configuration
1617 .lock()
1618 .map_err(|_| SuperviseError::StatePoisoned {
1619 module_id: Some(self.inner.module_id.clone()),
1620 })?
1621 .restart_policy,
1622 Instant::now(),
1623 ),
1624 })
1625 }
1626
1627 #[cfg(test)]
1628 pub(crate) fn is_warming(&self) -> Result<bool, SuperviseError> {
1629 self.is_warming_with_snapshot_lock(None)
1630 }
1631
1632 pub(crate) fn is_warming_for_control(
1633 &self,
1634 caller: &'static str,
1635 ) -> Result<bool, SuperviseError> {
1636 self.is_warming_with_snapshot_lock(Some(caller))
1637 }
1638
1639 fn is_warming_with_snapshot_lock(
1640 &self,
1641 caller: Option<&'static str>,
1642 ) -> Result<bool, SuperviseError> {
1643 let snapshot = match caller {
1644 Some(caller) => {
1645 lock_snapshot_for_control(&self.inner.snapshot, &self.inner.module_id, caller)?
1646 }
1647 None => lock_snapshot(&self.inner.snapshot)?,
1648 }
1649 .clone();
1650 Ok(matches!(
1651 snapshot.state,
1652 ModuleState::Starting | ModuleState::Running | ModuleState::Restarting
1653 ))
1654 }
1655
1656 pub(crate) fn declared_protocol(&self) -> Result<ModuleProtocol, SuperviseError> {
1660 let configured = self
1661 .inner
1662 .configuration
1663 .lock()
1664 .map_err(|_| SuperviseError::StatePoisoned {
1665 module_id: Some(self.inner.module_id.clone()),
1666 })?
1667 .spec
1668 .protocol;
1669 let state = lock_snapshot(&self.inner.snapshot)?;
1670 Ok(state.spawned_protocol.unwrap_or(configured))
1671 }
1672
1673 pub(crate) fn configuration(&self) -> Result<(ModuleSpec, HealthConfig), SuperviseError> {
1674 let configuration =
1675 self.inner
1676 .configuration
1677 .lock()
1678 .map_err(|_| SuperviseError::StatePoisoned {
1679 module_id: Some(self.inner.module_id.clone()),
1680 })?;
1681 Ok((configuration.spec.clone(), configuration.health.clone()))
1682 }
1683
1684 pub(crate) fn configured_register_timeout(&self) -> Result<Duration, SuperviseError> {
1685 self.inner
1686 .configuration
1687 .lock()
1688 .map(|configuration| configuration.register_timeout)
1689 .map_err(|_| SuperviseError::StatePoisoned {
1690 module_id: Some(self.inner.module_id.clone()),
1691 })
1692 }
1693
1694 pub(crate) fn configured_enabled(&self) -> Result<bool, SuperviseError> {
1695 self.inner
1696 .configuration
1697 .lock()
1698 .map(|configuration| configuration.enabled)
1699 .map_err(|_| SuperviseError::StatePoisoned {
1700 module_id: Some(self.inner.module_id.clone()),
1701 })
1702 }
1703
1704 #[cfg(any(test, feature = "test-support"))]
1708 pub async fn update_spec_for_test(&self, spec: ModuleSpec) -> Result<(), SuperviseError> {
1709 let (_, health) = self.configuration()?;
1710 let drain_timeout_ms = u64::try_from(
1711 self.inner
1712 .effective_drain_timeout
1713 .lock()
1714 .unwrap_or_else(|poisoned| poisoned.into_inner())
1715 .as_millis(),
1716 )
1717 .ok();
1718 self.update_configuration(spec, health, drain_timeout_ms)
1719 .await
1720 }
1721
1722 pub(crate) async fn update_configuration(
1723 &self,
1724 spec: ModuleSpec,
1725 health: HealthConfig,
1726 drain_timeout_ms: Option<u64>,
1727 ) -> Result<(), SuperviseError> {
1728 if spec.module_id != self.inner.module_id {
1729 return Err(SuperviseError::InvalidSpec {
1730 reason: "a supervised module's module_id cannot be changed".to_string(),
1731 });
1732 }
1733 validate_spec(&spec)?;
1734 let (reply_tx, reply_rx) = oneshot::channel();
1735 self.inner
1736 .commands
1737 .send(SupervisorCommand::UpdateConfiguration {
1738 spec: spec.clone(),
1739 health: health.clone(),
1740 drain_timeout_ms,
1741 reply: reply_tx,
1742 })
1743 .await
1744 .map_err(|_| SuperviseError::CommandClosed {
1745 module_id: self.inner.module_id.clone(),
1746 })?;
1747 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
1748 module_id: self.inner.module_id.clone(),
1749 })??;
1750 let mut configuration =
1751 self.inner
1752 .configuration
1753 .lock()
1754 .map_err(|_| SuperviseError::StatePoisoned {
1755 module_id: Some(self.inner.module_id.clone()),
1756 })?;
1757 configuration.spec = spec;
1758 configuration.health = health;
1759 Ok(())
1760 }
1761}
1762
1763impl Drop for SupervisedModuleInner {
1764 fn drop(&mut self) {
1765 let Ok(mut monitor) = self.monitor.lock() else {
1766 return;
1767 };
1768 if let Some(monitor) = monitor.as_ref().filter(|monitor| !monitor.is_finished()) {
1769 let _ = update_snapshot(&self.snapshot, Some(&self.module_id), |state| {
1770 state.state = ModuleState::Stopped;
1771 clear_current_process_facts(state);
1772 });
1773 monitor.abort();
1774 }
1775 let _ = monitor.take();
1776 }
1777}
1778
1779#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1783pub enum SwapOutcome {
1784 Cutover,
1785 SupersededByConfigRestart,
1786}
1787
1788impl SwapOutcome {
1789 pub fn as_str(self) -> &'static str {
1790 match self {
1791 Self::Cutover => "cutover",
1792 Self::SupersededByConfigRestart => "superseded_by_config_restart",
1793 }
1794 }
1795}
1796
1797#[derive(Debug)]
1798pub enum SuperviseError {
1799 ConfigHeld {
1800 module_id: String,
1801 code: String,
1802 detail: String,
1803 },
1804 ConfigDeliveryDeferred {
1805 module_id: String,
1806 },
1807 InvalidSpec {
1808 reason: String,
1809 },
1810 Spawn {
1811 program: PathBuf,
1812 source: io::Error,
1813 cgroup_path: Option<PathBuf>,
1814 },
1815 Cgroup {
1816 module_id: String,
1817 source: io::Error,
1818 },
1819 LaunchNonce {
1823 reason: String,
1824 },
1825 Wait {
1826 module_id: String,
1827 source: io::Error,
1828 },
1829 Kill {
1830 module_id: String,
1831 source: io::Error,
1832 },
1833 Forwarding(ForwardingError),
1834 Registry(RegistryError),
1835 ReloadUnavailable {
1836 module_id: String,
1837 reason: String,
1838 },
1839 Disabled {
1844 module_id: String,
1845 },
1846 ReloadFailed {
1847 module_id: String,
1848 reason: String,
1849 },
1850 RegistrationStillActive {
1851 module_id: String,
1852 waited: Duration,
1853 },
1854 StatePoisoned {
1855 module_id: Option<String>,
1856 },
1857 CommandClosed {
1858 module_id: String,
1859 },
1860 SwapInProgress {
1864 module_id: String,
1865 },
1866 SwapRefused {
1868 module_id: String,
1869 reason: SwapRefusal,
1870 },
1871 SwapFailed {
1875 module_id: String,
1876 arm: SwapFailureArm,
1877 detail: String,
1878 candidate_exit: Option<ExitReport>,
1881 },
1882}
1883
1884#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1886pub enum SwapRefusal {
1887 OverlapExclusive,
1889 NotRegistered,
1892 ProtocolNone,
1895 NotConfigured,
1898 AlreadySwapping,
1900}
1901
1902impl SwapRefusal {
1903 pub fn as_str(self) -> &'static str {
1904 match self {
1905 Self::OverlapExclusive => "overlap_exclusive",
1906 Self::NotRegistered => "not_registered",
1907 Self::ProtocolNone => "protocol_none",
1908 Self::NotConfigured => "not_configured",
1909 Self::AlreadySwapping => "already_swapping",
1910 }
1911 }
1912}
1913
1914#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1917pub enum SwapFailureArm {
1918 SpawnFailed,
1920 NeverRegistered,
1922 NeverReady,
1924 CandidateExited,
1926 CandidateUnhealthy,
1928 Interrupted,
1932 CutoverLost,
1937}
1938
1939impl SwapFailureArm {
1940 pub fn as_str(self) -> &'static str {
1941 match self {
1942 Self::SpawnFailed => "spawn_failed",
1943 Self::NeverRegistered => "never_registered",
1944 Self::NeverReady => "never_ready",
1945 Self::CandidateExited => "candidate_exited",
1946 Self::CandidateUnhealthy => "candidate_unhealthy",
1947 Self::Interrupted => "interrupted",
1948 Self::CutoverLost => "cutover_lost",
1949 }
1950 }
1951}
1952
1953impl SuperviseError {
1954 pub(crate) fn is_config_gate_error(&self) -> bool {
1955 match self {
1956 Self::ConfigHeld { .. } => true,
1957 Self::Spawn { source, .. } => source
1958 .get_ref()
1959 .is_some_and(|cause| cause.is::<crate::config_gate::GateError>()),
1960 _ => false,
1961 }
1962 }
1963}
1964
1965impl fmt::Display for SuperviseError {
1966 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1967 match self {
1968 Self::ConfigHeld { module_id, code, detail } => write!(f, "{code}: module '{module_id}' held: {detail}"),
1969 Self::ConfigDeliveryDeferred { module_id } => write!(f, "config_gated: module '{module_id}' is waiting for its exited delivery target's failure record"),
1970 Self::InvalidSpec { reason } => write!(f, "invalid module spec: {reason}"),
1971 Self::Spawn {
1972 program,
1973 source,
1974 cgroup_path: Some(cgroup_path),
1975 } => write!(
1976 f,
1977 "failed to place module in cgroup '{}' while spawning '{}': {source}",
1978 cgroup_path.display(),
1979 program.display()
1980 ),
1981 Self::Spawn {
1982 program,
1983 source,
1984 cgroup_path: None,
1985 } => write!(
1986 f,
1987 "failed to spawn module '{}': {source}",
1988 program.display()
1989 ),
1990 Self::Cgroup { module_id, source } => {
1991 write!(
1992 f,
1993 "failed to prepare cgroup for module '{module_id}': {source}"
1994 )
1995 }
1996 Self::LaunchNonce { reason } => {
1997 write!(
1998 f,
1999 "failed to generate reserved-module launch nonce: {reason}"
2000 )
2001 }
2002 Self::Wait { module_id, source } => {
2003 write!(f, "failed to wait for module '{module_id}': {source}")
2004 }
2005 Self::Kill { module_id, source } => {
2006 write!(f, "failed to kill module '{module_id}': {source}")
2007 }
2008 Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
2009 Self::Registry(err) => write!(f, "registry error: {err}"),
2010 Self::ReloadUnavailable { module_id, reason } => {
2011 write!(f, "reload unavailable for module '{module_id}': {reason}")
2012 }
2013 Self::Disabled { module_id } => {
2014 write!(
2015 f,
2016 "module '{module_id}' is disabled; enable it before restart or reload"
2017 )
2018 }
2019 Self::ReloadFailed { module_id, reason } => {
2020 write!(f, "reload failed for module '{module_id}': {reason}")
2021 }
2022 Self::RegistrationStillActive { module_id, waited } => write!(
2023 f,
2024 "module '{module_id}' registration remained active after waiting {waited:?}"
2025 ),
2026 Self::StatePoisoned { module_id } => match module_id {
2027 Some(module_id) => {
2028 write!(f, "supervisor state for module '{module_id}' was poisoned")
2029 }
2030 None => write!(f, "supervisor state was poisoned"),
2031 },
2032 Self::CommandClosed { module_id } => {
2033 write!(
2034 f,
2035 "supervisor command channel for module '{module_id}' is closed"
2036 )
2037 }
2038 Self::SwapInProgress { module_id } => write!(
2039 f,
2040 "module '{module_id}' is being swapped; retry once the swap has cut over or failed, or stop the module to abort the swap"
2041 ),
2042 Self::SwapRefused { module_id, reason } => match reason {
2043 SwapRefusal::OverlapExclusive => write!(
2044 f,
2045 "module '{module_id}' is declared overlap: \"exclusive\" (the default): two processes of it must not run at once, so it cannot be swapped; use a plain restart, or declare overlap: \"safe\" in its config if it really tolerates a second process"
2046 ),
2047 SwapRefusal::NotRegistered => write!(
2048 f,
2049 "module '{module_id}' is not registered, so there is no serving process to keep while a replacement warms; use a plain restart"
2050 ),
2051 SwapRefusal::ProtocolNone => write!(
2052 f,
2053 "module '{module_id}' is protocol: \"none\" and never registers, so a swap could never see its replacement become ready; use a plain restart"
2054 ),
2055 SwapRefusal::NotConfigured => write!(
2056 f,
2057 "module '{module_id}' cannot be swapped: the supervisor was built without the forwarding table or shared handle a swap needs"
2058 ),
2059 SwapRefusal::AlreadySwapping => {
2060 write!(f, "module '{module_id}' is already being swapped")
2061 }
2062 },
2063 Self::SwapFailed {
2064 module_id,
2065 arm,
2066 detail,
2067 ..
2068 } => write!(
2069 f,
2070 "swap of module '{module_id}' failed ({}): {detail}; the running process was left serving",
2071 arm.as_str()
2072 ),
2073 }
2074 }
2075}
2076
2077impl Error for SuperviseError {
2078 fn source(&self) -> Option<&(dyn Error + 'static)> {
2079 match self {
2080 Self::Spawn { source, .. }
2081 | Self::Cgroup { source, .. }
2082 | Self::Wait { source, .. }
2083 | Self::Kill { source, .. } => Some(source),
2084 Self::Forwarding(err) => Some(err),
2085 Self::Registry(err) => Some(err),
2086 Self::LaunchNonce { .. }
2087 | Self::ConfigDeliveryDeferred { .. }
2088 | Self::ConfigHeld { .. }
2089 | Self::InvalidSpec { .. }
2090 | Self::ReloadUnavailable { .. }
2091 | Self::Disabled { .. }
2092 | Self::ReloadFailed { .. }
2093 | Self::RegistrationStillActive { .. }
2094 | Self::StatePoisoned { .. }
2095 | Self::CommandClosed { .. }
2096 | Self::SwapInProgress { .. }
2097 | Self::SwapRefused { .. }
2098 | Self::SwapFailed { .. } => None,
2099 }
2100 }
2101}
2102
2103fn unix_ms_now() -> u64 {
2104 SystemTime::now()
2105 .duration_since(UNIX_EPOCH)
2106 .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
2107 .unwrap_or(0)
2108}
2109
2110fn update_snapshot(
2111 snapshot: &SharedSnapshot,
2112 module_id: Option<&str>,
2113 update: impl FnOnce(&mut SupervisorSnapshot),
2114) -> Result<(), SuperviseError> {
2115 let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
2116 module_id: module_id.map(ToOwned::to_owned),
2117 })?;
2118 update(&mut state);
2119 Ok(())
2120}
2121
2122const SLOW_SNAPSHOT_LOCK_THRESHOLD: Duration = Duration::from_millis(250);
2123
2124fn lock_snapshot_for_control<'a>(
2125 snapshot: &'a SharedSnapshot,
2126 module_id: &str,
2127 caller: &'static str,
2128) -> Result<std::sync::MutexGuard<'a, SupervisorSnapshot>, SuperviseError> {
2129 let started_at = Instant::now();
2130 let guard = lock_snapshot(snapshot)?;
2131 let waited = started_at.elapsed();
2132 if waited >= SLOW_SNAPSHOT_LOCK_THRESHOLD {
2133 warn!(
2134 module_id = %module_id,
2135 waited_ms = waited.as_millis() as u64,
2136 caller = %caller,
2137 "slow snapshot lock"
2138 );
2139 }
2140 Ok(guard)
2141}
2142
2143fn lock_snapshot(
2144 snapshot: &SharedSnapshot,
2145) -> Result<std::sync::MutexGuard<'_, SupervisorSnapshot>, SuperviseError> {
2146 snapshot
2147 .lock()
2148 .map_err(|_| SuperviseError::StatePoisoned { module_id: None })
2149}
2150
2151#[cfg(all(test, unix))]
2152mod restart_ordering_tests;
2153
2154#[cfg(all(test, target_os = "macos"))]
2155#[path = "supervise/suspended_spawn_tests.rs"]
2156mod suspended_spawn_tests;
2157
2158#[cfg(all(test, target_os = "linux"))]
2159#[path = "supervise/cgroup_reap_tests.rs"]
2160mod cgroup_reap_tests;
2161
2162#[cfg(test)]
2163#[path = "supervise/supervise_tests.rs"]
2164mod tests;
2165
2166#[cfg(test)]
2167#[path = "supervise/spawn_record_tests.rs"]
2168mod spawn_record_tests;
2169
2170#[cfg(all(test, target_os = "linux"))]
2171#[path = "supervise/spawn_image_tests.rs"]
2172mod spawn_image_tests;
2173
2174#[cfg(test)]
2175#[path = "supervise/slot_registration_wait_tests.rs"]
2176mod slot_registration_wait_tests;
2177
2178#[cfg(test)]
2179#[path = "supervise/terminal_history_tests.rs"]
2180mod terminal_history_tests;
2181
2182#[cfg(all(test, unix))]
2183#[path = "supervise/health_event_tests.rs"]
2184mod health_event_tests;
2185
2186#[cfg(test)]
2187#[path = "supervise/drain_busy_reprobe_tests.rs"]
2188mod drain_busy_reprobe_tests;
2189
2190#[cfg(test)]
2191#[path = "supervise/health_evidence_tests.rs"]
2192mod health_evidence_tests;
2193
2194#[cfg(test)]
2195#[path = "supervise/health_tombstone_tests.rs"]
2196mod health_tombstone_tests;
2197
2198#[cfg(test)]
2199#[path = "supervise/child_env_tests.rs"]
2200mod child_env_tests;
2201
2202#[cfg(test)]
2203#[path = "supervise/jitter_tests.rs"]
2204mod jitter_tests;
2205
2206#[cfg(all(test, target_os = "linux"))]
2207#[path = "supervise/cgroup_placement_tests.rs"]
2208mod cgroup_placement_tests;
2209
2210#[cfg(test)]
2211#[path = "supervise/spawn_subscriber_lag_tests.rs"]
2212mod spawn_subscriber_lag_tests;
2213
2214#[cfg(test)]
2215#[path = "supervise/terminal_history_read_concurrency_tests.rs"]
2216mod terminal_history_read_concurrency_tests;
2217
2218#[cfg(test)]
2223#[path = "supervise/stderr_settle_tests.rs"]
2224mod stderr_settle_tests;
2225
2226#[cfg(all(test, windows))]
2240#[path = "supervise/job_containment_tests.rs"]
2241mod job_containment_tests;
2242
2243#[cfg(test)]
2244#[path = "supervise/privacy_trampoline_configuration_tests.rs"]
2245mod privacy_trampoline_configuration_tests;
2246
2247#[cfg(test)]
2248#[path = "supervise/privacy_exec_boundary_tests.rs"]
2249mod privacy_exec_boundary_tests;
2250
2251#[cfg(all(test, unix))]
2255#[path = "supervise/launch_nonce_descriptor_tests.rs"]
2256mod launch_nonce_descriptor_tests;
2257
2258#[cfg(all(test, target_os = "linux"))]
2259#[path = "supervise/cgroup_containment_tests.rs"]
2260mod cgroup_containment_tests;
2261
2262#[cfg(all(test, unix))]
2265#[path = "supervise/record_write_stall_tests.rs"]
2266mod record_write_stall_tests;
2267
2268#[cfg(all(test, unix))]
2269#[path = "supervise/retained_status_tests.rs"]
2270mod retained_status_tests;