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