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
220use std::{
221 collections::{HashMap, HashSet, VecDeque},
222 error::Error,
223 fmt, io,
224 path::PathBuf,
225 process::{ExitStatus, Stdio},
226 sync::{Arc, Mutex, OnceLock, TryLockError},
227 time::{Duration, SystemTime, UNIX_EPOCH},
228};
229
230use cortexkit_log::Retention;
231use serde_json::Value;
232use sha2::{Digest, Sha256};
233use subc_control::{
234 ClientControlPush, LiveSpawn, ModuleProtocol, RouteCloseReason, SpawnCursor, SpawnEvent,
235 SpawnEventKind, SpawnSnapshot, SupervisorHealthStatus, TerminalDisposition, TerminalExitKind,
236};
237use subc_protocol::{
238 manifest::{SelfSignalKind, SignalAnchor},
239 session::{
240 HealthReport, HealthStatus, ModuleControlCommand, ModuleControlRequest,
241 MODULE_CONTROL_OP_HEALTH_CHECK,
242 },
243 Flags, FrameType, Principal, Priority, SUBC_LAUNCH_NONCE_ENV, SUBC_MODULE_ID_ENV,
244};
245use tokio::{
246 process::{Child, Command},
247 sync::{mpsc, oneshot, watch, Mutex as AsyncMutex},
248 task::JoinHandle,
249 time::{sleep, sleep_until, timeout, timeout_at, Instant},
250};
251use tracing::{debug, error, info, warn};
252
253use crate::{
254 child_output::StderrPump,
255 child_roster::ChildRoster,
256 daemon_config::{
257 CAPTURE_KEEP_ENV, CAPTURE_MAX_AGE_DAYS_ENV, CAPTURE_MAX_FILE_MB_ENV, CK_LOG_ENV,
258 },
259 forwarding::{
260 CloseReason, ForwardingError, ForwardingTable, GoodbyeTarget, ModuleControlRpcOutcome,
261 ModuleDrainTarget, PendingModuleControlRpc,
262 },
263 provenance::{ExecutableIdentityProbe, SpawnedFileIdentity},
264 registry::{ConnectionId, RegistrationEndReason, RegistryError},
265 stderr_tail::{ChildOutputSink, StderrRing, StderrTailConfig, StderrTailSnapshot},
266 terminal_ring::{TerminalHistorySnapshot, TerminalRecord, TerminalRing, TerminalRingConfig},
267 Frame, FrameSink, Registry,
268};
269
270#[cfg(not(windows))]
271use crate::provenance::spawned_file_identity;
272
273#[path = "supervise_swap.rs"]
274mod swap;
275use swap::OpenSwap;
276use swap::PromotionObserverSlot;
277pub(crate) use swap::SwapHelloAdmission;
278pub(crate) use swap::SwapPromotionObserver;
279pub use swap::DEFAULT_SWAP_READY_TIMEOUT;
280
281#[path = "supervise_activity.rs"]
282mod activity;
283
284#[cfg(unix)]
285#[path = "supervise/admission.rs"]
286mod admission;
287mod admission_exit;
288#[cfg(all(test, target_os = "linux"))]
289mod async_spawn_tests;
290#[cfg(all(test, windows))]
291mod carried_job_tests;
292mod config_delivery;
293use config_delivery::cancel_deferred_reload;
294use config_delivery::defer_config_spawn;
295use config_delivery::hold_config_respawn;
296use config_delivery::hold_config_spawn;
297use config_delivery::record_approved_attempt_failure;
298use config_delivery::try_park_config_attempt;
299use config_delivery::CONFIG_ADMISSION_RETRY_DELAY;
300mod content_binding;
301mod program_binding;
302mod registration;
303pub(crate) mod resume_hello;
304use registration::arm_registration_deadline;
305use registration::constant_time_eq;
306use registration::handle_reload_child_registration_failure;
307use registration::handle_reload_spawn_failure;
308pub(crate) use registration::notify_registration_release;
309use registration::registration_child_is_running;
310use registration::registration_failure_exit_report;
311use registration::release_dead_registration;
312use registration::wait_for_registration_after_reload;
313use registration::wait_for_registration_release;
314use registration::wait_for_slot_registration_release;
315use registration::watch_registration;
316#[cfg(test)]
317use registration::IdentitySamplePause;
318use registration::RegistrationWaitOutcome;
319use registration::RegistrationWatch;
320use registration::ReloadRegistrationFailure;
321pub(crate) use registration::ReservedHelloRejection;
322pub(crate) use registration::ReservedHelloVerification;
323pub(crate) use registration::DEFAULT_REGISTER_TIMEOUT;
324use registration::REGISTRY_RELEASE_POLL;
325use registration::REGISTRY_RELEASE_TIMEOUT;
326pub(crate) mod script;
327type NonceLaunches = HashMap<String, (String, std::sync::Weak<RegistrationSpawn>)>;
329pub(crate) use registration::NonceAttestation;
330#[cfg(all(test, unix))]
331pub(crate) use registration::RegistrationProof;
332pub(crate) use registration::RegistrationSpawn;
333pub(crate) use registration::REGISTRATION_CHANNEL_CLOSED;
334#[cfg(all(test, unix))]
335pub(crate) mod unix_channel_placement_tests;
336use program_binding::ProgramBindingPublication;
337mod config_exit_failure;
338#[cfg(all(test, any(target_os = "linux", windows)))]
339mod missing_path_tests;
340#[cfg(all(test, unix))]
341mod program_binding_tests;
342#[cfg(all(test, windows))]
343mod program_binding_windows_tests;
344#[cfg(all(test, windows))]
345mod windows_channel_tests;
346pub use config_exit_failure::ModuleStopReason;
347mod unregistered_stop;
348use unregistered_stop::stop_unregistered_child;
349#[cfg(target_os = "linux")]
350#[path = "supervise/cgroup_label.rs"]
351mod cgroup_label;
352#[cfg(all(test, unix))]
353mod config_exit_hold_tests;
354pub(crate) mod containment;
355#[cfg(all(test, unix))]
356mod containment_tests;
357#[cfg(target_os = "linux")]
358mod ordinary_cgroup;
359#[cfg(unix)]
360pub(crate) mod plain_group;
361#[cfg(all(test, target_os = "linux"))]
362mod plain_group_regression;
363mod slow_retry;
364use slow_retry::{FailedRetry, FailureContext};
365mod host_health;
366use host_health::HostHealth;
367
368#[cfg(test)]
369mod crash_admission_tests;
370mod crash_budget;
371use crash_budget::budgeted_restart_child;
372use crash_budget::daemon_will_restart;
373use crash_budget::log_crash_respawn;
374use crash_budget::reset_restart_count;
375use crash_budget::respawn_still_pending;
376use crash_budget::schedule_respawn;
377use crash_budget::CrashRestartSchedule;
378pub use crash_budget::RestartPolicy;
379#[cfg(all(test, unix))]
380mod mark_readiness_tests;
381#[cfg(all(test, unix))]
382mod slow_retry_tests;
383use crash_budget::{admit_running_child_async, spawn_and_mark_running_async};
384
385struct SupervisedChild {
386 registration_spawn: Option<Arc<RegistrationSpawn>>,
387 #[cfg(any(unix, windows))]
389 registration_channel: Option<SpawnRegistrationChannel>,
390 live_program_binding: Option<Arc<content_binding::LiveProgramBinding>>,
391 registered_config_connection: Option<ConnectionId>,
392 admission_base: Option<subc_config::Digest>,
393 registration_declaration: Option<String>,
394 _program_binding: Option<ProgramBindingPublication>,
395 subtree_target: crate::subtree_resources::Target,
396 child: containment::ProcessChild,
397 exec: crate::activity::ExecOwner,
398 #[cfg(windows)]
399 nonce_delivery: Option<subc_os::LaunchNoncePipeDelivery>,
400 #[cfg(target_os = "macos")]
401 privacy_exec: Option<PrivacyExec>,
402 #[cfg(target_os = "macos")]
409 report_ready: Arc<OnceLock<()>>,
410 spawn_failure: Option<String>,
413 admission_kill_sent: bool,
416 protocol: ModuleProtocol,
421 #[cfg(target_os = "linux")]
428 module_id: String,
429 #[cfg(target_os = "linux")]
430 cgroup_placement: Option<subc_cgroup::Placement>,
431 #[cfg(target_os = "linux")]
432 unresolved_cgroup: Option<ordinary_cgroup::Unresolved>,
433 #[cfg(windows)]
456 job: Option<Arc<Mutex<subc_jobobject::JobObject>>>,
457 stdout_pump: Option<tokio::sync::oneshot::Receiver<()>>,
458 stderr_pump: Option<StderrPump>,
459 #[cfg(unix)]
460 capture_stop: Option<crate::child_output::StopReaders>,
461 #[cfg(unix)]
462 late_output_lost: bool,
463 stderr_ring: Arc<Mutex<StderrRing>>,
464 spawned_at: Instant,
467 config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
468 registration_deadline: Option<Instant>,
471 registration_watch: Option<RegistrationWatch>,
472 spawned_at_ms: u64,
473 spawned_from: PathBuf,
474 launch_spec_digest: LaunchSpecDigest,
475 spawned_file_identity: Option<SpawnedFileIdentity>,
476 process_start_time: Option<u64>,
477 process_identity: Option<ProcessIdentity>,
478 pid: u32,
479 roster_guard: Option<crate::child_roster::RosterGuard>,
482}
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 #[cfg(windows)]
553 pub(crate) nonce_pipe_refusal: Option<&'static str>,
554 pub(crate) legacy_registration_spawn: bool,
555 pub(crate) registration_declaration: Option<String>,
556 pub module_id: String,
557 pub stop_reason: Option<ModuleStopReason>,
560 pub waiting_for_previous_pid: Option<u32>,
562 pub waiting_for_previous_detail: Option<String>,
564 pub launch_nonce_source: Option<String>,
569 pub state: ModuleState,
570 pub enabled: bool,
571 pub process_alive: bool,
572 pub registration_active: bool,
573 pub protocol: ModuleProtocol,
578 pub live: bool,
589 pub restart_count: u32,
593 pub lifetime_restarts: u32,
597 pub spawn_generation: u64,
598 pub swap_outcome: Option<SwapOutcome>,
600 pub max_restarts: u32,
605 pub restart_window: Duration,
609 pub drain_timeout: Duration,
613 pub restart_backoff: Duration,
614 pub restart_max_backoff: Duration,
615 pub pid: Option<u32>,
620 pub spawned_at_ms: Option<u64>,
621 pub spawned_from: Option<PathBuf>,
622 pub(crate) launch_spec_digest: Option<LaunchSpecDigest>,
623 pub process_start_time: Option<u64>,
624 pub last_exit: Option<ExitReport>,
625 pub health: ModuleHealthStatus,
626}
627
628#[derive(Debug, Clone, PartialEq)]
629struct SupervisorSnapshot {
630 admission_refused: Option<String>,
631 #[cfg(windows)]
632 nonce_pipe_refusal: Option<&'static str>,
633 config_hold_parked: bool,
635 config_hold_daemon_initiated: bool,
638 config_hold_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
640 approved_start_failure: Option<(crate::config_gate::runtime::ApprovalIdentity, String)>,
642 legacy_registration_spawn: bool,
643 registration_declaration: Option<String>,
644 stop_reason: Option<ModuleStopReason>,
645 config_exit_failed_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
646 subtree_target: crate::subtree_resources::Target,
647 failed_retry: FailedRetry,
648 exec_outcome: Option<Arc<crate::activity::ExecOutcome>>,
649 #[cfg(windows)]
650 pipe_consumed: Option<Arc<OnceLock<()>>>,
651 #[cfg(test)]
653 actor_turns: u64,
654 #[cfg(test)]
657 actor_select: Option<ActorSelectCheckpoint>,
658 state: ModuleState,
659 enabled: bool,
660 process_alive: bool,
661 spawned_protocol: Option<ModuleProtocol>,
662 spawn_failure: Option<String>,
663 waiting_for_previous_pid: Option<u32>,
664 waiting_for_previous_detail: Option<String>,
665 crash_restarts: VecDeque<Instant>,
671 lifetime_restarts: u32,
672 spawn_generation: u64,
681 swap_outcome: Option<SwapOutcome>,
682 pid: Option<u32>,
683 #[cfg(target_os = "macos")]
684 report_ready: Option<Arc<OnceLock<()>>>,
685 reaped_pid: Option<u32>,
687 respawn_pending: bool,
689 coalesced_restart_pending: bool,
691 spawned_at_ms: Option<u64>,
692 spawned_from: Option<PathBuf>,
693 launch_spec_digest: Option<LaunchSpecDigest>,
694 spawned_file_identity: Option<SpawnedFileIdentity>,
695 process_start_time: Option<u64>,
696 deliberate_severance: Option<ProcessIdentity>,
697 last_exit: Option<ExitReport>,
698 drain_disposition_detail: Option<String>,
700 health: ModuleHealthStatus,
701 last_probe_evidence: Option<HealthProbeEvidence>,
702 in_alternate_slot: bool,
707 draining_to_replace: bool,
714 configuration_updated_since_spawn: bool,
720}
721
722impl SupervisorSnapshot {
723 fn reported_pid(&self) -> Option<u32> {
728 #[cfg(target_os = "macos")]
729 if self
730 .report_ready
731 .as_ref()
732 .is_some_and(|ready| ready.get().is_none())
733 {
734 return None;
735 }
736 self.pid
737 }
738
739 fn starting() -> Self {
740 Self::new(ModuleState::Starting, true)
741 }
742
743 fn disabled() -> Self {
744 Self::new(ModuleState::Disabled, false)
745 }
746
747 fn clear_crash_restarts(&mut self) {
752 self.crash_restarts.clear();
753 }
754
755 fn new(state: ModuleState, enabled: bool) -> Self {
756 Self {
757 admission_refused: None,
758 #[cfg(windows)]
759 nonce_pipe_refusal: None,
760 config_hold_parked: false,
761 config_hold_daemon_initiated: false,
762 config_hold_approval: None,
763 approved_start_failure: None,
764 legacy_registration_spawn: false,
765 registration_declaration: None,
766 stop_reason: None,
767 config_exit_failed_approval: None,
768 subtree_target: crate::subtree_resources::Target::Unavailable("not_running"),
769 failed_retry: FailedRetry::default(),
770 exec_outcome: None,
771 #[cfg(test)]
772 actor_turns: 0,
773 #[cfg(test)]
774 actor_select: None,
775 state,
776 enabled,
777 process_alive: false,
778 #[cfg(windows)]
779 pipe_consumed: None,
780 spawned_protocol: None,
781 spawn_failure: None,
782 waiting_for_previous_pid: None,
783 waiting_for_previous_detail: None,
784 crash_restarts: VecDeque::new(),
785 lifetime_restarts: 0,
786 spawn_generation: 0,
787 swap_outcome: None,
788 pid: None,
789 #[cfg(target_os = "macos")]
790 report_ready: None,
791 reaped_pid: None,
792 respawn_pending: false,
793 coalesced_restart_pending: false,
794 spawned_at_ms: None,
795 spawned_from: None,
796 launch_spec_digest: None,
797 spawned_file_identity: None,
798 process_start_time: None,
799 deliberate_severance: None,
800 last_exit: None,
801 drain_disposition_detail: None,
802 health: ModuleHealthStatus::default(),
803 last_probe_evidence: None,
804 in_alternate_slot: false,
805 draining_to_replace: false,
806 configuration_updated_since_spawn: false,
807 }
808 }
809}
810
811type SharedSnapshot = Arc<Mutex<SupervisorSnapshot>>;
812
813#[derive(Debug, Clone, Copy)]
814enum RespawnKind {
815 Spawn,
816 CrashRestart,
817 Reload,
818}
819
820#[derive(Debug, Clone)]
821struct PendingRespawn {
822 deadline: Instant,
823 kind: RespawnKind,
824 daemon_initiated: bool,
825 approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
826}
827
828impl PendingRespawn {
829 fn failure_context(&self, runtime: &SupervisorRuntimeConfig) -> FailureContext {
830 FailureContext {
831 approval: self.approval.clone(),
832 ..runtime.failure_context(self.daemon_initiated)
833 }
834 }
835}
836
837type ReloadReply = oneshot::Sender<Result<(), SuperviseError>>;
838
839#[derive(Debug, Clone)]
840struct SupervisorRuntimeConfig {
841 registry: Arc<Registry>,
842 config_delivery: Option<config_delivery::ConfigDelivery>,
843 recovery_is_daemon: bool,
845 start_requester: Option<Principal>,
846 pending_activity_restart: bool,
847 provenance_probe: ExecutableIdentityProbe,
848 scheduled_respawn: Arc<Mutex<Option<PendingRespawn>>>,
850 deferred_reload_reply: Arc<Mutex<Option<ReloadReply>>>,
852 restart_policy: RestartPolicy,
853 register_timeout: Duration,
854 drain_timeout: Duration,
857 effective_drain_timeout: Arc<Mutex<Duration>>,
860 default_drain_timeout: Duration,
863 health: HealthConfig,
864 host_health: HostHealth,
865 connection_file_path: Option<PathBuf>,
866 capture_logs_dir: Option<PathBuf>,
867 forwarding: Option<Arc<ForwardingTable>>,
868 supervisor_handle: Option<SupervisorHandle>,
869 #[cfg(any(target_os = "linux", target_os = "macos"))]
870 replacement_ticket: Option<live_upgrade::ReplacementTicket>,
871 stderr_ring: Arc<Mutex<StderrRing>>,
878 terminal_ring: Arc<Mutex<TerminalRing>>,
879 spawn_events: SpawnEventFeed,
880 child_roster: ChildRoster,
881 #[cfg(target_os = "linux")]
882 cgroup_placement: Option<subc_cgroup::Placement>,
883 #[cfg(test)]
884 test_seed_stale_facts_before_enable_spawn: bool,
885 #[cfg(test)]
886 test_reload_exit_record_gate: Option<Arc<ReloadExitRecordGate>>,
887}
888
889impl SupervisorRuntimeConfig {
890 fn failure_context(&self, daemon_initiated: bool) -> FailureContext {
891 FailureContext {
892 daemon_initiated,
893 approval: None,
894 shutdown: self.child_roster.shutdown_flag(),
895 }
896 }
897}
898
899#[derive(Debug, Clone, PartialEq, Eq)]
900struct SupervisedConfiguration {
901 spec: ModuleSpec,
902 enabled: bool,
903 health: HealthConfig,
904 register_timeout: Duration,
905 restart_policy: RestartPolicy,
906}
907
908#[derive(Debug, Clone, Default)]
911pub struct SupervisorHandle {
912 pub(crate) pending_adoptions: resume_hello::PendingAdoptions,
913 upgrade_state: live_upgrade::UpgradeState,
914 #[cfg(test)]
915 resource_commit_pause: Arc<Mutex<Option<resource_launch::ResourceCommitPause>>>,
916 #[cfg(test)]
917 registration_test_channels: CapturedRegistrationChannels,
918 registration_service: Arc<Mutex<Option<registration::RegistrationService>>>,
919 registration_connections: Arc<Mutex<HashMap<ConnectionId, Arc<RegistrationSpawn>>>>,
920 registration_launches: Arc<Mutex<Vec<std::sync::Weak<RegistrationSpawn>>>>,
921 gate_runtime: Arc<Mutex<Option<std::sync::Weak<crate::config_gate::runtime::RuntimeOwner>>>>,
922 program_bindings: program_binding::ProgramBindings,
923 #[cfg(test)]
924 identity_sample_pause: Arc<Mutex<Option<IdentitySamplePause>>>,
925 #[cfg(all(test, unix))]
926 plain_identity_policy_pause: Arc<Mutex<Option<(String, IdentitySamplePause)>>>,
927 host_health: HostHealth,
928 restart_intent: Arc<Mutex<DaemonRestartIntent>>,
929 activity: Arc<Mutex<Option<crate::activity::ActivityLedger>>>,
930 activity_images: Arc<Mutex<HashMap<String, activity::ActivityImage>>>,
931 modules: Arc<Mutex<HashMap<String, SupervisedModule>>>,
932 configured_ids: Arc<Mutex<HashSet<String>>>,
944 spawn_events: SpawnEventFeed,
945 reserved_nonces: Arc<Mutex<HashMap<String, Option<String>>>>,
956 implicit_protocol_none: Arc<Mutex<HashSet<String>>>,
960 removal_tombstones: Arc<Mutex<HashMap<String, u64>>>,
966 spawn_nonces: Arc<Mutex<HashMap<String, String>>>,
970 nonce_launches: Arc<Mutex<NonceLaunches>>,
976 reserved_prefix_owners: Arc<Mutex<HashMap<String, String>>>,
984 swaps: Arc<Mutex<HashMap<String, OpenSwap>>>,
990 promotion_observer: PromotionObserverSlot,
992 operation_lock: Arc<AsyncMutex<()>>,
996}
997
998#[derive(Debug)]
999struct DaemonRestartIntent {
1000 expires: Option<Duration>,
1001 window: Duration,
1002}
1003
1004impl Default for DaemonRestartIntent {
1005 fn default() -> Self {
1006 Self {
1007 expires: None,
1008 window: Duration::from_secs(120),
1009 }
1010 }
1011}
1012
1013impl SupervisorHandle {
1014 pub(crate) fn module_is_gated(&self, module: &str) -> bool {
1015 let runtime = {
1016 let Ok(runtime) = self.gate_runtime.lock() else {
1017 return true;
1018 };
1019 runtime.clone()
1020 };
1021 runtime.is_some_and(|runtime| {
1022 runtime
1023 .upgrade()
1024 .is_none_or(|owner| owner.module_is_gated(module))
1025 })
1026 }
1027 pub(crate) fn announce_daemon_restart(&self) -> u64 {
1028 let mut intent = self
1029 .restart_intent
1030 .lock()
1031 .unwrap_or_else(|p| p.into_inner());
1032 intent.expires = Some(subc_uptime::suspend_inclusive_now() + intent.window);
1033 unix_ms_now().saturating_add(intent.window.as_millis() as u64)
1034 }
1035
1036 #[cfg(feature = "test-support")]
1037 pub(crate) fn set_shutdown_intent_window(&self, window: Duration) {
1038 self.restart_intent
1039 .lock()
1040 .unwrap_or_else(|p| p.into_inner())
1041 .window = window;
1042 }
1043
1044 #[cfg(unix)]
1045 fn take_daemon_shutdown_reason(&self) -> RouteCloseReason {
1046 let expiry = self
1047 .restart_intent
1048 .lock()
1049 .unwrap_or_else(|p| p.into_inner())
1050 .expires
1051 .take();
1052 if expiry.is_some_and(|expiry| subc_uptime::suspend_inclusive_now() < expiry) {
1053 RouteCloseReason::Restart
1054 } else {
1055 RouteCloseReason::Disable
1056 }
1057 }
1058
1059 pub fn new() -> Self {
1060 Self::default()
1061 }
1062
1063 pub(crate) fn operation_lock(&self) -> Arc<AsyncMutex<()>> {
1064 Arc::clone(&self.operation_lock)
1065 }
1066}
1067
1068#[derive(Debug, Clone)]
1070pub struct Supervisor {
1071 registry: Arc<Registry>,
1072 config_delivery: Option<config_delivery::ConfigDelivery>,
1073 restart_policy: RestartPolicy,
1074 drain_timeout: Duration,
1075 connection_file_path: Option<PathBuf>,
1076 capture_logs_dir: Option<PathBuf>,
1077 forwarding: Option<Arc<ForwardingTable>>,
1078 process_liveness: Arc<SupervisorProcessLiveness>,
1079 supervisor_handle: Option<SupervisorHandle>,
1080 health: HealthConfig,
1081 host_health: HostHealth,
1082 daemon_start_clock: crate::clock::StartClock,
1083 terminal_journal: Option<Arc<crate::terminal_journal::TerminalJournal>>,
1084 spawn_events: SpawnEventFeed,
1085 provenance_probe: ExecutableIdentityProbe,
1086 child_roster: ChildRoster,
1089 #[cfg(target_os = "linux")]
1090 cgroup_placement: Option<subc_cgroup::Placement>,
1091 #[cfg(test)]
1092 test_after_first_spawn: AfterFirstSpawnHook,
1093}
1094
1095impl Supervisor {
1096 pub fn new(registry: Arc<Registry>, restart_policy: RestartPolicy) -> Self {
1097 Self {
1098 registry,
1099 config_delivery: None,
1100 restart_policy,
1101 drain_timeout: DEFAULT_DRAIN_TIMEOUT,
1102 connection_file_path: None,
1103 capture_logs_dir: None,
1104 forwarding: None,
1105 process_liveness: Arc::new(SupervisorProcessLiveness::default()),
1106 supervisor_handle: None,
1107 health: HealthConfig::default(),
1108 host_health: HostHealth::default(),
1109 daemon_start_clock: crate::clock::StartClock::capture(),
1110 terminal_journal: None,
1111 spawn_events: SpawnEventFeed::default(),
1112 provenance_probe: ExecutableIdentityProbe::default(),
1113 child_roster: ChildRoster::default(),
1114 #[cfg(target_os = "linux")]
1115 cgroup_placement: None,
1116 #[cfg(test)]
1117 test_after_first_spawn: AfterFirstSpawnHook::default(),
1118 }
1119 }
1120
1121 pub fn with_drain_timeout(mut self, drain_timeout: Duration) -> Self {
1122 self.drain_timeout = drain_timeout;
1123 self
1124 }
1125
1126 pub(crate) fn default_drain_timeout(&self) -> Duration {
1128 self.drain_timeout
1129 }
1130
1131 pub fn with_process_liveness(
1132 mut self,
1133 process_liveness: Arc<SupervisorProcessLiveness>,
1134 ) -> Self {
1135 self.process_liveness = process_liveness;
1136 self
1137 }
1138
1139 pub fn with_config_runtime(
1141 mut self,
1142 owner: Arc<crate::config_gate::runtime::RuntimeOwner>,
1143 ) -> Self {
1144 if let Some(handle) = &self.supervisor_handle {
1145 handle.install_binding_retirement(&owner);
1146 }
1147 self.config_delivery = Some(config_delivery::ConfigDelivery(owner));
1148 self
1149 }
1150
1151 pub fn with_connection_file_path(mut self, connection_file_path: impl Into<PathBuf>) -> Self {
1152 self.connection_file_path = Some(connection_file_path.into());
1153 self
1154 }
1155
1156 pub fn with_capture_logs_dir(mut self, logs_dir: impl Into<PathBuf>) -> Self {
1158 self.capture_logs_dir = Some(logs_dir.into());
1159 self
1160 }
1161
1162 pub fn with_daemon_incarnation(self, daemon_incarnation: String) -> Self {
1165 self.spawn_events.configure_incarnation(daemon_incarnation);
1169 self
1170 }
1171
1172 pub fn with_terminal_journal(self, path: PathBuf, daemon_incarnation: String) -> Self {
1175 let mut this = self.with_daemon_incarnation(daemon_incarnation.clone());
1176 this.terminal_journal = Some(Arc::new(crate::terminal_journal::TerminalJournal::open(
1177 path,
1178 daemon_incarnation,
1179 )));
1180 this
1181 }
1182
1183 pub fn with_forwarding(mut self, forwarding: Arc<ForwardingTable>) -> Self {
1184 self.child_roster.counters = forwarding.counters();
1185 self.forwarding = Some(forwarding);
1186 self
1187 }
1188
1189 pub fn with_handle(mut self, supervisor_handle: SupervisorHandle) -> Self {
1190 if let Some(delivery) = &self.config_delivery {
1191 supervisor_handle.install_binding_retirement(&delivery.0);
1192 }
1193 self.host_health = supervisor_handle.host_health.clone();
1194 self.spawn_events = supervisor_handle.spawn_events.clone();
1195 self.supervisor_handle = Some(supervisor_handle);
1196 self
1197 }
1198
1199 pub fn with_health_config(mut self, health: HealthConfig) -> Self {
1200 self.health = health;
1201 self
1202 }
1203
1204 pub fn with_live_children_record(self, path: impl Into<PathBuf>) -> Self {
1208 self.child_roster.record_to(path.into());
1209 self
1210 }
1211
1212 pub(crate) fn with_owned_live_children_record(
1213 self,
1214 owner: &crate::run_dir_lock::RunDirLock,
1215 protected: &crate::live_children::AdoptedPids,
1216 ) -> Self {
1217 self.child_roster.record_to_owned(owner, protected);
1218 self
1219 }
1220
1221 #[cfg(target_os = "linux")]
1222 pub fn with_cgroup_placement(
1223 mut self,
1224 cgroup_placement: Option<subc_cgroup::Placement>,
1225 ) -> Self {
1226 self.child_roster
1227 .set_cgroup_placement(cgroup_placement.clone());
1228 self.cgroup_placement = cgroup_placement;
1229 self
1230 }
1231}
1232
1233impl Default for Supervisor {
1234 fn default() -> Self {
1235 Self::new(Arc::new(Registry::default()), RestartPolicy::default())
1236 }
1237}
1238
1239#[derive(Clone)]
1241pub struct SupervisedModule {
1242 inner: Arc<SupervisedModuleInner>,
1243}
1244
1245struct SupervisedModuleInner {
1246 retained: crate::child_roster::RetainedView,
1247 module_id: String,
1248 registry: Arc<Registry>,
1249 snapshot: SharedSnapshot,
1250 configuration: Arc<Mutex<SupervisedConfiguration>>,
1251 stderr_ring: Arc<Mutex<StderrRing>>,
1252 terminal_ring: Arc<Mutex<TerminalRing>>,
1253 commands: mpsc::Sender<SupervisorCommand>,
1254 monitor: Mutex<Option<JoinHandle<()>>>,
1255 effective_drain_timeout: Arc<Mutex<Duration>>,
1256 provenance_probe: ExecutableIdentityProbe,
1257}
1258
1259impl fmt::Debug for SupervisedModule {
1260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261 f.debug_struct("SupervisedModule")
1262 .field("module_id", &self.inner.module_id)
1263 .field("status", &self.status())
1264 .finish_non_exhaustive()
1265 }
1266}
1267
1268impl SupervisedModule {
1269 pub fn module_id(&self) -> &str {
1270 &self.inner.module_id
1271 }
1272
1273 pub fn state(&self) -> Result<ModuleState, SuperviseError> {
1274 Ok(lock_snapshot(&self.inner.snapshot)?.state)
1275 }
1276
1277 pub(crate) fn registration_end_reason(
1278 &self,
1279 ) -> Result<Option<RegistrationEndReason>, SuperviseError> {
1280 let snapshot = lock_snapshot(&self.inner.snapshot)?;
1281 Ok(match snapshot.state {
1282 ModuleState::Draining if snapshot.draining_to_replace => {
1283 Some(RegistrationEndReason::SupervisorRestart)
1284 }
1285 ModuleState::Draining => Some(RegistrationEndReason::SupervisorStop),
1286 ModuleState::Restarting if snapshot.draining_to_replace => {
1287 Some(RegistrationEndReason::SupervisorRestart)
1288 }
1289 _ => None,
1290 })
1291 }
1292
1293 pub fn stderr_tail(
1300 &self,
1301 max_lines: Option<usize>,
1302 max_bytes: Option<usize>,
1303 ) -> StderrTailSnapshot {
1304 self.inner
1305 .stderr_ring
1306 .lock()
1307 .unwrap_or_else(|poisoned| poisoned.into_inner())
1308 .snapshot(max_lines, max_bytes)
1309 }
1310
1311 pub fn terminal_history(&self) -> TerminalHistorySnapshot {
1316 self.inner
1317 .terminal_ring
1318 .lock()
1319 .unwrap_or_else(|poisoned| poisoned.into_inner())
1320 .snapshot()
1321 }
1322
1323 pub fn durable_terminal_history(&self) -> subc_control::TerminalHistory {
1328 durable_terminal_history_of(&self.inner.terminal_ring, &self.inner.module_id)
1329 }
1330
1331 pub(crate) async fn read_durable_terminal_history(
1336 &self,
1337 ) -> Result<subc_control::TerminalHistory, tokio::task::JoinError> {
1338 let terminal_ring = Arc::clone(&self.inner.terminal_ring);
1339 let module_id = self.inner.module_id.clone();
1340 tokio::task::spawn_blocking(move || durable_terminal_history_of(&terminal_ring, &module_id))
1341 .await
1342 }
1343
1344 pub fn status(&self) -> Result<ModuleStatus, SuperviseError> {
1345 self.status_with_snapshot_lock(&self.inner.snapshot, None)
1346 .map(|(status, _)| status)
1347 }
1348
1349 pub(crate) fn next_retry_at_ms(&self) -> Result<Option<u64>, SuperviseError> {
1350 let state = lock_snapshot(&self.inner.snapshot)?;
1351 Ok(state
1352 .failed_retry
1353 .pending
1354 .filter(|_| state.state == ModuleState::Failed && state.enabled)
1355 .map(|retry| {
1356 unix_ms_now().saturating_add(
1357 u64::try_from(
1358 retry
1359 .deadline
1360 .saturating_duration_since(Instant::now())
1361 .as_millis(),
1362 )
1363 .unwrap_or(u64::MAX),
1364 )
1365 }))
1366 }
1367
1368 #[cfg(all(test, unix))]
1369 pub(crate) fn retry_deadline_for_test(&self) -> Option<Instant> {
1370 lock_snapshot(&self.inner.snapshot)
1371 .unwrap()
1372 .failed_retry
1373 .pending
1374 .map(|retry| retry.deadline)
1375 }
1376
1377 pub(crate) fn status_for_control(
1382 &self,
1383 caller: &'static str,
1384 ) -> Result<ModuleStatus, SuperviseError> {
1385 self.status_with_snapshot_lock(&self.inner.snapshot, Some(caller))
1386 .map(|(status, _)| status)
1387 }
1388
1389 fn status_with_snapshot_lock(
1390 &self,
1391 snapshot: &SharedSnapshot,
1392 caller: Option<&'static str>,
1393 ) -> Result<(ModuleStatus, Option<SpawnedFileIdentity>), SuperviseError> {
1394 let restart_policy = self
1395 .inner
1396 .configuration
1397 .lock()
1398 .map_err(|_| SuperviseError::StatePoisoned {
1399 module_id: Some(self.inner.module_id.clone()),
1400 })?
1401 .restart_policy;
1402 let mut guard = match caller {
1403 Some(caller) => lock_snapshot_for_control(snapshot, &self.inner.module_id, caller)?,
1404 None => lock_snapshot(snapshot)?,
1405 };
1406 let restart_count = guard.crash_restarts_in_window(restart_policy.window, Instant::now());
1409 let snapshot = guard.clone();
1410 drop(guard);
1411 let drain_timeout = *self.inner.effective_drain_timeout.lock().map_err(|_| {
1412 SuperviseError::StatePoisoned {
1413 module_id: Some(self.inner.module_id.clone()),
1414 }
1415 })?;
1416 let registration_active = self
1417 .inner
1418 .registry
1419 .get_module(&self.inner.module_id)
1420 .map_err(SuperviseError::Registry)?
1421 .is_some();
1422 let protocol = snapshot
1423 .spawned_protocol
1424 .unwrap_or(self.declared_protocol()?);
1425 let running_process =
1426 snapshot.enabled && snapshot.state == ModuleState::Running && snapshot.process_alive;
1427 let live = match protocol {
1433 ModuleProtocol::Subc => running_process && registration_active,
1434 ModuleProtocol::None => running_process,
1435 };
1436 let retained = self.inner.retained.waiting_detail(&self.inner.module_id);
1439 let carry_configured = self
1440 .inner
1441 .configuration
1442 .lock()
1443 .map_err(|_| SuperviseError::StatePoisoned {
1444 module_id: Some(self.inner.module_id.clone()),
1445 })?
1446 .spec
1447 .carry_containment;
1448 let recovery_block = carries_containment(
1449 carry_configured,
1450 self.inner
1451 .retained
1452 .has_carried_container(&self.inner.module_id),
1453 )
1454 .then(|| self.inner.retained.recovery_block())
1455 .flatten();
1456 let launch_nonce_source = observed_launch_nonce_source(&snapshot);
1457 let pid = snapshot.reported_pid();
1458 let mut health = snapshot.health;
1459 if let Some(detail) = recovery_block
1460 .as_ref()
1461 .or_else(|| retained.as_ref().map(|(_, detail)| detail))
1462 {
1463 health.detail = Some(match health.detail {
1464 Some(previous) => format!("{previous}; {detail}"),
1465 None => detail.clone(),
1466 });
1467 }
1468
1469 Ok((
1470 ModuleStatus {
1471 admission_refused: snapshot.admission_refused,
1472 #[cfg(windows)]
1473 nonce_pipe_refusal: snapshot.nonce_pipe_refusal,
1474 legacy_registration_spawn: snapshot.legacy_registration_spawn,
1475 registration_declaration: snapshot.registration_declaration.clone(),
1476 stop_reason: snapshot.stop_reason,
1477 waiting_for_previous_pid: retained
1478 .as_ref()
1479 .map(|(pid, _)| *pid)
1480 .filter(|pid| *pid > 0)
1481 .or(snapshot.waiting_for_previous_pid),
1482 waiting_for_previous_detail: recovery_block
1483 .or_else(|| retained.map(|(_, detail)| detail))
1484 .or(snapshot.waiting_for_previous_detail),
1485 module_id: self.inner.module_id.clone(),
1486 launch_nonce_source,
1487 state: snapshot.state,
1488 enabled: snapshot.enabled,
1489 process_alive: snapshot.process_alive,
1490 registration_active,
1491 protocol,
1492 live,
1493 restart_count,
1494 lifetime_restarts: snapshot.lifetime_restarts,
1495 spawn_generation: snapshot.spawn_generation,
1496 swap_outcome: snapshot.swap_outcome,
1497 max_restarts: restart_policy.max_restarts,
1498 restart_window: restart_policy.window,
1499 drain_timeout,
1500 restart_backoff: restart_policy.backoff,
1501 restart_max_backoff: restart_policy.max_backoff,
1502 pid,
1503 spawned_at_ms: snapshot.spawned_at_ms,
1504 spawned_from: snapshot.spawned_from,
1505 launch_spec_digest: snapshot.launch_spec_digest,
1506 process_start_time: snapshot.process_start_time,
1507 last_exit: snapshot.last_exit,
1508 health,
1509 },
1510 snapshot.spawned_file_identity.clone(),
1511 ))
1512 }
1513
1514 #[cfg(test)]
1515 pub(crate) fn hold_snapshot_for_test(
1516 &self,
1517 acquired: std::sync::mpsc::Sender<()>,
1518 hold: Duration,
1519 ) -> std::thread::JoinHandle<()> {
1520 let snapshot = Arc::clone(&self.inner.snapshot);
1521 std::thread::spawn(move || {
1522 let _guard = snapshot.lock().expect("test snapshot lock is not poisoned");
1523 acquired
1524 .send(())
1525 .expect("test receiver waits for snapshot lock");
1526 std::thread::sleep(hold);
1527 })
1528 }
1529
1530 pub(crate) async fn status_and_running_image_agreement(
1536 &self,
1537 ) -> Result<(ModuleStatus, subc_control::RunningImageAgreement), SuperviseError> {
1538 let (status, identity) = self.status_with_snapshot_lock(&self.inner.snapshot, None)?;
1539 let image = self
1540 .inner
1541 .provenance_probe
1542 .observe(
1543 status.pid,
1544 status.spawned_from.as_deref(),
1545 identity,
1546 status.process_start_time,
1547 )
1548 .await;
1549 Ok((status, image))
1550 }
1551
1552 pub(crate) async fn running_image_agreement(&self) -> subc_control::RunningImageAgreement {
1553 let snapshot = match lock_snapshot(&self.inner.snapshot) {
1554 Ok(snapshot) => snapshot.clone(),
1555 Err(_) => {
1556 return subc_control::RunningImageAgreement::Unavailable {
1557 reason: subc_control::RunningImageUnavailableReason::NotRunning,
1558 };
1559 }
1560 };
1561 self.inner
1562 .provenance_probe
1563 .observe(
1564 snapshot.reported_pid(),
1565 snapshot.spawned_from.as_deref(),
1566 snapshot.spawned_file_identity.clone(),
1567 snapshot.process_start_time,
1568 )
1569 .await
1570 }
1571
1572 pub(crate) fn child_resource_usage(&self) -> subc_control::ChildResourceUsage {
1575 #[cfg(windows)]
1576 {
1577 let image = lock_snapshot(&self.inner.snapshot)
1578 .ok()
1579 .and_then(|snapshot| {
1580 snapshot
1581 .spawned_file_identity
1582 .as_ref()
1583 .and_then(|identity| identity.windows_image.clone())
1584 });
1585 match image {
1586 Some(image) => {
1587 crate::child_resources::read_windows_handle(image.process(), image.start_time())
1588 }
1589 None => subc_control::ChildResourceUsage::Unavailable {
1590 reason: subc_control::ChildResourceUnavailableReason::NotRunning,
1591 },
1592 }
1593 }
1594 #[cfg(not(windows))]
1595 {
1596 let (pid, start_time) = match lock_snapshot(&self.inner.snapshot) {
1597 Ok(snapshot) => (snapshot.reported_pid(), snapshot.process_start_time),
1598 Err(_) => {
1599 return subc_control::ChildResourceUsage::Unavailable {
1600 reason: subc_control::ChildResourceUnavailableReason::Unreadable,
1601 }
1602 }
1603 };
1604 crate::child_resources::read(pid, start_time)
1605 }
1606 }
1607
1608 #[cfg(all(test, any(target_os = "linux", windows)))]
1609 pub(crate) fn subtree_target(&self) -> crate::subtree_resources::Target {
1610 self.inner
1611 .snapshot
1612 .try_lock()
1613 .map(|snapshot| snapshot.subtree_target.clone())
1614 .unwrap_or(crate::subtree_resources::Target::Unavailable("read_failed"))
1615 }
1616
1617 #[cfg(test)]
1618 pub(crate) fn set_subtree_target_for_test(&self, target: crate::subtree_resources::Target) {
1619 self.inner.snapshot.lock().unwrap().subtree_target = target;
1620 }
1621
1622 pub(crate) fn will_recover_after_connection_loss(&self) -> Result<bool, SuperviseError> {
1623 let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
1624 Ok(match snapshot.state {
1625 ModuleState::Restarting => true,
1626 ModuleState::Failed | ModuleState::Disabled => false,
1627 _ if snapshot.enabled && snapshot.respawn_pending => true,
1628 _ => daemon_will_restart(
1629 &mut snapshot,
1630 &self
1631 .inner
1632 .configuration
1633 .lock()
1634 .map_err(|_| SuperviseError::StatePoisoned {
1635 module_id: Some(self.inner.module_id.clone()),
1636 })?
1637 .restart_policy,
1638 Instant::now(),
1639 ),
1640 })
1641 }
1642
1643 #[cfg(test)]
1644 pub(crate) fn is_warming(&self) -> Result<bool, SuperviseError> {
1645 self.is_warming_with_snapshot_lock(None)
1646 }
1647
1648 pub(crate) fn is_warming_for_control(
1649 &self,
1650 caller: &'static str,
1651 ) -> Result<bool, SuperviseError> {
1652 self.is_warming_with_snapshot_lock(Some(caller))
1653 }
1654
1655 fn is_warming_with_snapshot_lock(
1656 &self,
1657 caller: Option<&'static str>,
1658 ) -> Result<bool, SuperviseError> {
1659 let snapshot = match caller {
1660 Some(caller) => {
1661 lock_snapshot_for_control(&self.inner.snapshot, &self.inner.module_id, caller)?
1662 }
1663 None => lock_snapshot(&self.inner.snapshot)?,
1664 }
1665 .clone();
1666 Ok(matches!(
1667 snapshot.state,
1668 ModuleState::Starting | ModuleState::Running | ModuleState::Restarting
1669 ))
1670 }
1671
1672 pub(crate) fn declared_protocol(&self) -> Result<ModuleProtocol, SuperviseError> {
1676 let configured = self
1677 .inner
1678 .configuration
1679 .lock()
1680 .map_err(|_| SuperviseError::StatePoisoned {
1681 module_id: Some(self.inner.module_id.clone()),
1682 })?
1683 .spec
1684 .protocol;
1685 let state = lock_snapshot(&self.inner.snapshot)?;
1686 Ok(state.spawned_protocol.unwrap_or(configured))
1687 }
1688
1689 pub(crate) fn configuration(&self) -> Result<(ModuleSpec, HealthConfig), SuperviseError> {
1690 let configuration =
1691 self.inner
1692 .configuration
1693 .lock()
1694 .map_err(|_| SuperviseError::StatePoisoned {
1695 module_id: Some(self.inner.module_id.clone()),
1696 })?;
1697 Ok((configuration.spec.clone(), configuration.health.clone()))
1698 }
1699
1700 pub(crate) fn configured_register_timeout(&self) -> Result<Duration, SuperviseError> {
1701 self.inner
1702 .configuration
1703 .lock()
1704 .map(|configuration| configuration.register_timeout)
1705 .map_err(|_| SuperviseError::StatePoisoned {
1706 module_id: Some(self.inner.module_id.clone()),
1707 })
1708 }
1709
1710 pub(crate) fn configured_enabled(&self) -> Result<bool, SuperviseError> {
1711 self.inner
1712 .configuration
1713 .lock()
1714 .map(|configuration| configuration.enabled)
1715 .map_err(|_| SuperviseError::StatePoisoned {
1716 module_id: Some(self.inner.module_id.clone()),
1717 })
1718 }
1719
1720 #[cfg(any(test, feature = "test-support"))]
1724 pub async fn update_spec_for_test(&self, spec: ModuleSpec) -> Result<(), SuperviseError> {
1725 let (_, health) = self.configuration()?;
1726 let drain_timeout_ms = u64::try_from(
1727 self.inner
1728 .effective_drain_timeout
1729 .lock()
1730 .unwrap_or_else(|poisoned| poisoned.into_inner())
1731 .as_millis(),
1732 )
1733 .ok();
1734 self.update_configuration(spec, health, drain_timeout_ms)
1735 .await
1736 }
1737
1738 pub(crate) async fn update_configuration(
1739 &self,
1740 spec: ModuleSpec,
1741 health: HealthConfig,
1742 drain_timeout_ms: Option<u64>,
1743 ) -> Result<(), SuperviseError> {
1744 if spec.module_id != self.inner.module_id {
1745 return Err(SuperviseError::InvalidSpec {
1746 reason: "a supervised module's module_id cannot be changed".to_string(),
1747 });
1748 }
1749 validate_spec(&spec)?;
1750 let (reply_tx, reply_rx) = oneshot::channel();
1751 self.inner
1752 .commands
1753 .send(SupervisorCommand::UpdateConfiguration {
1754 spec: spec.clone(),
1755 health: health.clone(),
1756 drain_timeout_ms,
1757 reply: reply_tx,
1758 })
1759 .await
1760 .map_err(|_| SuperviseError::CommandClosed {
1761 module_id: self.inner.module_id.clone(),
1762 })?;
1763 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
1764 module_id: self.inner.module_id.clone(),
1765 })??;
1766 let mut configuration =
1767 self.inner
1768 .configuration
1769 .lock()
1770 .map_err(|_| SuperviseError::StatePoisoned {
1771 module_id: Some(self.inner.module_id.clone()),
1772 })?;
1773 configuration.spec = spec;
1774 configuration.health = health;
1775 Ok(())
1776 }
1777}
1778
1779impl Drop for SupervisedModuleInner {
1780 fn drop(&mut self) {
1781 let Ok(mut monitor) = self.monitor.lock() else {
1782 return;
1783 };
1784 if let Some(monitor) = monitor.as_ref().filter(|monitor| !monitor.is_finished()) {
1785 let _ = update_snapshot(&self.snapshot, Some(&self.module_id), |state| {
1786 state.state = ModuleState::Stopped;
1787 clear_current_process_facts(state);
1788 });
1789 monitor.abort();
1790 }
1791 let _ = monitor.take();
1792 }
1793}
1794
1795#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1799pub enum SwapOutcome {
1800 Cutover,
1801 SupersededByConfigRestart,
1802}
1803
1804impl SwapOutcome {
1805 pub fn as_str(self) -> &'static str {
1806 match self {
1807 Self::Cutover => "cutover",
1808 Self::SupersededByConfigRestart => "superseded_by_config_restart",
1809 }
1810 }
1811}
1812
1813#[derive(Debug)]
1814pub enum SuperviseError {
1815 UpgradeInProgress,
1816 ConfigHeld {
1817 module_id: String,
1818 code: String,
1819 detail: String,
1820 },
1821 ConfigDeliveryDeferred {
1822 module_id: String,
1823 },
1824 InvalidSpec {
1825 reason: String,
1826 },
1827 Spawn {
1828 program: PathBuf,
1829 source: io::Error,
1830 cgroup_path: Option<PathBuf>,
1831 },
1832 Cgroup {
1833 module_id: String,
1834 source: io::Error,
1835 },
1836 LaunchNonce {
1840 reason: String,
1841 },
1842 Wait {
1843 module_id: String,
1844 source: io::Error,
1845 },
1846 Kill {
1847 module_id: String,
1848 source: io::Error,
1849 },
1850 Forwarding(ForwardingError),
1851 Registry(RegistryError),
1852 ReloadUnavailable {
1853 module_id: String,
1854 reason: String,
1855 },
1856 Disabled {
1861 module_id: String,
1862 },
1863 ReloadFailed {
1864 module_id: String,
1865 reason: String,
1866 },
1867 RegistrationStillActive {
1868 module_id: String,
1869 waited: Duration,
1870 },
1871 StatePoisoned {
1872 module_id: Option<String>,
1873 },
1874 CommandClosed {
1875 module_id: String,
1876 },
1877 SwapInProgress {
1881 module_id: String,
1882 },
1883 SwapRefused {
1885 module_id: String,
1886 reason: SwapRefusal,
1887 },
1888 SwapFailed {
1892 module_id: String,
1893 arm: SwapFailureArm,
1894 detail: String,
1895 candidate_exit: Option<ExitReport>,
1898 },
1899}
1900
1901#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1903pub enum SwapRefusal {
1904 OverlapExclusive,
1906 NotRegistered,
1909 ProtocolNone,
1912 NotConfigured,
1915 AlreadySwapping,
1917}
1918
1919impl SwapRefusal {
1920 pub fn as_str(self) -> &'static str {
1921 match self {
1922 Self::OverlapExclusive => "overlap_exclusive",
1923 Self::NotRegistered => "not_registered",
1924 Self::ProtocolNone => "protocol_none",
1925 Self::NotConfigured => "not_configured",
1926 Self::AlreadySwapping => "already_swapping",
1927 }
1928 }
1929}
1930
1931#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1934pub enum SwapFailureArm {
1935 SpawnFailed,
1937 NeverRegistered,
1939 NeverReady,
1941 CandidateExited,
1943 CandidateUnhealthy,
1945 Interrupted,
1949 CutoverLost,
1954}
1955
1956impl SwapFailureArm {
1957 pub fn as_str(self) -> &'static str {
1958 match self {
1959 Self::SpawnFailed => "spawn_failed",
1960 Self::NeverRegistered => "never_registered",
1961 Self::NeverReady => "never_ready",
1962 Self::CandidateExited => "candidate_exited",
1963 Self::CandidateUnhealthy => "candidate_unhealthy",
1964 Self::Interrupted => "interrupted",
1965 Self::CutoverLost => "cutover_lost",
1966 }
1967 }
1968}
1969
1970impl SuperviseError {
1971 pub(crate) fn is_config_gate_error(&self) -> bool {
1972 match self {
1973 Self::ConfigHeld { .. } => true,
1974 Self::Spawn { source, .. } => source
1975 .get_ref()
1976 .is_some_and(|cause| cause.is::<crate::config_gate::GateError>()),
1977 _ => false,
1978 }
1979 }
1980}
1981
1982impl fmt::Display for SuperviseError {
1983 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1984 match self {
1985 Self::ConfigHeld { module_id, code, detail } => write!(f, "{code}: module '{module_id}' held: {detail}"),
1986 Self::ConfigDeliveryDeferred { module_id } => write!(f, "config_gated: module '{module_id}' is waiting for its exited delivery target's failure record"),
1987 Self::InvalidSpec { reason } => write!(f, "invalid module spec: {reason}"),
1988 Self::Spawn {
1989 program,
1990 source,
1991 cgroup_path: Some(cgroup_path),
1992 } => write!(
1993 f,
1994 "failed to place module in cgroup '{}' while spawning '{}': {source}",
1995 cgroup_path.display(),
1996 program.display()
1997 ),
1998 Self::Spawn {
1999 program,
2000 source,
2001 cgroup_path: None,
2002 } => write!(
2003 f,
2004 "failed to spawn module '{}': {source}",
2005 program.display()
2006 ),
2007 Self::Cgroup { module_id, source } => {
2008 write!(
2009 f,
2010 "failed to prepare cgroup for module '{module_id}': {source}"
2011 )
2012 }
2013 Self::LaunchNonce { reason } => {
2014 write!(
2015 f,
2016 "failed to generate reserved-module launch nonce: {reason}"
2017 )
2018 }
2019 Self::Wait { module_id, source } => {
2020 write!(f, "failed to wait for module '{module_id}': {source}")
2021 }
2022 Self::Kill { module_id, source } => {
2023 write!(f, "failed to kill module '{module_id}': {source}")
2024 }
2025 Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
2026 Self::Registry(err) => write!(f, "registry error: {err}"),
2027 Self::ReloadUnavailable { module_id, reason } => {
2028 write!(f, "reload unavailable for module '{module_id}': {reason}")
2029 }
2030 Self::Disabled { module_id } => {
2031 write!(
2032 f,
2033 "module '{module_id}' is disabled; enable it before restart or reload"
2034 )
2035 }
2036 Self::ReloadFailed { module_id, reason } => {
2037 write!(f, "reload failed for module '{module_id}': {reason}")
2038 }
2039 Self::RegistrationStillActive { module_id, waited } => write!(
2040 f,
2041 "module '{module_id}' registration remained active after waiting {waited:?}"
2042 ),
2043 Self::StatePoisoned { module_id } => match module_id {
2044 Some(module_id) => {
2045 write!(f, "supervisor state for module '{module_id}' was poisoned")
2046 }
2047 None => write!(f, "supervisor state was poisoned"),
2048 },
2049 Self::CommandClosed { module_id } => {
2050 write!(
2051 f,
2052 "supervisor command channel for module '{module_id}' is closed"
2053 )
2054 }
2055 Self::UpgradeInProgress => f.write_str("daemon upgrade is in progress"),
2056 Self::SwapInProgress { module_id } => write!(
2057 f,
2058 "module '{module_id}' is being swapped; retry once the swap has cut over or failed, or stop the module to abort the swap"
2059 ),
2060 Self::SwapRefused { module_id, reason } => match reason {
2061 SwapRefusal::OverlapExclusive => write!(
2062 f,
2063 "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"
2064 ),
2065 SwapRefusal::NotRegistered => write!(
2066 f,
2067 "module '{module_id}' is not registered, so there is no serving process to keep while a replacement warms; use a plain restart"
2068 ),
2069 SwapRefusal::ProtocolNone => write!(
2070 f,
2071 "module '{module_id}' is protocol: \"none\" and never registers, so a swap could never see its replacement become ready; use a plain restart"
2072 ),
2073 SwapRefusal::NotConfigured => write!(
2074 f,
2075 "module '{module_id}' cannot be swapped: the supervisor was built without the forwarding table or shared handle a swap needs"
2076 ),
2077 SwapRefusal::AlreadySwapping => {
2078 write!(f, "module '{module_id}' is already being swapped")
2079 }
2080 },
2081 Self::SwapFailed {
2082 module_id,
2083 arm,
2084 detail,
2085 ..
2086 } => write!(
2087 f,
2088 "swap of module '{module_id}' failed ({}): {detail}; the running process was left serving",
2089 arm.as_str()
2090 ),
2091 }
2092 }
2093}
2094
2095impl Error for SuperviseError {
2096 fn source(&self) -> Option<&(dyn Error + 'static)> {
2097 match self {
2098 Self::Spawn { source, .. }
2099 | Self::Cgroup { source, .. }
2100 | Self::Wait { source, .. }
2101 | Self::Kill { source, .. } => Some(source),
2102 Self::Forwarding(err) => Some(err),
2103 Self::Registry(err) => Some(err),
2104 Self::LaunchNonce { .. }
2105 | Self::ConfigDeliveryDeferred { .. }
2106 | Self::ConfigHeld { .. }
2107 | Self::InvalidSpec { .. }
2108 | Self::ReloadUnavailable { .. }
2109 | Self::Disabled { .. }
2110 | Self::ReloadFailed { .. }
2111 | Self::RegistrationStillActive { .. }
2112 | Self::StatePoisoned { .. }
2113 | Self::CommandClosed { .. }
2114 | Self::SwapInProgress { .. }
2115 | Self::UpgradeInProgress
2116 | Self::SwapRefused { .. }
2117 | Self::SwapFailed { .. } => None,
2118 }
2119 }
2120}
2121
2122fn unix_ms_now() -> u64 {
2123 SystemTime::now()
2124 .duration_since(UNIX_EPOCH)
2125 .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
2126 .unwrap_or(0)
2127}
2128
2129fn update_snapshot(
2130 snapshot: &SharedSnapshot,
2131 module_id: Option<&str>,
2132 update: impl FnOnce(&mut SupervisorSnapshot),
2133) -> Result<(), SuperviseError> {
2134 let mut state = lock_snapshot(snapshot).map_err(|_| SuperviseError::StatePoisoned {
2135 module_id: module_id.map(ToOwned::to_owned),
2136 })?;
2137 update(&mut state);
2138 Ok(())
2139}
2140
2141const SLOW_SNAPSHOT_LOCK_THRESHOLD: Duration = Duration::from_millis(250);
2142
2143fn lock_snapshot_for_control<'a>(
2144 snapshot: &'a SharedSnapshot,
2145 module_id: &str,
2146 caller: &'static str,
2147) -> Result<std::sync::MutexGuard<'a, SupervisorSnapshot>, SuperviseError> {
2148 let started_at = Instant::now();
2149 let guard = lock_snapshot(snapshot)?;
2150 let waited = started_at.elapsed();
2151 if waited >= SLOW_SNAPSHOT_LOCK_THRESHOLD {
2152 warn!(
2153 module_id = %module_id,
2154 waited_ms = waited.as_millis() as u64,
2155 caller = %caller,
2156 "slow snapshot lock"
2157 );
2158 }
2159 Ok(guard)
2160}
2161
2162fn lock_snapshot(
2163 snapshot: &SharedSnapshot,
2164) -> Result<std::sync::MutexGuard<'_, SupervisorSnapshot>, SuperviseError> {
2165 let guard = match snapshot.try_lock() {
2166 Ok(guard) => return Ok(guard),
2167 Err(TryLockError::Poisoned(guard)) => Err(guard),
2168 Err(TryLockError::WouldBlock) => {
2169 if tokio::runtime::Handle::try_current().is_ok_and(|handle| {
2172 handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread
2173 }) {
2174 tokio::task::block_in_place(|| snapshot.lock())
2175 } else {
2176 snapshot.lock()
2177 }
2178 }
2179 };
2180 guard.map_err(|_| SuperviseError::StatePoisoned { module_id: None })
2181}
2182
2183#[cfg(all(test, unix))]
2184mod restart_ordering_tests;
2185
2186#[cfg(all(test, target_os = "macos"))]
2187#[path = "supervise/suspended_spawn_tests.rs"]
2188mod suspended_spawn_tests;
2189
2190#[cfg(all(test, target_os = "linux"))]
2191#[path = "supervise/cgroup_reap_tests.rs"]
2192mod cgroup_reap_tests;
2193
2194#[cfg(test)]
2195#[path = "supervise/supervise_tests.rs"]
2196mod tests;
2197
2198#[cfg(test)]
2199#[path = "supervise/spawn_record_tests.rs"]
2200mod spawn_record_tests;
2201
2202#[cfg(all(test, target_os = "linux"))]
2203#[path = "supervise/spawn_image_tests.rs"]
2204mod spawn_image_tests;
2205
2206#[cfg(test)]
2207#[path = "supervise/slot_registration_wait_tests.rs"]
2208mod slot_registration_wait_tests;
2209
2210#[cfg(test)]
2211#[path = "supervise/terminal_history_tests.rs"]
2212mod terminal_history_tests;
2213
2214#[cfg(all(test, unix))]
2215#[path = "supervise/health_event_tests.rs"]
2216mod health_event_tests;
2217
2218#[cfg(test)]
2219#[path = "supervise/drain_busy_reprobe_tests.rs"]
2220mod drain_busy_reprobe_tests;
2221
2222#[cfg(test)]
2223#[path = "supervise/health_evidence_tests.rs"]
2224mod health_evidence_tests;
2225
2226#[cfg(test)]
2227#[path = "supervise/health_tombstone_tests.rs"]
2228mod health_tombstone_tests;
2229
2230#[cfg(test)]
2231#[path = "supervise/child_env_tests.rs"]
2232mod child_env_tests;
2233
2234#[cfg(test)]
2235#[path = "supervise/jitter_tests.rs"]
2236mod jitter_tests;
2237
2238#[cfg(all(test, target_os = "linux"))]
2239#[path = "supervise/cgroup_placement_tests.rs"]
2240mod cgroup_placement_tests;
2241
2242#[cfg(test)]
2243#[path = "supervise/spawn_subscriber_lag_tests.rs"]
2244mod spawn_subscriber_lag_tests;
2245
2246#[cfg(test)]
2247#[path = "supervise/terminal_history_read_concurrency_tests.rs"]
2248mod terminal_history_read_concurrency_tests;
2249
2250#[cfg(test)]
2255#[path = "supervise/stderr_settle_tests.rs"]
2256mod stderr_settle_tests;
2257
2258#[cfg(all(test, windows))]
2272#[path = "supervise/job_containment_tests.rs"]
2273mod job_containment_tests;
2274
2275#[cfg(test)]
2276#[path = "supervise/privacy_trampoline_configuration_tests.rs"]
2277mod privacy_trampoline_configuration_tests;
2278
2279#[cfg(test)]
2280#[path = "supervise/privacy_exec_boundary_tests.rs"]
2281mod privacy_exec_boundary_tests;
2282
2283#[cfg(all(test, unix))]
2287#[path = "supervise/launch_nonce_descriptor_tests.rs"]
2288mod launch_nonce_descriptor_tests;
2289
2290#[cfg(all(test, target_os = "linux"))]
2291#[path = "supervise/cgroup_containment_tests.rs"]
2292mod cgroup_containment_tests;
2293
2294#[cfg(all(test, unix))]
2297#[path = "supervise/record_write_stall_tests.rs"]
2298mod record_write_stall_tests;
2299
2300#[cfg(all(test, unix))]
2301#[path = "supervise/retained_status_tests.rs"]
2302mod retained_status_tests;