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 pub(crate) legacy_registration_spawn: bool,
553 pub(crate) registration_declaration: Option<String>,
554 pub module_id: String,
555 pub stop_reason: Option<ModuleStopReason>,
558 pub waiting_for_previous_pid: Option<u32>,
560 pub waiting_for_previous_detail: Option<String>,
562 pub launch_nonce_source: Option<String>,
567 pub state: ModuleState,
568 pub enabled: bool,
569 pub process_alive: bool,
570 pub registration_active: bool,
571 pub protocol: ModuleProtocol,
576 pub live: bool,
587 pub restart_count: u32,
591 pub lifetime_restarts: u32,
595 pub spawn_generation: u64,
596 pub swap_outcome: Option<SwapOutcome>,
598 pub max_restarts: u32,
603 pub restart_window: Duration,
607 pub drain_timeout: Duration,
611 pub restart_backoff: Duration,
612 pub restart_max_backoff: Duration,
613 pub pid: Option<u32>,
618 pub spawned_at_ms: Option<u64>,
619 pub spawned_from: Option<PathBuf>,
620 pub(crate) launch_spec_digest: Option<LaunchSpecDigest>,
621 pub process_start_time: Option<u64>,
622 pub last_exit: Option<ExitReport>,
623 pub health: ModuleHealthStatus,
624}
625
626#[derive(Debug, Clone, PartialEq)]
627struct SupervisorSnapshot {
628 admission_refused: Option<String>,
629 config_hold_parked: bool,
631 config_hold_daemon_initiated: bool,
634 config_hold_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
636 approved_start_failure: Option<(crate::config_gate::runtime::ApprovalIdentity, String)>,
638 legacy_registration_spawn: bool,
639 registration_declaration: Option<String>,
640 stop_reason: Option<ModuleStopReason>,
641 config_exit_failed_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
642 subtree_target: crate::subtree_resources::Target,
643 failed_retry: FailedRetry,
644 exec_outcome: Option<Arc<crate::activity::ExecOutcome>>,
645 #[cfg(windows)]
646 pipe_consumed: Option<Arc<OnceLock<()>>>,
647 #[cfg(test)]
649 actor_turns: u64,
650 #[cfg(test)]
653 actor_select: Option<ActorSelectCheckpoint>,
654 state: ModuleState,
655 enabled: bool,
656 process_alive: bool,
657 spawned_protocol: Option<ModuleProtocol>,
658 spawn_failure: Option<String>,
659 waiting_for_previous_pid: Option<u32>,
660 waiting_for_previous_detail: Option<String>,
661 crash_restarts: VecDeque<Instant>,
667 lifetime_restarts: u32,
668 spawn_generation: u64,
677 swap_outcome: Option<SwapOutcome>,
678 pid: Option<u32>,
679 #[cfg(target_os = "macos")]
680 report_ready: Option<Arc<OnceLock<()>>>,
681 reaped_pid: Option<u32>,
683 respawn_pending: bool,
685 coalesced_restart_pending: bool,
687 spawned_at_ms: Option<u64>,
688 spawned_from: Option<PathBuf>,
689 launch_spec_digest: Option<LaunchSpecDigest>,
690 spawned_file_identity: Option<SpawnedFileIdentity>,
691 process_start_time: Option<u64>,
692 deliberate_severance: Option<ProcessIdentity>,
693 last_exit: Option<ExitReport>,
694 drain_disposition_detail: Option<String>,
696 health: ModuleHealthStatus,
697 last_probe_evidence: Option<HealthProbeEvidence>,
698 in_alternate_slot: bool,
703 draining_to_replace: bool,
710 configuration_updated_since_spawn: bool,
716}
717
718impl SupervisorSnapshot {
719 fn reported_pid(&self) -> Option<u32> {
724 #[cfg(target_os = "macos")]
725 if self
726 .report_ready
727 .as_ref()
728 .is_some_and(|ready| ready.get().is_none())
729 {
730 return None;
731 }
732 self.pid
733 }
734
735 fn starting() -> Self {
736 Self::new(ModuleState::Starting, true)
737 }
738
739 fn disabled() -> Self {
740 Self::new(ModuleState::Disabled, false)
741 }
742
743 fn clear_crash_restarts(&mut self) {
748 self.crash_restarts.clear();
749 }
750
751 fn new(state: ModuleState, enabled: bool) -> Self {
752 Self {
753 admission_refused: None,
754 config_hold_parked: false,
755 config_hold_daemon_initiated: false,
756 config_hold_approval: None,
757 approved_start_failure: None,
758 legacy_registration_spawn: false,
759 registration_declaration: None,
760 stop_reason: None,
761 config_exit_failed_approval: None,
762 subtree_target: crate::subtree_resources::Target::Unavailable("not_running"),
763 failed_retry: FailedRetry::default(),
764 exec_outcome: None,
765 #[cfg(test)]
766 actor_turns: 0,
767 #[cfg(test)]
768 actor_select: None,
769 state,
770 enabled,
771 process_alive: false,
772 #[cfg(windows)]
773 pipe_consumed: None,
774 spawned_protocol: None,
775 spawn_failure: None,
776 waiting_for_previous_pid: None,
777 waiting_for_previous_detail: None,
778 crash_restarts: VecDeque::new(),
779 lifetime_restarts: 0,
780 spawn_generation: 0,
781 swap_outcome: None,
782 pid: None,
783 #[cfg(target_os = "macos")]
784 report_ready: None,
785 reaped_pid: None,
786 respawn_pending: false,
787 coalesced_restart_pending: false,
788 spawned_at_ms: None,
789 spawned_from: None,
790 launch_spec_digest: None,
791 spawned_file_identity: None,
792 process_start_time: None,
793 deliberate_severance: None,
794 last_exit: None,
795 drain_disposition_detail: None,
796 health: ModuleHealthStatus::default(),
797 last_probe_evidence: None,
798 in_alternate_slot: false,
799 draining_to_replace: false,
800 configuration_updated_since_spawn: false,
801 }
802 }
803}
804
805type SharedSnapshot = Arc<Mutex<SupervisorSnapshot>>;
806
807#[derive(Debug, Clone, Copy)]
808enum RespawnKind {
809 Spawn,
810 CrashRestart,
811 Reload,
812}
813
814#[derive(Debug, Clone)]
815struct PendingRespawn {
816 deadline: Instant,
817 kind: RespawnKind,
818 daemon_initiated: bool,
819 approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
820}
821
822impl PendingRespawn {
823 fn failure_context(&self, runtime: &SupervisorRuntimeConfig) -> FailureContext {
824 FailureContext {
825 approval: self.approval.clone(),
826 ..runtime.failure_context(self.daemon_initiated)
827 }
828 }
829}
830
831type ReloadReply = oneshot::Sender<Result<(), SuperviseError>>;
832
833#[derive(Debug, Clone)]
834struct SupervisorRuntimeConfig {
835 registry: Arc<Registry>,
836 config_delivery: Option<config_delivery::ConfigDelivery>,
837 recovery_is_daemon: bool,
839 start_requester: Option<Principal>,
840 pending_activity_restart: bool,
841 provenance_probe: ExecutableIdentityProbe,
842 scheduled_respawn: Arc<Mutex<Option<PendingRespawn>>>,
844 deferred_reload_reply: Arc<Mutex<Option<ReloadReply>>>,
846 restart_policy: RestartPolicy,
847 register_timeout: Duration,
848 drain_timeout: Duration,
851 effective_drain_timeout: Arc<Mutex<Duration>>,
854 default_drain_timeout: Duration,
857 health: HealthConfig,
858 host_health: HostHealth,
859 connection_file_path: Option<PathBuf>,
860 capture_logs_dir: Option<PathBuf>,
861 forwarding: Option<Arc<ForwardingTable>>,
862 supervisor_handle: Option<SupervisorHandle>,
863 #[cfg(any(target_os = "linux", target_os = "macos"))]
864 replacement_ticket: Option<live_upgrade::ReplacementTicket>,
865 stderr_ring: Arc<Mutex<StderrRing>>,
872 terminal_ring: Arc<Mutex<TerminalRing>>,
873 spawn_events: SpawnEventFeed,
874 child_roster: ChildRoster,
875 #[cfg(target_os = "linux")]
876 cgroup_placement: Option<subc_cgroup::Placement>,
877 #[cfg(test)]
878 test_seed_stale_facts_before_enable_spawn: bool,
879 #[cfg(test)]
880 test_reload_exit_record_gate: Option<Arc<ReloadExitRecordGate>>,
881}
882
883impl SupervisorRuntimeConfig {
884 fn failure_context(&self, daemon_initiated: bool) -> FailureContext {
885 FailureContext {
886 daemon_initiated,
887 approval: None,
888 shutdown: self.child_roster.shutdown_flag(),
889 }
890 }
891}
892
893#[derive(Debug, Clone, PartialEq, Eq)]
894struct SupervisedConfiguration {
895 spec: ModuleSpec,
896 enabled: bool,
897 health: HealthConfig,
898 register_timeout: Duration,
899 restart_policy: RestartPolicy,
900}
901
902#[derive(Debug, Clone, Default)]
905pub struct SupervisorHandle {
906 pub(crate) pending_adoptions: resume_hello::PendingAdoptions,
907 upgrade_state: live_upgrade::UpgradeState,
908 #[cfg(test)]
909 resource_commit_pause: Arc<Mutex<Option<resource_launch::ResourceCommitPause>>>,
910 #[cfg(test)]
911 registration_test_channels: CapturedRegistrationChannels,
912 registration_service: Arc<Mutex<Option<registration::RegistrationService>>>,
913 registration_connections: Arc<Mutex<HashMap<ConnectionId, Arc<RegistrationSpawn>>>>,
914 registration_launches: Arc<Mutex<Vec<std::sync::Weak<RegistrationSpawn>>>>,
915 gate_runtime: Arc<Mutex<Option<std::sync::Weak<crate::config_gate::runtime::RuntimeOwner>>>>,
916 program_bindings: program_binding::ProgramBindings,
917 #[cfg(test)]
918 identity_sample_pause: Arc<Mutex<Option<IdentitySamplePause>>>,
919 #[cfg(all(test, unix))]
920 plain_identity_policy_pause: Arc<Mutex<Option<(String, IdentitySamplePause)>>>,
921 host_health: HostHealth,
922 restart_intent: Arc<Mutex<DaemonRestartIntent>>,
923 activity: Arc<Mutex<Option<crate::activity::ActivityLedger>>>,
924 activity_images: Arc<Mutex<HashMap<String, activity::ActivityImage>>>,
925 modules: Arc<Mutex<HashMap<String, SupervisedModule>>>,
926 configured_ids: Arc<Mutex<HashSet<String>>>,
938 spawn_events: SpawnEventFeed,
939 reserved_nonces: Arc<Mutex<HashMap<String, Option<String>>>>,
950 implicit_protocol_none: Arc<Mutex<HashSet<String>>>,
954 removal_tombstones: Arc<Mutex<HashMap<String, u64>>>,
960 spawn_nonces: Arc<Mutex<HashMap<String, String>>>,
964 nonce_launches: Arc<Mutex<NonceLaunches>>,
970 reserved_prefix_owners: Arc<Mutex<HashMap<String, String>>>,
978 swaps: Arc<Mutex<HashMap<String, OpenSwap>>>,
984 promotion_observer: PromotionObserverSlot,
986 operation_lock: Arc<AsyncMutex<()>>,
990}
991
992#[derive(Debug)]
993struct DaemonRestartIntent {
994 expires: Option<Duration>,
995 window: Duration,
996}
997
998impl Default for DaemonRestartIntent {
999 fn default() -> Self {
1000 Self {
1001 expires: None,
1002 window: Duration::from_secs(120),
1003 }
1004 }
1005}
1006
1007impl SupervisorHandle {
1008 pub(crate) fn module_is_gated(&self, module: &str) -> bool {
1009 let runtime = {
1010 let Ok(runtime) = self.gate_runtime.lock() else {
1011 return true;
1012 };
1013 runtime.clone()
1014 };
1015 runtime.is_some_and(|runtime| {
1016 runtime
1017 .upgrade()
1018 .is_none_or(|owner| owner.module_is_gated(module))
1019 })
1020 }
1021 pub(crate) fn announce_daemon_restart(&self) -> u64 {
1022 let mut intent = self
1023 .restart_intent
1024 .lock()
1025 .unwrap_or_else(|p| p.into_inner());
1026 intent.expires = Some(subc_uptime::suspend_inclusive_now() + intent.window);
1027 unix_ms_now().saturating_add(intent.window.as_millis() as u64)
1028 }
1029
1030 #[cfg(feature = "test-support")]
1031 pub(crate) fn set_shutdown_intent_window(&self, window: Duration) {
1032 self.restart_intent
1033 .lock()
1034 .unwrap_or_else(|p| p.into_inner())
1035 .window = window;
1036 }
1037
1038 #[cfg(unix)]
1039 fn take_daemon_shutdown_reason(&self) -> RouteCloseReason {
1040 let expiry = self
1041 .restart_intent
1042 .lock()
1043 .unwrap_or_else(|p| p.into_inner())
1044 .expires
1045 .take();
1046 if expiry.is_some_and(|expiry| subc_uptime::suspend_inclusive_now() < expiry) {
1047 RouteCloseReason::Restart
1048 } else {
1049 RouteCloseReason::Disable
1050 }
1051 }
1052
1053 pub fn new() -> Self {
1054 Self::default()
1055 }
1056
1057 pub(crate) fn operation_lock(&self) -> Arc<AsyncMutex<()>> {
1058 Arc::clone(&self.operation_lock)
1059 }
1060}
1061
1062#[derive(Debug, Clone)]
1064pub struct Supervisor {
1065 registry: Arc<Registry>,
1066 config_delivery: Option<config_delivery::ConfigDelivery>,
1067 restart_policy: RestartPolicy,
1068 drain_timeout: Duration,
1069 connection_file_path: Option<PathBuf>,
1070 capture_logs_dir: Option<PathBuf>,
1071 forwarding: Option<Arc<ForwardingTable>>,
1072 process_liveness: Arc<SupervisorProcessLiveness>,
1073 supervisor_handle: Option<SupervisorHandle>,
1074 health: HealthConfig,
1075 host_health: HostHealth,
1076 daemon_start_clock: crate::clock::StartClock,
1077 terminal_journal: Option<Arc<crate::terminal_journal::TerminalJournal>>,
1078 spawn_events: SpawnEventFeed,
1079 provenance_probe: ExecutableIdentityProbe,
1080 child_roster: ChildRoster,
1083 #[cfg(target_os = "linux")]
1084 cgroup_placement: Option<subc_cgroup::Placement>,
1085 #[cfg(test)]
1086 test_after_first_spawn: AfterFirstSpawnHook,
1087}
1088
1089impl Supervisor {
1090 pub fn new(registry: Arc<Registry>, restart_policy: RestartPolicy) -> Self {
1091 Self {
1092 registry,
1093 config_delivery: None,
1094 restart_policy,
1095 drain_timeout: DEFAULT_DRAIN_TIMEOUT,
1096 connection_file_path: None,
1097 capture_logs_dir: None,
1098 forwarding: None,
1099 process_liveness: Arc::new(SupervisorProcessLiveness::default()),
1100 supervisor_handle: None,
1101 health: HealthConfig::default(),
1102 host_health: HostHealth::default(),
1103 daemon_start_clock: crate::clock::StartClock::capture(),
1104 terminal_journal: None,
1105 spawn_events: SpawnEventFeed::default(),
1106 provenance_probe: ExecutableIdentityProbe::default(),
1107 child_roster: ChildRoster::default(),
1108 #[cfg(target_os = "linux")]
1109 cgroup_placement: None,
1110 #[cfg(test)]
1111 test_after_first_spawn: AfterFirstSpawnHook::default(),
1112 }
1113 }
1114
1115 pub fn with_drain_timeout(mut self, drain_timeout: Duration) -> Self {
1116 self.drain_timeout = drain_timeout;
1117 self
1118 }
1119
1120 pub(crate) fn default_drain_timeout(&self) -> Duration {
1122 self.drain_timeout
1123 }
1124
1125 pub fn with_process_liveness(
1126 mut self,
1127 process_liveness: Arc<SupervisorProcessLiveness>,
1128 ) -> Self {
1129 self.process_liveness = process_liveness;
1130 self
1131 }
1132
1133 pub fn with_config_runtime(
1135 mut self,
1136 owner: Arc<crate::config_gate::runtime::RuntimeOwner>,
1137 ) -> Self {
1138 if let Some(handle) = &self.supervisor_handle {
1139 handle.install_binding_retirement(&owner);
1140 }
1141 self.config_delivery = Some(config_delivery::ConfigDelivery(owner));
1142 self
1143 }
1144
1145 pub fn with_connection_file_path(mut self, connection_file_path: impl Into<PathBuf>) -> Self {
1146 self.connection_file_path = Some(connection_file_path.into());
1147 self
1148 }
1149
1150 pub fn with_capture_logs_dir(mut self, logs_dir: impl Into<PathBuf>) -> Self {
1152 self.capture_logs_dir = Some(logs_dir.into());
1153 self
1154 }
1155
1156 pub fn with_daemon_incarnation(self, daemon_incarnation: String) -> Self {
1159 self.spawn_events.configure_incarnation(daemon_incarnation);
1163 self
1164 }
1165
1166 pub fn with_terminal_journal(self, path: PathBuf, daemon_incarnation: String) -> Self {
1169 let mut this = self.with_daemon_incarnation(daemon_incarnation.clone());
1170 this.terminal_journal = Some(Arc::new(crate::terminal_journal::TerminalJournal::open(
1171 path,
1172 daemon_incarnation,
1173 )));
1174 this
1175 }
1176
1177 pub fn with_forwarding(mut self, forwarding: Arc<ForwardingTable>) -> Self {
1178 self.child_roster.counters = forwarding.counters();
1179 self.forwarding = Some(forwarding);
1180 self
1181 }
1182
1183 pub fn with_handle(mut self, supervisor_handle: SupervisorHandle) -> Self {
1184 if let Some(delivery) = &self.config_delivery {
1185 supervisor_handle.install_binding_retirement(&delivery.0);
1186 }
1187 self.host_health = supervisor_handle.host_health.clone();
1188 self.spawn_events = supervisor_handle.spawn_events.clone();
1189 self.supervisor_handle = Some(supervisor_handle);
1190 self
1191 }
1192
1193 pub fn with_health_config(mut self, health: HealthConfig) -> Self {
1194 self.health = health;
1195 self
1196 }
1197
1198 pub fn with_live_children_record(self, path: impl Into<PathBuf>) -> Self {
1202 self.child_roster.record_to(path.into());
1203 self
1204 }
1205
1206 #[cfg(any(target_os = "linux", target_os = "macos"))]
1207 pub(crate) fn with_resume_roster(
1208 self,
1209 path: PathBuf,
1210 protected: &crate::live_children::AdoptedPids,
1211 ) -> Self {
1212 self.child_roster.record_to_with_adopted(path, protected);
1213 self
1214 }
1215
1216 #[cfg(target_os = "linux")]
1217 pub fn with_cgroup_placement(
1218 mut self,
1219 cgroup_placement: Option<subc_cgroup::Placement>,
1220 ) -> Self {
1221 self.child_roster
1222 .set_cgroup_placement(cgroup_placement.clone());
1223 self.cgroup_placement = cgroup_placement;
1224 self
1225 }
1226}
1227
1228impl Default for Supervisor {
1229 fn default() -> Self {
1230 Self::new(Arc::new(Registry::default()), RestartPolicy::default())
1231 }
1232}
1233
1234#[derive(Clone)]
1236pub struct SupervisedModule {
1237 inner: Arc<SupervisedModuleInner>,
1238}
1239
1240struct SupervisedModuleInner {
1241 retained: crate::child_roster::RetainedView,
1242 module_id: String,
1243 registry: Arc<Registry>,
1244 snapshot: SharedSnapshot,
1245 configuration: Arc<Mutex<SupervisedConfiguration>>,
1246 stderr_ring: Arc<Mutex<StderrRing>>,
1247 terminal_ring: Arc<Mutex<TerminalRing>>,
1248 commands: mpsc::Sender<SupervisorCommand>,
1249 monitor: Mutex<Option<JoinHandle<()>>>,
1250 effective_drain_timeout: Arc<Mutex<Duration>>,
1251 provenance_probe: ExecutableIdentityProbe,
1252}
1253
1254impl fmt::Debug for SupervisedModule {
1255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1256 f.debug_struct("SupervisedModule")
1257 .field("module_id", &self.inner.module_id)
1258 .field("status", &self.status())
1259 .finish_non_exhaustive()
1260 }
1261}
1262
1263impl SupervisedModule {
1264 pub fn module_id(&self) -> &str {
1265 &self.inner.module_id
1266 }
1267
1268 pub fn state(&self) -> Result<ModuleState, SuperviseError> {
1269 Ok(lock_snapshot(&self.inner.snapshot)?.state)
1270 }
1271
1272 pub(crate) fn registration_end_reason(
1273 &self,
1274 ) -> Result<Option<RegistrationEndReason>, SuperviseError> {
1275 let snapshot = lock_snapshot(&self.inner.snapshot)?;
1276 Ok(match snapshot.state {
1277 ModuleState::Draining if snapshot.draining_to_replace => {
1278 Some(RegistrationEndReason::SupervisorRestart)
1279 }
1280 ModuleState::Draining => Some(RegistrationEndReason::SupervisorStop),
1281 ModuleState::Restarting if snapshot.draining_to_replace => {
1282 Some(RegistrationEndReason::SupervisorRestart)
1283 }
1284 _ => None,
1285 })
1286 }
1287
1288 pub fn stderr_tail(
1295 &self,
1296 max_lines: Option<usize>,
1297 max_bytes: Option<usize>,
1298 ) -> StderrTailSnapshot {
1299 self.inner
1300 .stderr_ring
1301 .lock()
1302 .unwrap_or_else(|poisoned| poisoned.into_inner())
1303 .snapshot(max_lines, max_bytes)
1304 }
1305
1306 pub fn terminal_history(&self) -> TerminalHistorySnapshot {
1311 self.inner
1312 .terminal_ring
1313 .lock()
1314 .unwrap_or_else(|poisoned| poisoned.into_inner())
1315 .snapshot()
1316 }
1317
1318 pub fn durable_terminal_history(&self) -> subc_control::TerminalHistory {
1323 durable_terminal_history_of(&self.inner.terminal_ring, &self.inner.module_id)
1324 }
1325
1326 pub(crate) async fn read_durable_terminal_history(
1331 &self,
1332 ) -> Result<subc_control::TerminalHistory, tokio::task::JoinError> {
1333 let terminal_ring = Arc::clone(&self.inner.terminal_ring);
1334 let module_id = self.inner.module_id.clone();
1335 tokio::task::spawn_blocking(move || durable_terminal_history_of(&terminal_ring, &module_id))
1336 .await
1337 }
1338
1339 pub fn status(&self) -> Result<ModuleStatus, SuperviseError> {
1340 self.status_with_snapshot_lock(&self.inner.snapshot, None)
1341 .map(|(status, _)| status)
1342 }
1343
1344 pub(crate) fn next_retry_at_ms(&self) -> Result<Option<u64>, SuperviseError> {
1345 let state = lock_snapshot(&self.inner.snapshot)?;
1346 Ok(state
1347 .failed_retry
1348 .pending
1349 .filter(|_| state.state == ModuleState::Failed && state.enabled)
1350 .map(|retry| {
1351 unix_ms_now().saturating_add(
1352 u64::try_from(
1353 retry
1354 .deadline
1355 .saturating_duration_since(Instant::now())
1356 .as_millis(),
1357 )
1358 .unwrap_or(u64::MAX),
1359 )
1360 }))
1361 }
1362
1363 #[cfg(all(test, unix))]
1364 pub(crate) fn retry_deadline_for_test(&self) -> Option<Instant> {
1365 lock_snapshot(&self.inner.snapshot)
1366 .unwrap()
1367 .failed_retry
1368 .pending
1369 .map(|retry| retry.deadline)
1370 }
1371
1372 pub(crate) fn status_for_control(
1377 &self,
1378 caller: &'static str,
1379 ) -> Result<ModuleStatus, SuperviseError> {
1380 self.status_with_snapshot_lock(&self.inner.snapshot, Some(caller))
1381 .map(|(status, _)| status)
1382 }
1383
1384 fn status_with_snapshot_lock(
1385 &self,
1386 snapshot: &SharedSnapshot,
1387 caller: Option<&'static str>,
1388 ) -> Result<(ModuleStatus, Option<SpawnedFileIdentity>), SuperviseError> {
1389 let restart_policy = self
1390 .inner
1391 .configuration
1392 .lock()
1393 .map_err(|_| SuperviseError::StatePoisoned {
1394 module_id: Some(self.inner.module_id.clone()),
1395 })?
1396 .restart_policy;
1397 let mut guard = match caller {
1398 Some(caller) => lock_snapshot_for_control(snapshot, &self.inner.module_id, caller)?,
1399 None => lock_snapshot(snapshot)?,
1400 };
1401 let restart_count = guard.crash_restarts_in_window(restart_policy.window, Instant::now());
1404 let snapshot = guard.clone();
1405 drop(guard);
1406 let drain_timeout = *self.inner.effective_drain_timeout.lock().map_err(|_| {
1407 SuperviseError::StatePoisoned {
1408 module_id: Some(self.inner.module_id.clone()),
1409 }
1410 })?;
1411 let registration_active = self
1412 .inner
1413 .registry
1414 .get_module(&self.inner.module_id)
1415 .map_err(SuperviseError::Registry)?
1416 .is_some();
1417 let protocol = snapshot
1418 .spawned_protocol
1419 .unwrap_or(self.declared_protocol()?);
1420 let running_process =
1421 snapshot.enabled && snapshot.state == ModuleState::Running && snapshot.process_alive;
1422 let live = match protocol {
1428 ModuleProtocol::Subc => running_process && registration_active,
1429 ModuleProtocol::None => running_process,
1430 };
1431 let retained = self.inner.retained.waiting_detail(&self.inner.module_id);
1434 let carry_configured = self
1435 .inner
1436 .configuration
1437 .lock()
1438 .map_err(|_| SuperviseError::StatePoisoned {
1439 module_id: Some(self.inner.module_id.clone()),
1440 })?
1441 .spec
1442 .carry_containment;
1443 let recovery_block = carries_containment(
1444 carry_configured,
1445 self.inner
1446 .retained
1447 .has_carried_container(&self.inner.module_id),
1448 )
1449 .then(|| self.inner.retained.recovery_block())
1450 .flatten();
1451 let launch_nonce_source = observed_launch_nonce_source(&snapshot);
1452 let pid = snapshot.reported_pid();
1453 let mut health = snapshot.health;
1454 if let Some(detail) = recovery_block
1455 .as_ref()
1456 .or_else(|| retained.as_ref().map(|(_, detail)| detail))
1457 {
1458 health.detail = Some(match health.detail {
1459 Some(previous) => format!("{previous}; {detail}"),
1460 None => detail.clone(),
1461 });
1462 }
1463
1464 Ok((
1465 ModuleStatus {
1466 admission_refused: snapshot.admission_refused,
1467 legacy_registration_spawn: snapshot.legacy_registration_spawn,
1468 registration_declaration: snapshot.registration_declaration.clone(),
1469 stop_reason: snapshot.stop_reason,
1470 waiting_for_previous_pid: retained
1471 .as_ref()
1472 .map(|(pid, _)| *pid)
1473 .filter(|pid| *pid > 0)
1474 .or(snapshot.waiting_for_previous_pid),
1475 waiting_for_previous_detail: recovery_block
1476 .or_else(|| retained.map(|(_, detail)| detail))
1477 .or(snapshot.waiting_for_previous_detail),
1478 module_id: self.inner.module_id.clone(),
1479 launch_nonce_source,
1480 state: snapshot.state,
1481 enabled: snapshot.enabled,
1482 process_alive: snapshot.process_alive,
1483 registration_active,
1484 protocol,
1485 live,
1486 restart_count,
1487 lifetime_restarts: snapshot.lifetime_restarts,
1488 spawn_generation: snapshot.spawn_generation,
1489 swap_outcome: snapshot.swap_outcome,
1490 max_restarts: restart_policy.max_restarts,
1491 restart_window: restart_policy.window,
1492 drain_timeout,
1493 restart_backoff: restart_policy.backoff,
1494 restart_max_backoff: restart_policy.max_backoff,
1495 pid,
1496 spawned_at_ms: snapshot.spawned_at_ms,
1497 spawned_from: snapshot.spawned_from,
1498 launch_spec_digest: snapshot.launch_spec_digest,
1499 process_start_time: snapshot.process_start_time,
1500 last_exit: snapshot.last_exit,
1501 health,
1502 },
1503 snapshot.spawned_file_identity.clone(),
1504 ))
1505 }
1506
1507 #[cfg(test)]
1508 pub(crate) fn hold_snapshot_for_test(
1509 &self,
1510 acquired: std::sync::mpsc::Sender<()>,
1511 hold: Duration,
1512 ) -> std::thread::JoinHandle<()> {
1513 let snapshot = Arc::clone(&self.inner.snapshot);
1514 std::thread::spawn(move || {
1515 let _guard = snapshot.lock().expect("test snapshot lock is not poisoned");
1516 acquired
1517 .send(())
1518 .expect("test receiver waits for snapshot lock");
1519 std::thread::sleep(hold);
1520 })
1521 }
1522
1523 pub(crate) async fn status_and_running_image_agreement(
1529 &self,
1530 ) -> Result<(ModuleStatus, subc_control::RunningImageAgreement), SuperviseError> {
1531 let (status, identity) = self.status_with_snapshot_lock(&self.inner.snapshot, None)?;
1532 let image = self
1533 .inner
1534 .provenance_probe
1535 .observe(
1536 status.pid,
1537 status.spawned_from.as_deref(),
1538 identity,
1539 status.process_start_time,
1540 )
1541 .await;
1542 Ok((status, image))
1543 }
1544
1545 pub(crate) async fn running_image_agreement(&self) -> subc_control::RunningImageAgreement {
1546 let snapshot = match lock_snapshot(&self.inner.snapshot) {
1547 Ok(snapshot) => snapshot.clone(),
1548 Err(_) => {
1549 return subc_control::RunningImageAgreement::Unavailable {
1550 reason: subc_control::RunningImageUnavailableReason::NotRunning,
1551 };
1552 }
1553 };
1554 self.inner
1555 .provenance_probe
1556 .observe(
1557 snapshot.reported_pid(),
1558 snapshot.spawned_from.as_deref(),
1559 snapshot.spawned_file_identity.clone(),
1560 snapshot.process_start_time,
1561 )
1562 .await
1563 }
1564
1565 pub(crate) fn child_resource_usage(&self) -> subc_control::ChildResourceUsage {
1568 #[cfg(windows)]
1569 {
1570 let image = lock_snapshot(&self.inner.snapshot)
1571 .ok()
1572 .and_then(|snapshot| {
1573 snapshot
1574 .spawned_file_identity
1575 .as_ref()
1576 .and_then(|identity| identity.windows_image.clone())
1577 });
1578 match image {
1579 Some(image) => {
1580 crate::child_resources::read_windows_handle(image.process(), image.start_time())
1581 }
1582 None => subc_control::ChildResourceUsage::Unavailable {
1583 reason: subc_control::ChildResourceUnavailableReason::NotRunning,
1584 },
1585 }
1586 }
1587 #[cfg(not(windows))]
1588 {
1589 let (pid, start_time) = match lock_snapshot(&self.inner.snapshot) {
1590 Ok(snapshot) => (snapshot.reported_pid(), snapshot.process_start_time),
1591 Err(_) => {
1592 return subc_control::ChildResourceUsage::Unavailable {
1593 reason: subc_control::ChildResourceUnavailableReason::Unreadable,
1594 }
1595 }
1596 };
1597 crate::child_resources::read(pid, start_time)
1598 }
1599 }
1600
1601 #[cfg(all(test, any(target_os = "linux", windows)))]
1602 pub(crate) fn subtree_target(&self) -> crate::subtree_resources::Target {
1603 self.inner
1604 .snapshot
1605 .try_lock()
1606 .map(|snapshot| snapshot.subtree_target.clone())
1607 .unwrap_or(crate::subtree_resources::Target::Unavailable("read_failed"))
1608 }
1609
1610 #[cfg(test)]
1611 pub(crate) fn set_subtree_target_for_test(&self, target: crate::subtree_resources::Target) {
1612 self.inner.snapshot.lock().unwrap().subtree_target = target;
1613 }
1614
1615 pub(crate) fn will_recover_after_connection_loss(&self) -> Result<bool, SuperviseError> {
1616 let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
1617 Ok(match snapshot.state {
1618 ModuleState::Restarting => true,
1619 ModuleState::Failed | ModuleState::Disabled => false,
1620 _ if snapshot.enabled && snapshot.respawn_pending => true,
1621 _ => daemon_will_restart(
1622 &mut snapshot,
1623 &self
1624 .inner
1625 .configuration
1626 .lock()
1627 .map_err(|_| SuperviseError::StatePoisoned {
1628 module_id: Some(self.inner.module_id.clone()),
1629 })?
1630 .restart_policy,
1631 Instant::now(),
1632 ),
1633 })
1634 }
1635
1636 #[cfg(test)]
1637 pub(crate) fn is_warming(&self) -> Result<bool, SuperviseError> {
1638 self.is_warming_with_snapshot_lock(None)
1639 }
1640
1641 pub(crate) fn is_warming_for_control(
1642 &self,
1643 caller: &'static str,
1644 ) -> Result<bool, SuperviseError> {
1645 self.is_warming_with_snapshot_lock(Some(caller))
1646 }
1647
1648 fn is_warming_with_snapshot_lock(
1649 &self,
1650 caller: Option<&'static str>,
1651 ) -> Result<bool, SuperviseError> {
1652 let snapshot = match caller {
1653 Some(caller) => {
1654 lock_snapshot_for_control(&self.inner.snapshot, &self.inner.module_id, caller)?
1655 }
1656 None => lock_snapshot(&self.inner.snapshot)?,
1657 }
1658 .clone();
1659 Ok(matches!(
1660 snapshot.state,
1661 ModuleState::Starting | ModuleState::Running | ModuleState::Restarting
1662 ))
1663 }
1664
1665 pub(crate) fn declared_protocol(&self) -> Result<ModuleProtocol, SuperviseError> {
1669 let configured = self
1670 .inner
1671 .configuration
1672 .lock()
1673 .map_err(|_| SuperviseError::StatePoisoned {
1674 module_id: Some(self.inner.module_id.clone()),
1675 })?
1676 .spec
1677 .protocol;
1678 let state = lock_snapshot(&self.inner.snapshot)?;
1679 Ok(state.spawned_protocol.unwrap_or(configured))
1680 }
1681
1682 pub(crate) fn configuration(&self) -> Result<(ModuleSpec, HealthConfig), SuperviseError> {
1683 let configuration =
1684 self.inner
1685 .configuration
1686 .lock()
1687 .map_err(|_| SuperviseError::StatePoisoned {
1688 module_id: Some(self.inner.module_id.clone()),
1689 })?;
1690 Ok((configuration.spec.clone(), configuration.health.clone()))
1691 }
1692
1693 pub(crate) fn configured_register_timeout(&self) -> Result<Duration, SuperviseError> {
1694 self.inner
1695 .configuration
1696 .lock()
1697 .map(|configuration| configuration.register_timeout)
1698 .map_err(|_| SuperviseError::StatePoisoned {
1699 module_id: Some(self.inner.module_id.clone()),
1700 })
1701 }
1702
1703 pub(crate) fn configured_enabled(&self) -> Result<bool, SuperviseError> {
1704 self.inner
1705 .configuration
1706 .lock()
1707 .map(|configuration| configuration.enabled)
1708 .map_err(|_| SuperviseError::StatePoisoned {
1709 module_id: Some(self.inner.module_id.clone()),
1710 })
1711 }
1712
1713 #[cfg(any(test, feature = "test-support"))]
1717 pub async fn update_spec_for_test(&self, spec: ModuleSpec) -> Result<(), SuperviseError> {
1718 let (_, health) = self.configuration()?;
1719 let drain_timeout_ms = u64::try_from(
1720 self.inner
1721 .effective_drain_timeout
1722 .lock()
1723 .unwrap_or_else(|poisoned| poisoned.into_inner())
1724 .as_millis(),
1725 )
1726 .ok();
1727 self.update_configuration(spec, health, drain_timeout_ms)
1728 .await
1729 }
1730
1731 pub(crate) async fn update_configuration(
1732 &self,
1733 spec: ModuleSpec,
1734 health: HealthConfig,
1735 drain_timeout_ms: Option<u64>,
1736 ) -> Result<(), SuperviseError> {
1737 if spec.module_id != self.inner.module_id {
1738 return Err(SuperviseError::InvalidSpec {
1739 reason: "a supervised module's module_id cannot be changed".to_string(),
1740 });
1741 }
1742 validate_spec(&spec)?;
1743 let (reply_tx, reply_rx) = oneshot::channel();
1744 self.inner
1745 .commands
1746 .send(SupervisorCommand::UpdateConfiguration {
1747 spec: spec.clone(),
1748 health: health.clone(),
1749 drain_timeout_ms,
1750 reply: reply_tx,
1751 })
1752 .await
1753 .map_err(|_| SuperviseError::CommandClosed {
1754 module_id: self.inner.module_id.clone(),
1755 })?;
1756 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
1757 module_id: self.inner.module_id.clone(),
1758 })??;
1759 let mut configuration =
1760 self.inner
1761 .configuration
1762 .lock()
1763 .map_err(|_| SuperviseError::StatePoisoned {
1764 module_id: Some(self.inner.module_id.clone()),
1765 })?;
1766 configuration.spec = spec;
1767 configuration.health = health;
1768 Ok(())
1769 }
1770}
1771
1772impl Drop for SupervisedModuleInner {
1773 fn drop(&mut self) {
1774 let Ok(mut monitor) = self.monitor.lock() else {
1775 return;
1776 };
1777 if let Some(monitor) = monitor.as_ref().filter(|monitor| !monitor.is_finished()) {
1778 let _ = update_snapshot(&self.snapshot, Some(&self.module_id), |state| {
1779 state.state = ModuleState::Stopped;
1780 clear_current_process_facts(state);
1781 });
1782 monitor.abort();
1783 }
1784 let _ = monitor.take();
1785 }
1786}
1787
1788#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1792pub enum SwapOutcome {
1793 Cutover,
1794 SupersededByConfigRestart,
1795}
1796
1797impl SwapOutcome {
1798 pub fn as_str(self) -> &'static str {
1799 match self {
1800 Self::Cutover => "cutover",
1801 Self::SupersededByConfigRestart => "superseded_by_config_restart",
1802 }
1803 }
1804}
1805
1806#[derive(Debug)]
1807pub enum SuperviseError {
1808 UpgradeInProgress,
1809 ConfigHeld {
1810 module_id: String,
1811 code: String,
1812 detail: String,
1813 },
1814 ConfigDeliveryDeferred {
1815 module_id: String,
1816 },
1817 InvalidSpec {
1818 reason: String,
1819 },
1820 Spawn {
1821 program: PathBuf,
1822 source: io::Error,
1823 cgroup_path: Option<PathBuf>,
1824 },
1825 Cgroup {
1826 module_id: String,
1827 source: io::Error,
1828 },
1829 LaunchNonce {
1833 reason: String,
1834 },
1835 Wait {
1836 module_id: String,
1837 source: io::Error,
1838 },
1839 Kill {
1840 module_id: String,
1841 source: io::Error,
1842 },
1843 Forwarding(ForwardingError),
1844 Registry(RegistryError),
1845 ReloadUnavailable {
1846 module_id: String,
1847 reason: String,
1848 },
1849 Disabled {
1854 module_id: String,
1855 },
1856 ReloadFailed {
1857 module_id: String,
1858 reason: String,
1859 },
1860 RegistrationStillActive {
1861 module_id: String,
1862 waited: Duration,
1863 },
1864 StatePoisoned {
1865 module_id: Option<String>,
1866 },
1867 CommandClosed {
1868 module_id: String,
1869 },
1870 SwapInProgress {
1874 module_id: String,
1875 },
1876 SwapRefused {
1878 module_id: String,
1879 reason: SwapRefusal,
1880 },
1881 SwapFailed {
1885 module_id: String,
1886 arm: SwapFailureArm,
1887 detail: String,
1888 candidate_exit: Option<ExitReport>,
1891 },
1892}
1893
1894#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1896pub enum SwapRefusal {
1897 OverlapExclusive,
1899 NotRegistered,
1902 ProtocolNone,
1905 NotConfigured,
1908 AlreadySwapping,
1910}
1911
1912impl SwapRefusal {
1913 pub fn as_str(self) -> &'static str {
1914 match self {
1915 Self::OverlapExclusive => "overlap_exclusive",
1916 Self::NotRegistered => "not_registered",
1917 Self::ProtocolNone => "protocol_none",
1918 Self::NotConfigured => "not_configured",
1919 Self::AlreadySwapping => "already_swapping",
1920 }
1921 }
1922}
1923
1924#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1927pub enum SwapFailureArm {
1928 SpawnFailed,
1930 NeverRegistered,
1932 NeverReady,
1934 CandidateExited,
1936 CandidateUnhealthy,
1938 Interrupted,
1942 CutoverLost,
1947}
1948
1949impl SwapFailureArm {
1950 pub fn as_str(self) -> &'static str {
1951 match self {
1952 Self::SpawnFailed => "spawn_failed",
1953 Self::NeverRegistered => "never_registered",
1954 Self::NeverReady => "never_ready",
1955 Self::CandidateExited => "candidate_exited",
1956 Self::CandidateUnhealthy => "candidate_unhealthy",
1957 Self::Interrupted => "interrupted",
1958 Self::CutoverLost => "cutover_lost",
1959 }
1960 }
1961}
1962
1963impl SuperviseError {
1964 pub(crate) fn is_config_gate_error(&self) -> bool {
1965 match self {
1966 Self::ConfigHeld { .. } => true,
1967 Self::Spawn { source, .. } => source
1968 .get_ref()
1969 .is_some_and(|cause| cause.is::<crate::config_gate::GateError>()),
1970 _ => false,
1971 }
1972 }
1973}
1974
1975impl fmt::Display for SuperviseError {
1976 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1977 match self {
1978 Self::ConfigHeld { module_id, code, detail } => write!(f, "{code}: module '{module_id}' held: {detail}"),
1979 Self::ConfigDeliveryDeferred { module_id } => write!(f, "config_gated: module '{module_id}' is waiting for its exited delivery target's failure record"),
1980 Self::InvalidSpec { reason } => write!(f, "invalid module spec: {reason}"),
1981 Self::Spawn {
1982 program,
1983 source,
1984 cgroup_path: Some(cgroup_path),
1985 } => write!(
1986 f,
1987 "failed to place module in cgroup '{}' while spawning '{}': {source}",
1988 cgroup_path.display(),
1989 program.display()
1990 ),
1991 Self::Spawn {
1992 program,
1993 source,
1994 cgroup_path: None,
1995 } => write!(
1996 f,
1997 "failed to spawn module '{}': {source}",
1998 program.display()
1999 ),
2000 Self::Cgroup { module_id, source } => {
2001 write!(
2002 f,
2003 "failed to prepare cgroup for module '{module_id}': {source}"
2004 )
2005 }
2006 Self::LaunchNonce { reason } => {
2007 write!(
2008 f,
2009 "failed to generate reserved-module launch nonce: {reason}"
2010 )
2011 }
2012 Self::Wait { module_id, source } => {
2013 write!(f, "failed to wait for module '{module_id}': {source}")
2014 }
2015 Self::Kill { module_id, source } => {
2016 write!(f, "failed to kill module '{module_id}': {source}")
2017 }
2018 Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
2019 Self::Registry(err) => write!(f, "registry error: {err}"),
2020 Self::ReloadUnavailable { module_id, reason } => {
2021 write!(f, "reload unavailable for module '{module_id}': {reason}")
2022 }
2023 Self::Disabled { module_id } => {
2024 write!(
2025 f,
2026 "module '{module_id}' is disabled; enable it before restart or reload"
2027 )
2028 }
2029 Self::ReloadFailed { module_id, reason } => {
2030 write!(f, "reload failed for module '{module_id}': {reason}")
2031 }
2032 Self::RegistrationStillActive { module_id, waited } => write!(
2033 f,
2034 "module '{module_id}' registration remained active after waiting {waited:?}"
2035 ),
2036 Self::StatePoisoned { module_id } => match module_id {
2037 Some(module_id) => {
2038 write!(f, "supervisor state for module '{module_id}' was poisoned")
2039 }
2040 None => write!(f, "supervisor state was poisoned"),
2041 },
2042 Self::CommandClosed { module_id } => {
2043 write!(
2044 f,
2045 "supervisor command channel for module '{module_id}' is closed"
2046 )
2047 }
2048 Self::UpgradeInProgress => f.write_str("daemon upgrade is in progress"),
2049 Self::SwapInProgress { module_id } => write!(
2050 f,
2051 "module '{module_id}' is being swapped; retry once the swap has cut over or failed, or stop the module to abort the swap"
2052 ),
2053 Self::SwapRefused { module_id, reason } => match reason {
2054 SwapRefusal::OverlapExclusive => write!(
2055 f,
2056 "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"
2057 ),
2058 SwapRefusal::NotRegistered => write!(
2059 f,
2060 "module '{module_id}' is not registered, so there is no serving process to keep while a replacement warms; use a plain restart"
2061 ),
2062 SwapRefusal::ProtocolNone => write!(
2063 f,
2064 "module '{module_id}' is protocol: \"none\" and never registers, so a swap could never see its replacement become ready; use a plain restart"
2065 ),
2066 SwapRefusal::NotConfigured => write!(
2067 f,
2068 "module '{module_id}' cannot be swapped: the supervisor was built without the forwarding table or shared handle a swap needs"
2069 ),
2070 SwapRefusal::AlreadySwapping => {
2071 write!(f, "module '{module_id}' is already being swapped")
2072 }
2073 },
2074 Self::SwapFailed {
2075 module_id,
2076 arm,
2077 detail,
2078 ..
2079 } => write!(
2080 f,
2081 "swap of module '{module_id}' failed ({}): {detail}; the running process was left serving",
2082 arm.as_str()
2083 ),
2084 }
2085 }
2086}
2087
2088impl Error for SuperviseError {
2089 fn source(&self) -> Option<&(dyn Error + 'static)> {
2090 match self {
2091 Self::Spawn { source, .. }
2092 | Self::Cgroup { source, .. }
2093 | Self::Wait { source, .. }
2094 | Self::Kill { source, .. } => Some(source),
2095 Self::Forwarding(err) => Some(err),
2096 Self::Registry(err) => Some(err),
2097 Self::LaunchNonce { .. }
2098 | Self::ConfigDeliveryDeferred { .. }
2099 | Self::ConfigHeld { .. }
2100 | Self::InvalidSpec { .. }
2101 | Self::ReloadUnavailable { .. }
2102 | Self::Disabled { .. }
2103 | Self::ReloadFailed { .. }
2104 | Self::RegistrationStillActive { .. }
2105 | Self::StatePoisoned { .. }
2106 | Self::CommandClosed { .. }
2107 | Self::SwapInProgress { .. }
2108 | Self::UpgradeInProgress
2109 | Self::SwapRefused { .. }
2110 | Self::SwapFailed { .. } => None,
2111 }
2112 }
2113}
2114
2115fn unix_ms_now() -> u64 {
2116 SystemTime::now()
2117 .duration_since(UNIX_EPOCH)
2118 .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
2119 .unwrap_or(0)
2120}
2121
2122fn update_snapshot(
2123 snapshot: &SharedSnapshot,
2124 module_id: Option<&str>,
2125 update: impl FnOnce(&mut SupervisorSnapshot),
2126) -> Result<(), SuperviseError> {
2127 let mut state = lock_snapshot(snapshot).map_err(|_| SuperviseError::StatePoisoned {
2128 module_id: module_id.map(ToOwned::to_owned),
2129 })?;
2130 update(&mut state);
2131 Ok(())
2132}
2133
2134const SLOW_SNAPSHOT_LOCK_THRESHOLD: Duration = Duration::from_millis(250);
2135
2136fn lock_snapshot_for_control<'a>(
2137 snapshot: &'a SharedSnapshot,
2138 module_id: &str,
2139 caller: &'static str,
2140) -> Result<std::sync::MutexGuard<'a, SupervisorSnapshot>, SuperviseError> {
2141 let started_at = Instant::now();
2142 let guard = lock_snapshot(snapshot)?;
2143 let waited = started_at.elapsed();
2144 if waited >= SLOW_SNAPSHOT_LOCK_THRESHOLD {
2145 warn!(
2146 module_id = %module_id,
2147 waited_ms = waited.as_millis() as u64,
2148 caller = %caller,
2149 "slow snapshot lock"
2150 );
2151 }
2152 Ok(guard)
2153}
2154
2155fn lock_snapshot(
2156 snapshot: &SharedSnapshot,
2157) -> Result<std::sync::MutexGuard<'_, SupervisorSnapshot>, SuperviseError> {
2158 let guard = match snapshot.try_lock() {
2159 Ok(guard) => return Ok(guard),
2160 Err(TryLockError::Poisoned(guard)) => Err(guard),
2161 Err(TryLockError::WouldBlock) => {
2162 if tokio::runtime::Handle::try_current().is_ok_and(|handle| {
2165 handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread
2166 }) {
2167 tokio::task::block_in_place(|| snapshot.lock())
2168 } else {
2169 snapshot.lock()
2170 }
2171 }
2172 };
2173 guard.map_err(|_| SuperviseError::StatePoisoned { module_id: None })
2174}
2175
2176#[cfg(all(test, unix))]
2177mod restart_ordering_tests;
2178
2179#[cfg(all(test, target_os = "macos"))]
2180#[path = "supervise/suspended_spawn_tests.rs"]
2181mod suspended_spawn_tests;
2182
2183#[cfg(all(test, target_os = "linux"))]
2184#[path = "supervise/cgroup_reap_tests.rs"]
2185mod cgroup_reap_tests;
2186
2187#[cfg(test)]
2188#[path = "supervise/supervise_tests.rs"]
2189mod tests;
2190
2191#[cfg(test)]
2192#[path = "supervise/spawn_record_tests.rs"]
2193mod spawn_record_tests;
2194
2195#[cfg(all(test, target_os = "linux"))]
2196#[path = "supervise/spawn_image_tests.rs"]
2197mod spawn_image_tests;
2198
2199#[cfg(test)]
2200#[path = "supervise/slot_registration_wait_tests.rs"]
2201mod slot_registration_wait_tests;
2202
2203#[cfg(test)]
2204#[path = "supervise/terminal_history_tests.rs"]
2205mod terminal_history_tests;
2206
2207#[cfg(all(test, unix))]
2208#[path = "supervise/health_event_tests.rs"]
2209mod health_event_tests;
2210
2211#[cfg(test)]
2212#[path = "supervise/drain_busy_reprobe_tests.rs"]
2213mod drain_busy_reprobe_tests;
2214
2215#[cfg(test)]
2216#[path = "supervise/health_evidence_tests.rs"]
2217mod health_evidence_tests;
2218
2219#[cfg(test)]
2220#[path = "supervise/health_tombstone_tests.rs"]
2221mod health_tombstone_tests;
2222
2223#[cfg(test)]
2224#[path = "supervise/child_env_tests.rs"]
2225mod child_env_tests;
2226
2227#[cfg(test)]
2228#[path = "supervise/jitter_tests.rs"]
2229mod jitter_tests;
2230
2231#[cfg(all(test, target_os = "linux"))]
2232#[path = "supervise/cgroup_placement_tests.rs"]
2233mod cgroup_placement_tests;
2234
2235#[cfg(test)]
2236#[path = "supervise/spawn_subscriber_lag_tests.rs"]
2237mod spawn_subscriber_lag_tests;
2238
2239#[cfg(test)]
2240#[path = "supervise/terminal_history_read_concurrency_tests.rs"]
2241mod terminal_history_read_concurrency_tests;
2242
2243#[cfg(test)]
2248#[path = "supervise/stderr_settle_tests.rs"]
2249mod stderr_settle_tests;
2250
2251#[cfg(all(test, windows))]
2265#[path = "supervise/job_containment_tests.rs"]
2266mod job_containment_tests;
2267
2268#[cfg(test)]
2269#[path = "supervise/privacy_trampoline_configuration_tests.rs"]
2270mod privacy_trampoline_configuration_tests;
2271
2272#[cfg(test)]
2273#[path = "supervise/privacy_exec_boundary_tests.rs"]
2274mod privacy_exec_boundary_tests;
2275
2276#[cfg(all(test, unix))]
2280#[path = "supervise/launch_nonce_descriptor_tests.rs"]
2281mod launch_nonce_descriptor_tests;
2282
2283#[cfg(all(test, target_os = "linux"))]
2284#[path = "supervise/cgroup_containment_tests.rs"]
2285mod cgroup_containment_tests;
2286
2287#[cfg(all(test, unix))]
2290#[path = "supervise/record_write_stall_tests.rs"]
2291mod record_write_stall_tests;
2292
2293#[cfg(all(test, unix))]
2294#[path = "supervise/retained_status_tests.rs"]
2295mod retained_status_tests;