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