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