1use std::{
12 collections::{BTreeMap, BTreeSet},
13 path::{Path, PathBuf},
14 sync::atomic::Ordering,
15 time::Duration,
16};
17
18use sha2::{Digest, Sha256};
19use subc_control::{
20 ops, BusyGaugeReading, LaunchSpecAgreement, RescanExpect, RescanModuleAction,
21 RescanModuleActionKind, StagedGeneration, SupervisorRescanResult, CONFIG_CHANGED_SINCE_PREVIEW,
22 RESCAN_CANDIDATE_MAX_BYTES, RESCAN_CANDIDATE_PREVIEW_CAPABILITY, RESCAN_CANDIDATE_TOO_LARGE,
23};
24
25use super::*;
26use crate::{
27 daemon_config::{ActivityConfig, ConfiguredModule, DaemonConfig},
28 router::{RouteCtx, RouterError},
29 supervise::{ModuleSpec, SupervisedModule},
30 Frame, HealthConfig,
31};
32
33#[cfg(test)]
34mod tests;
35
36#[derive(Clone)]
38pub(super) enum RescanMode {
39 Execute,
41 Preview,
44 Candidate(String),
47 Checked(RescanExpect),
50}
51
52const CONFIG_READ_DEADLINE: Duration = Duration::from_secs(5);
53static CONFIG_READ_SLOTS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4);
56
57pub(super) struct RescanInput {
58 pub(super) config: Option<(DaemonConfig, ActivityConfig)>,
59 pub(super) approved_preview: Option<DaemonConfig>,
60 pub(super) guard: tokio::sync::OwnedMutexGuard<()>,
61}
62
63pub(super) enum RescanInputError {
64 Lifecycle(crate::supervise::live_upgrade::LifecycleRefusal),
65 Config(&'static str, String),
66 Gate(crate::config_gate::GateError),
67}
68
69impl RescanInputError {
70 pub(super) fn into_frame(self, request: &Frame) -> Result<Frame, RouterError> {
71 match self {
72 Self::Config(code, message) => control_error_frame(request, code, message),
73 Self::Gate(error) => config_gate::config_error_frame(request, error),
74 Self::Lifecycle(refusal) => super::control_error_body_frame(request, refusal.body()),
75 }
76 }
77}
78
79impl RescanMode {
80 pub(super) fn previews(&self) -> bool {
81 matches!(self, Self::Preview | Self::Candidate(_))
82 }
83}
84
85pub(super) struct CurrentModule {
87 module: SupervisedModule,
88 spec: ModuleSpec,
89 health: HealthConfig,
90 enabled: bool,
91 drain_timeout: Duration,
92 staged_drain_timeout: Option<Duration>,
93}
94
95impl CurrentModule {
96 fn drain_changed(&self, next: Duration) -> bool {
97 self.drain_timeout != next
100 || self
101 .staged_drain_timeout
102 .is_some_and(|staged| staged != next)
103 }
104}
105
106#[derive(Debug, Default)]
107pub(super) struct ModuleEntries {
108 registration_channels: BTreeMap<String, bool>,
109 configured: BTreeMap<String, ConfiguredModule>,
110}
111
112impl ModuleEntries {
113 pub(super) fn reserved(&self, module_id: &str) -> bool {
114 self.configured
115 .get(module_id)
116 .is_some_and(|entry| entry.reserved)
117 }
118 pub(super) fn seed(&mut self, modules: &[ConfiguredModule]) {
119 self.configured = modules
120 .iter()
121 .cloned()
122 .map(|m| (m.module_id.clone(), m))
123 .collect();
124 self.registration_channels = modules
125 .iter()
126 .map(|m| (m.module_id.clone(), m.registration_channel))
127 .collect();
128 }
129
130 pub(super) fn record(
131 &mut self,
132 configured: &BTreeMap<String, ConfiguredModule>,
133 added: &[String],
134 removed: &[String],
135 ) {
136 for id in removed {
137 self.registration_channels.remove(id);
138 }
139 for id in added {
140 self.registration_channels
141 .insert(id.clone(), configured[id].registration_channel);
142 }
143 self.configured = configured.clone();
144 }
145}
146
147pub(super) fn entry_pending_fields(
148 current: &ConfiguredModule,
149 next: &ConfiguredModule,
150 applies_configuration: bool,
151) -> Vec<subc_control::SupervisorPendingField> {
152 use subc_control::{PendingModuleApply as Apply, SupervisorPendingField};
153 let mut fields = Vec::new();
154 let mut add = |field: &str, applies, value| {
155 fields.push(SupervisorPendingField {
156 field: field.to_owned(),
157 applies,
158 value: Some(value),
159 })
160 };
161 if current.register_timeout != next.register_timeout {
162 add(
163 "register_timeout_s",
164 Apply::NextSupervision,
165 serde_json::json!(next.register_timeout.as_secs()),
166 );
167 }
168 if current.restart != next.restart {
169 add(
170 "restart",
171 Apply::NextSupervision,
172 serde_json::json!({
173 "max_restarts": next.restart.max_restarts,
174 "window_secs": next.restart.window.as_secs(),
175 "backoff_ms": next.restart.backoff.as_millis() as u64,
176 "max_backoff_ms": next.restart.max_backoff.as_millis() as u64,
177 }),
178 );
179 }
180 let relay = |module: &ConfiguredModule| {
181 module
182 .route_bind_relay_timeout_ms
183 .map(Duration::from_millis)
184 .unwrap_or(crate::DEFAULT_ROUTE_BIND_RELAY_TIMEOUT)
185 };
186 if relay(current) != relay(next) {
187 add(
188 "route_bind_relay_timeout_ms",
189 Apply::DaemonRestart,
190 serde_json::json!(relay(next).as_millis() as u64),
191 );
192 }
193 if current.registration_channel != next.registration_channel {
194 add(
195 "registration_channel",
196 Apply::ConfigGate,
197 serde_json::json!(next.registration_channel),
198 );
199 }
200 if !applies_configuration {
201 let default = crate::supervise::DEFAULT_DRAIN_TIMEOUT;
202 fields.extend(pending_drain_timeout(
203 configured_drain_timeout(current, default),
204 configured_drain_timeout(next, default),
205 ));
206 }
207 fields
208}
209
210fn configured_drain_timeout(entry: &ConfiguredModule, default: Duration) -> Duration {
211 entry
212 .drain_timeout_ms
213 .map_or(default, Duration::from_millis)
214}
215
216fn pending_drain_timeout(
217 effective: Duration,
218 configured: Duration,
219) -> Option<subc_control::SupervisorPendingField> {
220 (effective != configured).then(|| subc_control::SupervisorPendingField {
221 field: "drain_timeout_ms".to_owned(),
222 applies: subc_control::PendingModuleApply::WithNextLaunchOrHealthChange,
223 value: Some(serde_json::json!(duration_ms(configured))),
224 })
225}
226
227impl ControlHandler {
228 pub(super) fn registration_channel_in_force(
229 declaration: Option<&str>,
230 configured: Option<bool>,
231 ) -> Option<bool> {
232 match declaration {
233 Some("declared") => Some(true),
234 Some("undeclared") => Some(false),
235 _ => configured,
238 }
239 }
240
241 pub(super) fn pending_module_fields(
242 &self,
243 module: &SupervisedModule,
244 proposed: Option<&ConfiguredModule>,
245 applies_configuration: bool,
246 approved_registration_channel: Option<bool>,
247 publication: Option<&crate::config_gate::runtime::Published>,
248 ) -> Result<Vec<subc_control::SupervisorPendingField>, String> {
249 let id = module.module_id();
250 let (recorded, registration_channel) = self
251 .rescan
252 .as_ref()
253 .map(|context| {
254 let entries = context
255 .module_entries
256 .lock()
257 .unwrap_or_else(|e| e.into_inner());
258 (
259 entries.configured.get(id).cloned(),
260 entries
261 .registration_channels
262 .get(id)
263 .copied()
264 .unwrap_or(false),
265 )
266 })
267 .unwrap_or_default();
268 let Some(mut next) = proposed.cloned().or(recorded) else {
269 return Ok(Vec::new());
270 };
271 if let Some(context) = &self.rescan {
272 next.drain_timeout_ms = Some(duration_ms(configured_drain_timeout(
273 &next,
274 context.supervisor.default_drain_timeout(),
275 )));
276 }
277 let status = module.status().map_err(|e| e.to_string())?;
278 let mut current = next.clone();
279 current.register_timeout = module
280 .configured_register_timeout()
281 .map_err(|e| e.to_string())?;
282 current.restart = crate::supervise::RestartPolicy {
283 max_restarts: status.max_restarts,
284 window: status.restart_window,
285 backoff: status.restart_backoff,
286 max_backoff: status.restart_max_backoff,
287 };
288 current.drain_timeout_ms = Some(status.drain_timeout.as_millis() as u64);
289 current.route_bind_relay_timeout_ms =
290 Some(self.route_bind_relay_timeout_for(id).as_millis() as u64);
291 current.registration_channel =
292 approved_registration_channel.unwrap_or(registration_channel);
293 let mut fields = entry_pending_fields(¤t, &next, applies_configuration);
294 let unstamped = match &self.config_runtime {
299 None => true,
300 Some(_) => publication.is_some_and(|view| {
301 matches!(
302 view.approved_daemon,
303 crate::config_gate::runtime::ApprovedDaemonView::NotStamped
304 )
305 }),
306 };
307 if unstamped {
308 fields.retain(|field| field.field != "registration_channel");
309 }
310 Ok(fields)
311 }
312}
313
314pub(super) struct RescanPlan {
317 pub(super) current: BTreeMap<String, CurrentModule>,
318 pub(super) configured: BTreeMap<String, ConfiguredModule>,
319 pub(super) added: Vec<String>,
320 pub(super) removed: Vec<String>,
321 pub(super) changed_pending_reload: Vec<String>,
324 pub(super) changed_pending: Vec<subc_control::SupervisorPendingModule>,
325 pub(super) configuration_changes: BTreeSet<String>,
327 pub(super) enabled_changes: BTreeSet<String>,
328 pub(super) unchanged: u32,
329}
330
331impl RescanPlan {
332 pub(super) fn preview_result(&self) -> SupervisorRescanResult {
333 SupervisorRescanResult {
334 added: self.added.clone(),
335 removed: self.removed.clone(),
336 changed_pending_reload: self.changed_pending_reload.clone(),
337 changed_pending: self.changed_pending.clone(),
338 enabled_changes: self.enabled_changes.iter().cloned().collect(),
339 unchanged: self.unchanged,
340 preview: true,
341 restart_required: Vec::new(),
345 capability_warnings: Vec::new(),
346 module_actions: Vec::new(),
347 earlier_pending: Vec::new(),
348 expect: None,
349 }
350 }
351}
352
353pub(super) fn reported_config_path(path: &Path) -> Option<PathBuf> {
359 (path.is_absolute() && path.to_str().is_some()).then(|| path.to_path_buf())
360}
361
362fn sha256_hex(bytes: &[u8]) -> String {
363 Sha256::digest(bytes)
364 .iter()
365 .map(|byte| format!("{byte:02x}"))
366 .collect()
367}
368
369fn duration_ms(duration: Duration) -> u64 {
370 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
371}
372
373fn changed_parts(
376 current_spec: &ModuleSpec,
377 current_health: &HealthConfig,
378 drain_changed: bool,
379 configured: &ConfiguredModule,
380) -> Vec<String> {
381 let next = configured.module_spec();
382 [
383 ("program", current_spec.program != next.program),
384 ("arguments", current_spec.args != next.args),
385 ("environment", current_spec.env != next.env),
386 ("protocol", current_spec.protocol != next.protocol),
387 ("reserved", current_spec.reserved != next.reserved),
388 (
389 "reserved_prefixes",
390 current_spec.reserved_prefixes != next.reserved_prefixes,
391 ),
392 ("overlap", current_spec.overlap != next.overlap),
393 (
394 "carry_containment",
395 current_spec.carry_containment != next.carry_containment,
396 ),
397 ("health", *current_health != configured.health),
398 ("drain_timeout_ms", drain_changed),
399 ]
400 .into_iter()
401 .filter(|(_, changed)| *changed)
402 .map(|(part, _)| part.to_string())
403 .collect()
404}
405
406impl ControlHandler {
407 pub(super) fn describe_capabilities(&self) -> Vec<String> {
412 let mut capabilities = self.capabilities_with_settings();
413 if self.rescan.is_some() {
414 capabilities.push(RESCAN_CANDIDATE_PREVIEW_CAPABILITY.to_string());
415 }
416 capabilities.push(super::server_describe::CAP_HUB_COMMANDS.to_string());
417 capabilities
418 }
419
420 fn staged_generation(&self, context: &SupervisorRescanContext) -> StagedGeneration {
421 StagedGeneration {
422 incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
423 counter: context.generation.load(Ordering::SeqCst),
424 }
425 }
426
427 pub(super) async fn handle_supervisor_rescan_checked(
428 &self,
429 ctx: &RouteCtx,
430 frame: Frame,
431 preview: bool,
432 candidate: Option<String>,
433 expect: Option<RescanExpect>,
434 ) -> Result<Vec<Frame>, RouterError> {
435 let corr = frame.header.corr;
436 let mode = match (preview, candidate, expect) {
437 (true, Some(candidate), None) => {
438 if candidate.len() > RESCAN_CANDIDATE_MAX_BYTES {
439 return Ok(vec![control_error_frame(
440 &frame,
441 RESCAN_CANDIDATE_TOO_LARGE,
442 format!(
443 "the candidate config is {} bytes; a preview accepts at most {RESCAN_CANDIDATE_MAX_BYTES}",
444 candidate.len()
445 ),
446 )?]);
447 }
448 RescanMode::Candidate(candidate)
449 }
450 (false, None, Some(expect)) => {
451 self.log_supervisor_request_received(
452 ctx,
453 corr,
454 ops::SUPERVISOR_RESCAN_CHECKED,
455 None,
456 None,
457 )?;
458 RescanMode::Checked(expect)
459 }
460 _ => {
461 return Ok(vec![control_error_frame(
462 &frame,
463 "invalid_control_body",
464 "supervisor.rescan_checked takes either preview: true with a candidate and \
465 no expect, or preview: false with an expect and no candidate",
466 )?]);
467 }
468 };
469 let requester = self.supervisor_requester(ctx, corr)?;
470 self.handle_supervisor_rescan(frame, mode, requester).await
471 }
472
473 pub(super) async fn rescan_input(
478 &self,
479 mode: &RescanMode,
480 context: &SupervisorRescanContext,
481 ) -> Result<RescanInput, RescanInputError> {
482 use tokio::time::{timeout_at, Instant};
483 use RescanInputError::Config;
484
485 if let Some(refusal) = self.supervisor.lifecycle_refusal(None) {
486 return Err(RescanInputError::Lifecycle(refusal));
487 }
488
489 let staged = self.staged_generation(context);
490 let (config, approved_preview) = if matches!(mode, RescanMode::Candidate(_)) {
491 (Self::read_rescan_config(mode, &context.config_path)?, None)
492 } else {
493 let deadline = Instant::now() + CONFIG_READ_DEADLINE;
494 let timed_out = || {
495 Config(
496 "rescan_config_read_timeout",
497 format!(
498 "supervisor rescan timed out reading daemon config at {}; nothing was applied",
499 context.config_path.display()
500 ),
501 )
502 };
503 let permit = timeout_at(deadline, CONFIG_READ_SLOTS.acquire())
504 .await
505 .map_err(|_| timed_out())?
506 .expect("rescan read slots never close");
507 if Instant::now() >= deadline {
508 return Err(timed_out());
509 }
510 let path = context.config_path.clone();
511 let owner = if matches!(mode, RescanMode::Preview) {
512 self.config_runtime.clone()
513 } else {
514 None
515 };
516 let mode = mode.clone();
517 let (send, recv) = tokio::sync::oneshot::channel();
518 std::thread::Builder::new()
519 .name("rescan-config-read".into())
520 .spawn(move || {
521 let _permit = permit;
522 let result = (|| {
523 let config = Self::read_rescan_config(&mode, &path)?;
524 let approved = if let Some(owner) = owner.filter(|_| !send.is_closed()) {
528 owner
529 .observe_file_proposal()
530 .map_err(RescanInputError::Gate)?;
531 owner
532 .approved_daemon_configuration()
533 .map_err(RescanInputError::Gate)?
534 } else {
535 None
536 };
537 Ok((config, approved))
538 })();
539 let _ = send.send(result);
540 })
541 .map_err(|error| {
542 Config(
543 "rescan_failed",
544 format!("could not start supervisor rescan config read: {error}"),
545 )
546 })?;
547 let result = timeout_at(deadline, recv).await.map_err(|_| timed_out())?;
548 if Instant::now() >= deadline {
551 return Err(timed_out());
552 }
553 result.map_err(|error| {
554 Config(
555 "rescan_failed",
556 format!("supervisor rescan config reader stopped: {error}"),
557 )
558 })??
559 };
560
561 let guard = self
562 .supervisor
563 .lifecycle_operation(None)
564 .await
565 .map_err(RescanInputError::Lifecycle)?;
566 let current = self.staged_generation(context);
567 let changed = match mode {
568 RescanMode::Candidate(_) => None,
569 RescanMode::Checked(expect) if current != expect.staged_generation => Some((
570 CONFIG_CHANGED_SINCE_PREVIEW,
571 &expect.staged_generation,
572 "after the preview",
573 )),
574 _ if current != staged => {
575 Some(("rescan_failed", &staged, "while reading daemon config"))
576 }
577 _ => None,
578 };
579 if let Some((code, before, reason)) = changed {
580 return Err(Config(code, format!(
581 "the daemon's staged configuration changed {reason} (was {}:{}, now {}:{}); nothing was applied",
582 before.incarnation, before.counter, current.incarnation, current.counter,
583 )));
584 }
585 Ok(RescanInput {
586 config,
587 approved_preview,
588 guard,
589 })
590 }
591
592 fn read_rescan_config(
593 mode: &RescanMode,
594 path: &Path,
595 ) -> Result<Option<(DaemonConfig, ActivityConfig)>, RescanInputError> {
596 let rejected = |err: crate::daemon_config::DaemonConfigError| {
597 RescanInputError::Config(
598 "invalid_daemon_config",
599 format!("supervisor rescan rejected daemon config: {err}"),
600 )
601 };
602 match mode {
603 RescanMode::Execute | RescanMode::Preview => {
604 crate::daemon_config::load_with_activity(path).map_err(rejected)
605 }
606 RescanMode::Candidate(candidate) => {
607 crate::daemon_config::parse_with_activity(candidate, path)
608 .map(Some)
609 .map_err(rejected)
610 }
611 RescanMode::Checked(expect) => {
612 let doc = Self::checked_config_doc(path, expect)?;
613 crate::daemon_config::parse_with_activity(&doc, path)
614 .map(Some)
615 .map_err(rejected)
616 }
617 }
618 }
619
620 fn checked_config_doc(path: &Path, expect: &RescanExpect) -> Result<String, RescanInputError> {
623 use RescanInputError::Config;
624 let bytes = match std::fs::read(path) {
625 Ok(bytes) => bytes,
626 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
627 return Err(Config(
628 CONFIG_CHANGED_SINCE_PREVIEW,
629 format!(
630 "daemon config not found at {}; nothing was applied",
631 path.display()
632 ),
633 ));
634 }
635 Err(err) => {
636 return Err(Config(
637 "invalid_daemon_config",
638 format!(
639 "supervisor rescan could not read daemon config at {}: {err}",
640 path.display()
641 ),
642 ));
643 }
644 };
645 if !sha256_hex(&bytes).eq_ignore_ascii_case(&expect.config_sha256) {
646 return Err(Config(
647 CONFIG_CHANGED_SINCE_PREVIEW,
648 format!(
649 "daemon config at {} is not the text that was previewed; nothing was applied",
650 path.display(),
651 ),
652 ));
653 }
654 String::from_utf8(bytes).map_err(|err| {
657 Config(
658 "invalid_daemon_config",
659 format!("daemon config at {} is not UTF-8: {err}", path.display()),
660 )
661 })
662 }
663
664 pub(super) fn preview_candidate(
669 &self,
670 context: &SupervisorRescanContext,
671 modules: Vec<ConfiguredModule>,
672 candidate: &str,
673 ) -> Result<SupervisorRescanResult, String> {
674 let default_drain_timeout = context.supervisor.default_drain_timeout();
675 let plan = self.plan_rescan(modules, default_drain_timeout)?;
676 let mut result = plan.preview_result();
677 let module_ids = plan
678 .current
679 .keys()
680 .chain(plan.configured.keys())
681 .collect::<BTreeSet<_>>();
682 let mut drained = BTreeSet::new();
683 for module_id in module_ids {
684 let current = plan.current.get(module_id);
685 let configured = plan.configured.get(module_id);
686 let (action, changed) = match (current, configured) {
687 (None, Some(configured)) if configured.enabled => {
688 (RescanModuleActionKind::Start, Vec::new())
689 }
690 (Some(current), None) if current.enabled => {
691 (RescanModuleActionKind::Stop, Vec::new())
692 }
693 (Some(current), Some(configured)) if current.enabled != configured.enabled => {
694 if configured.enabled {
695 (RescanModuleActionKind::Start, Vec::new())
696 } else {
697 (RescanModuleActionKind::Stop, Vec::new())
698 }
699 }
700 (Some(current), Some(configured))
701 if plan.configuration_changes.contains(module_id) =>
702 {
703 let changed = changed_parts(
704 ¤t.spec,
705 ¤t.health,
706 current.drain_changed(configured_drain_timeout(
707 configured,
708 default_drain_timeout,
709 )),
710 configured,
711 );
712 if current.enabled && plan.changed_pending_reload.contains(module_id) {
717 (RescanModuleActionKind::Restart, changed)
718 } else {
719 (RescanModuleActionKind::Reload, changed)
720 }
721 }
722 _ => continue,
723 };
724 let mut entry = RescanModuleAction {
725 module_id: module_id.clone(),
726 action,
727 changed,
728 drain_timeout_ms: None,
729 busy_gauges: Vec::new(),
730 };
731 if matches!(
732 entry.action,
733 RescanModuleActionKind::Restart | RescanModuleActionKind::Stop
734 ) {
735 if let Some(current) = current {
736 let status = current.module.status().map_err(|err| {
737 format!("failed to read status for module_id '{module_id}': {err}")
738 })?;
739 entry.drain_timeout_ms = Some(match configured {
743 Some(configured) if plan.configuration_changes.contains(module_id) => {
744 duration_ms(configured_drain_timeout(configured, default_drain_timeout))
745 }
746 _ => duration_ms(status.drain_timeout),
747 });
748 let metrics = status
749 .health
750 .metrics
751 .as_ref()
752 .and_then(serde_json::Value::as_object);
753 entry.busy_gauges =
754 crate::supervise::declared_busy_gauges(&self.registry, module_id)
755 .map_err(|err| {
756 format!(
757 "failed to read busy gauges for module_id '{module_id}': {err}"
758 )
759 })?
760 .into_iter()
761 .map(|gauge| BusyGaugeReading {
762 value: metrics.and_then(|metrics| metrics.get(&gauge)).cloned(),
763 gauge,
764 })
765 .collect();
766 }
767 drained.insert(module_id.clone());
768 }
769 result.module_actions.push(entry);
770 }
771 for (module_id, current) in &plan.current {
772 if drained.contains(module_id) {
773 continue;
774 }
775 let status = current.module.status().map_err(|err| {
776 format!("failed to read status for module_id '{module_id}': {err}")
777 })?;
778 if launch_spec_agreement(
779 ¤t.spec,
780 status.process_alive,
781 status.launch_spec_digest.as_ref(),
782 ) == LaunchSpecAgreement::Mismatch
783 {
784 result.earlier_pending.push(module_id.clone());
785 }
786 }
787 result.expect = Some(RescanExpect {
788 config_sha256: sha256_hex(candidate.as_bytes()),
789 staged_generation: self.staged_generation(context),
790 });
791 Ok(result)
792 }
793}
794
795#[cfg(all(test, unix))]
796#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
797async fn stalled_config_read_times_out_without_holding_operation_lock() {
798 use crate::{Registry, RestartPolicy, Supervisor, SupervisorHandle};
799 use cortexkit_test_support::ScratchDir;
800 use std::io::Write;
801 use std::sync::{mpsc, Arc};
802 use subc_protocol::{FrameType, Principal};
803
804 let dir = ScratchDir::new("rescan-stalled-file");
805 let path = dir.join("subc.jsonc");
806 assert!(std::process::Command::new("mkfifo")
807 .arg(&path)
808 .status()
809 .unwrap()
810 .success());
811 let registry = Arc::new(Registry::default());
812 let handle = SupervisorHandle::new();
813 let supervisor =
814 Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
815 let handler = Arc::new(
816 ControlHandler::new(registry)
817 .with_supervisor(handle.clone())
818 .with_supervisor_rescan(supervisor, &path, None),
819 );
820 let (opened, is_open) = tokio::sync::oneshot::channel();
821 let (release, released) = mpsc::channel();
822 let feeder = std::thread::spawn(move || {
823 let mut fifo = std::fs::OpenOptions::new().write(true).open(path).unwrap();
824 opened.send(()).unwrap();
825 released.recv_timeout(Duration::from_secs(10)).unwrap();
826 let _ = fifo.write_all(br#"{"version":1,"modules":{"never-applied":{"program":"/bin/true","protocol":"none","enabled":false}}}"#);
827 });
828 let request = tokio::spawn({
829 let handler = Arc::clone(&handler);
830 async move {
831 let frame = Frame::build(
832 FrameType::Request,
833 super::control_flags(),
834 0,
835 0,
836 1,
837 Vec::new(),
838 )
839 .unwrap();
840 handler
841 .handle_supervisor_rescan(frame, RescanMode::Execute, Principal::Direct)
842 .await
843 .unwrap()
844 .remove(0)
845 }
846 });
847 tokio::time::timeout(Duration::from_secs(2), is_open)
848 .await
849 .unwrap()
850 .unwrap();
851
852 let frame = Frame::build(
855 FrameType::Request,
856 super::control_flags(),
857 0,
858 0,
859 2,
860 Vec::new(),
861 )
862 .unwrap();
863 let restart = tokio::time::timeout(
864 Duration::from_secs(1),
865 handler.handle_supervisor_restart(frame, "missing".into(), None, Principal::Direct),
866 )
867 .await;
868 let mut request = request;
869 let reply = tokio::time::timeout(Duration::from_secs(6), &mut request).await;
870 release.send(()).unwrap();
871 feeder.join().unwrap();
872 let restart = restart
873 .expect("the rescan held the supervisor operation lock during its config read")
874 .unwrap()
875 .remove(0);
876 let body: serde_json::Value = serde_json::from_slice(&restart.body).unwrap();
877 assert_eq!(body["code"], "unknown_module");
878 let reply = reply
879 .expect("rescan did not answer before the config reader was released")
880 .unwrap();
881 assert_eq!(reply.header.ty, FrameType::Error);
882 let body: serde_json::Value = serde_json::from_slice(&reply.body).unwrap();
883 assert_eq!(body["code"], "rescan_config_read_timeout");
884 assert!(body["message"].as_str().unwrap().contains("subc.jsonc"));
885 assert!(handle.list().is_empty());
886 assert_eq!(
887 handler
888 .rescan
889 .as_ref()
890 .unwrap()
891 .generation
892 .load(Ordering::SeqCst),
893 0
894 );
895}
896
897#[derive(Debug, Clone)]
898pub(super) struct SupervisorRescanContext {
899 pub(super) supervisor: Supervisor,
900 pub(super) config_path: PathBuf,
901 pub(super) configured_port: Option<u16>,
902 pub(super) storage_config: Option<crate::daemon_config::StorageConfig>,
903 pub(super) admission_facts_carrier_module_id: Option<String>,
904 pub(super) admission_facts_targets: Option<Vec<String>>,
905 pub(super) scope_authority_owners: Vec<String>,
906 pub(super) flow_scope_authority_owners: Vec<String>,
907 federated_scope_owner: String,
908 pub(super) privileged_operator_prompt: PrivilegedOperatorPrompt,
909 generation: Arc<std::sync::atomic::AtomicU64>,
915 rescan_lock: Arc<tokio::sync::Mutex<()>>,
916 pub(super) module_entries: Arc<Mutex<rescan_checked::ModuleEntries>>,
917}
918
919impl ControlHandler {
920 pub fn with_supervisor_rescan(
921 mut self,
922 supervisor: Supervisor,
923 config_path: impl Into<PathBuf>,
924 configured_port: Option<u16>,
925 ) -> Self {
926 self.rescan = Some(SupervisorRescanContext {
927 supervisor,
928 config_path: config_path.into(),
929 configured_port,
930 storage_config: self.storage_config.clone(),
931 admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
932 admission_facts_targets: self.admission_facts_targets.clone(),
933 scope_authority_owners: self.scope_authority_owners.clone(),
934 flow_scope_authority_owners: self.flow_scope_authority_owners.clone(),
935 federated_scope_owner: self.federated_scope_owner.clone(),
936 privileged_operator_prompt: self.privileged_operator_prompt,
937 generation: Arc::default(),
938 rescan_lock: Arc::default(),
939 module_entries: Arc::default(),
940 });
941 self
942 }
943
944 pub(crate) fn with_supervisor_rescan_entries(
945 self,
946 modules: &[crate::daemon_config::ConfiguredModule],
947 ) -> Self {
948 if let Some(context) = &self.rescan {
949 let mut entries = context
950 .module_entries
951 .lock()
952 .unwrap_or_else(|e| e.into_inner());
953 entries.seed(modules);
954 }
955 self
956 }
957}
958
959impl ControlHandler {
960 pub(super) async fn handle_supervisor_rescan(
964 &self,
965 frame: Frame,
966 mode: RescanMode,
967 requester: Principal,
968 ) -> Result<Vec<Frame>, RouterError> {
969 let preview = mode.previews();
970 let Some(context) = self.rescan.clone() else {
971 return Ok(vec![control_error_frame(
972 &frame,
973 "rescan_unavailable",
974 "the daemon was not started with a reloadable config path".to_string(),
975 )?]);
976 };
977
978 let _rescan_guard = context.rescan_lock.lock().await;
979 let rescan_checked::RescanInput {
980 config: loaded,
981 approved_preview,
982 guard: _operation_guard,
983 } = match self.rescan_input(&mode, &context).await {
984 Ok(input) => input,
985 Err(error) => return Ok(vec![error.into_frame(&frame)?]),
986 };
987 let Some((config, activity_config)) = loaded else {
995 return Ok(vec![control_error_frame(
996 &frame,
997 "invalid_daemon_config",
998 format!(
999 "daemon config not found at {}; refusing to rescan (an absent config would \
1000 retire every supervised module)",
1001 context.config_path.display()
1002 ),
1003 )?]);
1004 };
1005 let (
1006 configured_port,
1007 storage_config,
1008 admission_facts_carrier_module_id,
1009 admission_facts_targets,
1010 scope_authority_owners,
1011 flow_scope_authority_owners,
1012 federated_scope_owner,
1013 privileged_operator_prompt,
1014 modules,
1015 reserved_capabilities,
1016 ) = (
1017 config.port,
1018 config.storage,
1019 config.admission_facts_carrier_module_id,
1020 config.admission_facts_targets,
1021 config.scope_authority_owners,
1022 config.flow_scope_authority_owners,
1023 config.federated_scope_owner,
1024 config.privileged_operator_prompt,
1025 config.modules,
1026 config.reserved_capabilities,
1027 );
1028
1029 let mut restart_required = Vec::new();
1038 for section in RestartRequiredSection::ALL {
1039 let changed = match section {
1040 RestartRequiredSection::Port => configured_port != context.configured_port,
1041 RestartRequiredSection::Storage => storage_config != context.storage_config,
1042 RestartRequiredSection::AdmissionFactsCarrierModuleId => {
1043 admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
1044 }
1045 RestartRequiredSection::AdmissionFactsTargets => {
1046 admission_facts_targets != context.admission_facts_targets
1047 }
1048 RestartRequiredSection::ScopeAuthorityOwners => {
1049 scope_authority_owners != context.scope_authority_owners
1050 }
1051 RestartRequiredSection::FlowScopeAuthorityOwners => {
1052 flow_scope_authority_owners != context.flow_scope_authority_owners
1053 }
1054 RestartRequiredSection::FederatedScopeOwner => {
1055 federated_scope_owner != context.federated_scope_owner
1056 }
1057 RestartRequiredSection::PrivilegedOperatorPrompt => {
1058 privileged_operator_prompt != context.privileged_operator_prompt
1059 }
1060 };
1061 if changed {
1062 restart_required.push(section.label().to_string());
1063 }
1064 }
1065 if !restart_required.is_empty() {
1066 warn!(
1067 config_path = %context.config_path.display(),
1068 sections = %restart_required.join(", "),
1069 "daemon config changed outside the modules section; restart the daemon to apply those changes"
1070 );
1071 }
1072
1073 for configured in &modules {
1074 if let Err(err) = validate_spec(&configured.module_spec()) {
1075 return Ok(vec![control_error_frame(
1076 &frame,
1077 "invalid_daemon_config",
1078 format!("supervisor rescan rejected daemon config: {err}"),
1079 )?]);
1080 }
1081 }
1082
1083 let configured_capabilities = modules
1084 .iter()
1085 .map(|module| (module.module_id.clone(), module.enabled))
1086 .collect::<Vec<_>>();
1087 let preview_capability_warnings = if preview {
1088 let (_, registrations) = self.runtime_capability_snapshot()?;
1089 let current_modules = self
1090 .supervisor
1091 .list()
1092 .into_iter()
1093 .map(|module| module.module_id().to_string())
1094 .collect::<BTreeSet<_>>();
1095 let resulting_modules = configured_capabilities.clone();
1096 let removed = current_modules
1097 .into_iter()
1098 .filter(|module_id| {
1099 !resulting_modules
1100 .iter()
1101 .any(|(configured_id, _)| configured_id == module_id)
1102 })
1103 .collect::<Vec<_>>();
1104 let disabled = match &mode {
1107 RescanMode::Candidate(_) => resulting_modules
1108 .iter()
1109 .filter(|(_, enabled)| !enabled)
1110 .map(|(module_id, _)| module_id.clone())
1111 .collect::<Vec<_>>(),
1112 _ => Vec::new(),
1113 };
1114 self.capability_evaluator.preview_warnings(
1115 resulting_modules,
1116 &removed,
1117 &disabled,
1118 ®istrations,
1119 )
1120 } else {
1121 Vec::new()
1122 };
1123 let reconciled = match (&mode, approved_preview.as_ref()) {
1124 (RescanMode::Preview, Some(approved)) => Ok((
1125 config_gate::preview_approved_daemon(approved, &modules),
1126 Vec::new(),
1127 )),
1128 (RescanMode::Candidate(candidate), _) => self
1129 .preview_candidate(&context, modules, candidate)
1130 .map(|result| (result, Vec::new())),
1131 _ => {
1132 self.reconcile_supervised_modules(
1133 &context.supervisor,
1134 modules,
1135 preview,
1136 requester.clone(),
1137 )
1138 .await
1139 }
1140 };
1141 let (result, changed) = match reconciled {
1142 Ok(result) => result,
1143 Err(message) => {
1144 return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
1145 }
1146 };
1147 if !preview {
1148 self.rescan_policy_root(config.agent_policy_root).await;
1149 if let Some(ledger) = &self.activity {
1150 ledger.module_rescanned(&result.added, &result.removed, requester.clone());
1151 ledger.config_changed(&result.added, &result.removed, &changed, requester);
1152 }
1153 if let Err(code) = self.configure_activity(activity_config).await {
1154 warn!(
1155 code,
1156 "activity retention could not be applied during rescan"
1157 );
1158 }
1159 self.capability_evaluator
1160 .configure(configured_capabilities, reserved_capabilities);
1161 self.capability_evaluator.wake_deadline_loop();
1162 self.refresh_capability_requirements();
1163 }
1164 let mut result = result;
1165 result.restart_required = restart_required;
1166 result.capability_warnings = preview_capability_warnings;
1167 let response = ClientControlResponse::SupervisorRescan { result };
1168 Ok(vec![control_response_body_frame(
1169 &frame,
1170 &response,
1171 "ClientControlResponse::SupervisorRescan",
1172 )?])
1173 }
1174}
1175
1176impl ControlHandler {
1177 fn plan_rescan(
1181 &self,
1182 configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
1183 default_drain_timeout: Duration,
1184 ) -> Result<RescanPlan, String> {
1185 let staged_drain_timeouts = self.rescan.as_ref().map(|context| {
1186 context
1187 .module_entries
1188 .lock()
1189 .unwrap_or_else(|e| e.into_inner())
1190 .configured
1191 .iter()
1192 .map(|(id, entry)| {
1193 (
1194 id.clone(),
1195 configured_drain_timeout(entry, default_drain_timeout),
1196 )
1197 })
1198 .collect::<BTreeMap<_, _>>()
1199 });
1200 let mut current = BTreeMap::new();
1201 for module in self.supervisor.list() {
1202 let (spec, health) = module.configuration().map_err(|err| {
1203 format!(
1204 "failed to read configuration for module_id '{}': {err}",
1205 module.module_id()
1206 )
1207 })?;
1208 let status = module.status().map_err(|err| {
1209 format!(
1210 "failed to read status for module_id '{}': {err}",
1211 module.module_id()
1212 )
1213 })?;
1214 let staged_drain_timeout = staged_drain_timeouts
1215 .as_ref()
1216 .and_then(|timeouts| timeouts.get(module.module_id()))
1217 .copied();
1218 current.insert(
1219 module.module_id().to_string(),
1220 CurrentModule {
1221 module,
1222 spec,
1223 health,
1224 enabled: status.enabled,
1225 drain_timeout: status.drain_timeout,
1226 staged_drain_timeout,
1227 },
1228 );
1229 }
1230 let configured = configured_modules
1231 .into_iter()
1232 .map(|module| (module.module_id.clone(), module))
1233 .collect::<BTreeMap<_, _>>();
1234
1235 let added = configured
1236 .keys()
1237 .filter(|module_id| !current.contains_key(*module_id))
1238 .cloned()
1239 .collect::<Vec<_>>();
1240 let removed = current
1241 .keys()
1242 .filter(|module_id| !configured.contains_key(*module_id))
1243 .cloned()
1244 .collect::<Vec<_>>();
1245 let mut changed_pending_reload = Vec::new();
1246 let mut changed_pending = Vec::new();
1247 let mut configuration_changes = BTreeSet::new();
1248 let mut enabled_changes = BTreeSet::new();
1249 let mut unchanged = 0_u32;
1250 let publication = self
1251 .config_runtime
1252 .as_ref()
1253 .and_then(|owner| owner.polled_snapshot().ok());
1254
1255 for (module_id, configured_module) in &configured {
1256 let Some(current) = current.get(module_id) else {
1257 continue;
1258 };
1259 let launch_changed = current.spec != configured_module.module_spec();
1263 let drain_timeout = configured_drain_timeout(configured_module, default_drain_timeout);
1264 let drain_changed = current.drain_changed(drain_timeout);
1265 let configuration_changed =
1266 launch_changed || current.health != configured_module.health || drain_changed;
1267 let pending = self.pending_module_fields(
1268 ¤t.module,
1269 Some(configured_module),
1270 configuration_changed,
1271 Self::registration_channel_in_force(
1272 publication
1273 .as_ref()
1274 .and_then(|view| view.registration_declaration(module_id))
1275 .as_deref(),
1276 publication
1277 .as_ref()
1278 .and_then(|view| match &view.approved_daemon {
1279 crate::config_gate::runtime::ApprovedDaemonView::Approved {
1280 config,
1281 ..
1282 } => config
1283 .modules
1284 .iter()
1285 .find(|entry| entry.module_id == *module_id)
1286 .map(|entry| entry.registration_channel),
1287 _ => None,
1288 }),
1289 ),
1290 publication.as_deref(),
1291 )?;
1292 let has_pending = !pending.is_empty();
1293 if has_pending {
1294 changed_pending.push(subc_control::SupervisorPendingModule {
1295 module_id: module_id.clone(),
1296 fields: pending
1297 .into_iter()
1298 .map(|mut field| {
1299 field.value = None;
1300 field
1301 })
1302 .collect(),
1303 });
1304 }
1305 let enabled_changed = current.enabled != configured_module.enabled
1308 || self
1309 .capability_evaluator
1310 .configured_enabled(module_id)
1311 .is_some_and(|enabled| enabled != configured_module.enabled);
1312 if configuration_changed {
1313 configuration_changes.insert(module_id.clone());
1314 }
1315 if launch_changed {
1316 changed_pending_reload.push(module_id.clone());
1317 }
1318 if enabled_changed {
1319 enabled_changes.insert(module_id.clone());
1320 }
1321 if !configuration_changed && !enabled_changed && !has_pending {
1322 unchanged = unchanged.saturating_add(1);
1323 }
1324 }
1325 Ok(RescanPlan {
1326 current,
1327 configured,
1328 added,
1329 removed,
1330 changed_pending_reload,
1331 changed_pending,
1332 configuration_changes,
1333 enabled_changes,
1334 unchanged,
1335 })
1336 }
1337
1338 pub(super) async fn reconcile_supervised_modules(
1347 &self,
1348 supervisor: &Supervisor,
1349 configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
1350 preview: bool,
1351 requester: Principal,
1352 ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
1353 let default_drain_timeout = supervisor.default_drain_timeout();
1354 let plan = self.plan_rescan(configured_modules, default_drain_timeout)?;
1355
1356 if preview {
1362 return Ok((plan.preview_result(), Vec::new()));
1363 }
1364 let changed = plan
1365 .configuration_changes
1366 .union(&plan.enabled_changes)
1367 .cloned()
1368 .collect::<Vec<_>>();
1369 let RescanPlan {
1370 current,
1371 configured,
1372 added,
1373 removed,
1374 changed_pending_reload,
1375 mut changed_pending,
1376 configuration_changes,
1377 enabled_changes,
1378 unchanged,
1379 } = plan;
1380 if !(added.is_empty()
1385 && removed.is_empty()
1386 && configuration_changes.is_empty()
1387 && changed_pending.is_empty()
1388 && enabled_changes.is_empty())
1389 {
1390 if let Some(context) = &self.rescan {
1391 context
1392 .generation
1393 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1394 }
1395 }
1396
1397 for module_id in &removed {
1398 let module = ¤t
1399 .get(module_id)
1400 .expect("removed module came from current supervisor state")
1401 .module;
1402 module
1403 .retire_requested(Some(requester.clone()))
1404 .await
1405 .map_err(|err| {
1406 format!("failed to retire module_id '{module_id}' during rescan: {err}")
1407 })?;
1408 self.supervisor.record_rescan_removal(module_id);
1442 self.supervisor.retire(module_id);
1443 self.route_outages.forget(module_id);
1444 }
1445
1446 for module_id in configured.keys() {
1447 let Some(current) = current.get(module_id) else {
1448 continue;
1449 };
1450 let module = ¤t.module;
1451 let configured_module = configured
1452 .get(module_id)
1453 .expect("configured module id came from configured map");
1454 if configuration_changes.contains(module_id) {
1455 module
1456 .update_configuration(
1457 configured_module.module_spec(),
1458 configured_module.health.clone(),
1459 configured_module.drain_timeout_ms,
1460 )
1461 .await
1462 .map_err(|err| {
1463 format!(
1464 "failed to update module_id '{module_id}' configuration during rescan: {err}"
1465 )
1466 })?;
1467 let effective = module
1468 .status()
1469 .map_err(|err| err.to_string())?
1470 .drain_timeout;
1471 let configured = configured_drain_timeout(configured_module, default_drain_timeout);
1472 if let Some(mut field) = pending_drain_timeout(effective, configured) {
1473 field.value = None;
1474 if let Some(pending) = changed_pending
1475 .iter_mut()
1476 .find(|pending| pending.module_id == *module_id)
1477 {
1478 pending.fields.push(field);
1479 } else {
1480 changed_pending.push(subc_control::SupervisorPendingModule {
1481 module_id: module_id.clone(),
1482 fields: vec![field],
1483 });
1484 }
1485 }
1486 }
1487 if current.enabled != configured_module.enabled {
1490 self.route_outages.mark_operator_action(module_id);
1493 module
1494 .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
1495 .await
1496 .map_err(|err| {
1497 self.route_outages.operator_action_ended_unrefused(module_id);
1498 format!(
1499 "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
1500 configured_module.enabled
1501 )
1502 })?;
1503 }
1504 }
1505 changed_pending.sort_by(|a, b| a.module_id.cmp(&b.module_id));
1506
1507 for module_id in &added {
1508 let configured_module = configured
1509 .get(module_id)
1510 .expect("added module id came from configured map");
1511 supervisor
1512 .supervise_configured_requested_async(
1513 configured_module.module_spec(),
1514 configured_module.enabled,
1515 configured_module.health.clone(),
1516 configured_module.drain_timeout_ms,
1517 configured_module.restart,
1518 configured_module.register_timeout,
1519 Some(requester.clone()),
1520 )
1521 .await
1522 .map_err(|err| {
1523 format!("failed to add module_id '{module_id}' during rescan: {err}")
1524 })?;
1525 }
1526
1527 if let Some(context) = &self.rescan {
1528 let mut entries = context
1529 .module_entries
1530 .lock()
1531 .unwrap_or_else(|e| e.into_inner());
1532 entries.record(&configured, &added, &removed);
1533 }
1534
1535 Ok((
1536 SupervisorRescanResult {
1537 added,
1538 removed,
1539 changed_pending_reload,
1540 changed_pending,
1541 enabled_changes: enabled_changes.iter().cloned().collect(),
1542 unchanged,
1543 preview: false,
1544 restart_required: Vec::new(),
1547 capability_warnings: Vec::new(),
1548 module_actions: Vec::new(),
1549 earlier_pending: Vec::new(),
1550 expect: None,
1551 },
1552 changed,
1553 ))
1554 }
1555}