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.capabilities_with_settings();
374 if self.rescan.is_some() {
375 capabilities.push(RESCAN_CANDIDATE_PREVIEW_CAPABILITY.to_string());
376 }
377 capabilities
378 }
379
380 fn staged_generation(&self, context: &SupervisorRescanContext) -> StagedGeneration {
381 StagedGeneration {
382 incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
383 counter: context.generation.load(Ordering::SeqCst),
384 }
385 }
386
387 pub(super) async fn handle_supervisor_rescan_checked(
388 &self,
389 ctx: &RouteCtx,
390 frame: Frame,
391 preview: bool,
392 candidate: Option<String>,
393 expect: Option<RescanExpect>,
394 ) -> Result<Vec<Frame>, RouterError> {
395 let corr = frame.header.corr;
396 let mode = match (preview, candidate, expect) {
397 (true, Some(candidate), None) => {
398 if candidate.len() > RESCAN_CANDIDATE_MAX_BYTES {
399 return Ok(vec![control_error_frame(
400 &frame,
401 RESCAN_CANDIDATE_TOO_LARGE,
402 format!(
403 "the candidate config is {} bytes; a preview accepts at most {RESCAN_CANDIDATE_MAX_BYTES}",
404 candidate.len()
405 ),
406 )?]);
407 }
408 RescanMode::Candidate(candidate)
409 }
410 (false, None, Some(expect)) => {
411 self.log_supervisor_request_received(
412 ctx,
413 corr,
414 ops::SUPERVISOR_RESCAN_CHECKED,
415 None,
416 None,
417 )?;
418 RescanMode::Checked(expect)
419 }
420 _ => {
421 return Ok(vec![control_error_frame(
422 &frame,
423 "invalid_control_body",
424 "supervisor.rescan_checked takes either preview: true with a candidate and \
425 no expect, or preview: false with an expect and no candidate",
426 )?]);
427 }
428 };
429 let requester = self.supervisor_requester(ctx, corr)?;
430 self.handle_supervisor_rescan(frame, mode, requester).await
431 }
432
433 pub(super) async fn rescan_input(
438 &self,
439 mode: &RescanMode,
440 context: &SupervisorRescanContext,
441 ) -> Result<RescanInput, RescanInputError> {
442 use tokio::time::{timeout_at, Instant};
443 use RescanInputError::Config;
444
445 let staged = self.staged_generation(context);
446 let (config, approved_preview) = if matches!(mode, RescanMode::Candidate(_)) {
447 (Self::read_rescan_config(mode, &context.config_path)?, None)
448 } else {
449 let deadline = Instant::now() + CONFIG_READ_DEADLINE;
450 let timed_out = || {
451 Config(
452 "rescan_config_read_timeout",
453 format!(
454 "supervisor rescan timed out reading daemon config at {}; nothing was applied",
455 context.config_path.display()
456 ),
457 )
458 };
459 let permit = timeout_at(deadline, CONFIG_READ_SLOTS.acquire())
460 .await
461 .map_err(|_| timed_out())?
462 .expect("rescan read slots never close");
463 if Instant::now() >= deadline {
464 return Err(timed_out());
465 }
466 let path = context.config_path.clone();
467 let owner = if matches!(mode, RescanMode::Preview) {
468 self.config_runtime.clone()
469 } else {
470 None
471 };
472 let mode = mode.clone();
473 let (send, recv) = tokio::sync::oneshot::channel();
474 std::thread::Builder::new()
475 .name("rescan-config-read".into())
476 .spawn(move || {
477 let _permit = permit;
478 let result = (|| {
479 let config = Self::read_rescan_config(&mode, &path)?;
480 let approved = if let Some(owner) = owner.filter(|_| !send.is_closed()) {
484 owner
485 .observe_file_proposal()
486 .map_err(RescanInputError::Gate)?;
487 owner
488 .approved_daemon_configuration()
489 .map_err(RescanInputError::Gate)?
490 } else {
491 None
492 };
493 Ok((config, approved))
494 })();
495 let _ = send.send(result);
496 })
497 .map_err(|error| {
498 Config(
499 "rescan_failed",
500 format!("could not start supervisor rescan config read: {error}"),
501 )
502 })?;
503 let result = timeout_at(deadline, recv).await.map_err(|_| timed_out())?;
504 if Instant::now() >= deadline {
507 return Err(timed_out());
508 }
509 result.map_err(|error| {
510 Config(
511 "rescan_failed",
512 format!("supervisor rescan config reader stopped: {error}"),
513 )
514 })??
515 };
516
517 let guard = self.supervisor.operation_lock().lock_owned().await;
518 let current = self.staged_generation(context);
519 let changed = match mode {
520 RescanMode::Candidate(_) => None,
521 RescanMode::Checked(expect) if current != expect.staged_generation => Some((
522 CONFIG_CHANGED_SINCE_PREVIEW,
523 &expect.staged_generation,
524 "after the preview",
525 )),
526 _ if current != staged => {
527 Some(("rescan_failed", &staged, "while reading daemon config"))
528 }
529 _ => None,
530 };
531 if let Some((code, before, reason)) = changed {
532 return Err(Config(code, format!(
533 "the daemon's staged configuration changed {reason} (was {}:{}, now {}:{}); nothing was applied",
534 before.incarnation, before.counter, current.incarnation, current.counter,
535 )));
536 }
537 Ok(RescanInput {
538 config,
539 approved_preview,
540 guard,
541 })
542 }
543
544 fn read_rescan_config(
545 mode: &RescanMode,
546 path: &Path,
547 ) -> Result<Option<(DaemonConfig, ActivityConfig)>, RescanInputError> {
548 let rejected = |err: crate::daemon_config::DaemonConfigError| {
549 RescanInputError::Config(
550 "invalid_daemon_config",
551 format!("supervisor rescan rejected daemon config: {err}"),
552 )
553 };
554 match mode {
555 RescanMode::Execute | RescanMode::Preview => {
556 crate::daemon_config::load_with_activity(path).map_err(rejected)
557 }
558 RescanMode::Candidate(candidate) => {
559 crate::daemon_config::parse_with_activity(candidate, path)
560 .map(Some)
561 .map_err(rejected)
562 }
563 RescanMode::Checked(expect) => {
564 let doc = Self::checked_config_doc(path, expect)?;
565 crate::daemon_config::parse_with_activity(&doc, path)
566 .map(Some)
567 .map_err(rejected)
568 }
569 }
570 }
571
572 fn checked_config_doc(path: &Path, expect: &RescanExpect) -> Result<String, RescanInputError> {
575 use RescanInputError::Config;
576 let bytes = match std::fs::read(path) {
577 Ok(bytes) => bytes,
578 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
579 return Err(Config(
580 CONFIG_CHANGED_SINCE_PREVIEW,
581 format!(
582 "daemon config not found at {}; nothing was applied",
583 path.display()
584 ),
585 ));
586 }
587 Err(err) => {
588 return Err(Config(
589 "invalid_daemon_config",
590 format!(
591 "supervisor rescan could not read daemon config at {}: {err}",
592 path.display()
593 ),
594 ));
595 }
596 };
597 if !sha256_hex(&bytes).eq_ignore_ascii_case(&expect.config_sha256) {
598 return Err(Config(
599 CONFIG_CHANGED_SINCE_PREVIEW,
600 format!(
601 "daemon config at {} is not the text that was previewed; nothing was applied",
602 path.display(),
603 ),
604 ));
605 }
606 String::from_utf8(bytes).map_err(|err| {
609 Config(
610 "invalid_daemon_config",
611 format!("daemon config at {} is not UTF-8: {err}", path.display()),
612 )
613 })
614 }
615
616 pub(super) fn preview_candidate(
621 &self,
622 context: &SupervisorRescanContext,
623 modules: Vec<ConfiguredModule>,
624 candidate: &str,
625 ) -> Result<SupervisorRescanResult, String> {
626 let plan = self.plan_rescan(modules)?;
627 let mut result = plan.preview_result();
628 let default_drain_ms = duration_ms(context.supervisor.default_drain_timeout());
629 let module_ids = plan
630 .current
631 .keys()
632 .chain(plan.configured.keys())
633 .collect::<BTreeSet<_>>();
634 let mut drained = BTreeSet::new();
635 for module_id in module_ids {
636 let current = plan.current.get(module_id);
637 let configured = plan.configured.get(module_id);
638 let (action, changed) = match (current, configured) {
639 (None, Some(configured)) if configured.enabled => {
640 (RescanModuleActionKind::Start, Vec::new())
641 }
642 (Some((_, _, _, true)), None) => (RescanModuleActionKind::Stop, Vec::new()),
643 (Some((_, _, _, enabled)), Some(configured)) if *enabled != configured.enabled => {
644 if configured.enabled {
645 (RescanModuleActionKind::Start, Vec::new())
646 } else {
647 (RescanModuleActionKind::Stop, Vec::new())
648 }
649 }
650 (Some((_, spec, health, enabled)), Some(configured))
651 if plan.configuration_changes.contains(module_id) =>
652 {
653 let changed = changed_parts(spec, health, configured);
654 if *enabled && plan.changed_pending_reload.contains(module_id) {
659 (RescanModuleActionKind::Restart, changed)
660 } else {
661 (RescanModuleActionKind::Reload, changed)
662 }
663 }
664 _ => continue,
665 };
666 let mut entry = RescanModuleAction {
667 module_id: module_id.clone(),
668 action,
669 changed,
670 drain_timeout_ms: None,
671 busy_gauges: Vec::new(),
672 };
673 if matches!(
674 entry.action,
675 RescanModuleActionKind::Restart | RescanModuleActionKind::Stop
676 ) {
677 if let Some((module, ..)) = current {
678 let status = module.status().map_err(|err| {
679 format!("failed to read status for module_id '{module_id}': {err}")
680 })?;
681 entry.drain_timeout_ms = Some(match configured {
685 Some(configured) if plan.configuration_changes.contains(module_id) => {
686 configured.drain_timeout_ms.unwrap_or(default_drain_ms)
687 }
688 _ => duration_ms(status.drain_timeout),
689 });
690 let metrics = status
691 .health
692 .metrics
693 .as_ref()
694 .and_then(serde_json::Value::as_object);
695 entry.busy_gauges =
696 crate::supervise::declared_busy_gauges(&self.registry, module_id)
697 .map_err(|err| {
698 format!(
699 "failed to read busy gauges for module_id '{module_id}': {err}"
700 )
701 })?
702 .into_iter()
703 .map(|gauge| BusyGaugeReading {
704 value: metrics.and_then(|metrics| metrics.get(&gauge)).cloned(),
705 gauge,
706 })
707 .collect();
708 }
709 drained.insert(module_id.clone());
710 }
711 result.module_actions.push(entry);
712 }
713 for (module_id, (module, spec, _, _)) in &plan.current {
714 if drained.contains(module_id) {
715 continue;
716 }
717 let status = module.status().map_err(|err| {
718 format!("failed to read status for module_id '{module_id}': {err}")
719 })?;
720 if launch_spec_agreement(
721 spec,
722 status.process_alive,
723 status.launch_spec_digest.as_ref(),
724 ) == LaunchSpecAgreement::Mismatch
725 {
726 result.earlier_pending.push(module_id.clone());
727 }
728 }
729 result.expect = Some(RescanExpect {
730 config_sha256: sha256_hex(candidate.as_bytes()),
731 staged_generation: self.staged_generation(context),
732 });
733 Ok(result)
734 }
735}
736
737#[cfg(all(test, unix))]
738#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
739async fn stalled_config_read_times_out_without_holding_operation_lock() {
740 use crate::{Registry, RestartPolicy, Supervisor, SupervisorHandle};
741 use cortexkit_test_support::ScratchDir;
742 use std::io::Write;
743 use std::sync::{mpsc, Arc};
744 use subc_protocol::{FrameType, Principal};
745
746 let dir = ScratchDir::new("rescan-stalled-file");
747 let path = dir.join("subc.jsonc");
748 assert!(std::process::Command::new("mkfifo")
749 .arg(&path)
750 .status()
751 .unwrap()
752 .success());
753 let registry = Arc::new(Registry::default());
754 let handle = SupervisorHandle::new();
755 let supervisor =
756 Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
757 let handler = Arc::new(
758 ControlHandler::new(registry)
759 .with_supervisor(handle.clone())
760 .with_supervisor_rescan(supervisor, &path, None),
761 );
762 let (opened, is_open) = tokio::sync::oneshot::channel();
763 let (release, released) = mpsc::channel();
764 let feeder = std::thread::spawn(move || {
765 let mut fifo = std::fs::OpenOptions::new().write(true).open(path).unwrap();
766 opened.send(()).unwrap();
767 released.recv_timeout(Duration::from_secs(10)).unwrap();
768 let _ = fifo.write_all(br#"{"version":1,"modules":{"never-applied":{"program":"/bin/true","protocol":"none","enabled":false}}}"#);
769 });
770 let request = tokio::spawn({
771 let handler = Arc::clone(&handler);
772 async move {
773 let frame = Frame::build(
774 FrameType::Request,
775 super::control_flags(),
776 0,
777 0,
778 1,
779 Vec::new(),
780 )
781 .unwrap();
782 handler
783 .handle_supervisor_rescan(frame, RescanMode::Execute, Principal::Direct)
784 .await
785 .unwrap()
786 .remove(0)
787 }
788 });
789 tokio::time::timeout(Duration::from_secs(2), is_open)
790 .await
791 .unwrap()
792 .unwrap();
793
794 let frame = Frame::build(
797 FrameType::Request,
798 super::control_flags(),
799 0,
800 0,
801 2,
802 Vec::new(),
803 )
804 .unwrap();
805 let restart = tokio::time::timeout(
806 Duration::from_secs(1),
807 handler.handle_supervisor_restart(frame, "missing".into(), None, Principal::Direct),
808 )
809 .await;
810 let mut request = request;
811 let reply = tokio::time::timeout(Duration::from_secs(6), &mut request).await;
812 release.send(()).unwrap();
813 feeder.join().unwrap();
814 let restart = restart
815 .expect("the rescan held the supervisor operation lock during its config read")
816 .unwrap()
817 .remove(0);
818 let body: serde_json::Value = serde_json::from_slice(&restart.body).unwrap();
819 assert_eq!(body["code"], "unknown_module");
820 let reply = reply
821 .expect("rescan did not answer before the config reader was released")
822 .unwrap();
823 assert_eq!(reply.header.ty, FrameType::Error);
824 let body: serde_json::Value = serde_json::from_slice(&reply.body).unwrap();
825 assert_eq!(body["code"], "rescan_config_read_timeout");
826 assert!(body["message"].as_str().unwrap().contains("subc.jsonc"));
827 assert!(handle.list().is_empty());
828 assert_eq!(
829 handler
830 .rescan
831 .as_ref()
832 .unwrap()
833 .generation
834 .load(Ordering::SeqCst),
835 0
836 );
837}
838
839#[derive(Debug, Clone)]
840pub(super) struct SupervisorRescanContext {
841 pub(super) supervisor: Supervisor,
842 pub(super) config_path: PathBuf,
843 pub(super) configured_port: Option<u16>,
844 pub(super) storage_config: Option<crate::daemon_config::StorageConfig>,
845 pub(super) admission_facts_carrier_module_id: Option<String>,
846 pub(super) admission_facts_targets: Option<Vec<String>>,
847 pub(super) scope_authority_owners: Vec<String>,
848 federated_scope_owner: String,
849 pub(super) privileged_operator_prompt: PrivilegedOperatorPrompt,
850 generation: Arc<std::sync::atomic::AtomicU64>,
856 rescan_lock: Arc<tokio::sync::Mutex<()>>,
857 pub(super) module_entries: Arc<Mutex<rescan_checked::ModuleEntries>>,
858}
859
860impl ControlHandler {
861 pub fn with_supervisor_rescan(
862 mut self,
863 supervisor: Supervisor,
864 config_path: impl Into<PathBuf>,
865 configured_port: Option<u16>,
866 ) -> Self {
867 self.rescan = Some(SupervisorRescanContext {
868 supervisor,
869 config_path: config_path.into(),
870 configured_port,
871 storage_config: self.storage_config.clone(),
872 admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
873 admission_facts_targets: self.admission_facts_targets.clone(),
874 scope_authority_owners: self.scope_authority_owners.clone(),
875 federated_scope_owner: self.federated_scope_owner.clone(),
876 privileged_operator_prompt: self.privileged_operator_prompt,
877 generation: Arc::default(),
878 rescan_lock: Arc::default(),
879 module_entries: Arc::default(),
880 });
881 self
882 }
883
884 pub(crate) fn with_supervisor_rescan_entries(
885 self,
886 modules: &[crate::daemon_config::ConfiguredModule],
887 ) -> Self {
888 if let Some(context) = &self.rescan {
889 let mut entries = context
890 .module_entries
891 .lock()
892 .unwrap_or_else(|e| e.into_inner());
893 entries.seed(modules);
894 }
895 self
896 }
897}
898
899impl ControlHandler {
900 pub(super) async fn handle_supervisor_rescan(
904 &self,
905 frame: Frame,
906 mode: RescanMode,
907 requester: Principal,
908 ) -> Result<Vec<Frame>, RouterError> {
909 let preview = mode.previews();
910 let Some(context) = self.rescan.clone() else {
911 return Ok(vec![control_error_frame(
912 &frame,
913 "rescan_unavailable",
914 "the daemon was not started with a reloadable config path".to_string(),
915 )?]);
916 };
917
918 let _rescan_guard = context.rescan_lock.lock().await;
919 let rescan_checked::RescanInput {
920 config: loaded,
921 approved_preview,
922 guard: _operation_guard,
923 } = match self.rescan_input(&mode, &context).await {
924 Ok(input) => input,
925 Err(error) => return Ok(vec![error.into_frame(&frame)?]),
926 };
927 let Some((config, activity_config)) = loaded else {
935 return Ok(vec![control_error_frame(
936 &frame,
937 "invalid_daemon_config",
938 format!(
939 "daemon config not found at {}; refusing to rescan (an absent config would \
940 retire every supervised module)",
941 context.config_path.display()
942 ),
943 )?]);
944 };
945 let (
946 configured_port,
947 storage_config,
948 admission_facts_carrier_module_id,
949 admission_facts_targets,
950 scope_authority_owners,
951 federated_scope_owner,
952 privileged_operator_prompt,
953 modules,
954 reserved_capabilities,
955 ) = (
956 config.port,
957 config.storage,
958 config.admission_facts_carrier_module_id,
959 config.admission_facts_targets,
960 config.scope_authority_owners,
961 config.federated_scope_owner,
962 config.privileged_operator_prompt,
963 config.modules,
964 config.reserved_capabilities,
965 );
966
967 let mut restart_required = Vec::new();
976 for section in RestartRequiredSection::ALL {
977 let changed = match section {
978 RestartRequiredSection::Port => configured_port != context.configured_port,
979 RestartRequiredSection::Storage => storage_config != context.storage_config,
980 RestartRequiredSection::AdmissionFactsCarrierModuleId => {
981 admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
982 }
983 RestartRequiredSection::AdmissionFactsTargets => {
984 admission_facts_targets != context.admission_facts_targets
985 }
986 RestartRequiredSection::ScopeAuthorityOwners => {
987 scope_authority_owners != context.scope_authority_owners
988 }
989 RestartRequiredSection::FederatedScopeOwner => {
990 federated_scope_owner != context.federated_scope_owner
991 }
992 RestartRequiredSection::PrivilegedOperatorPrompt => {
993 privileged_operator_prompt != context.privileged_operator_prompt
994 }
995 };
996 if changed {
997 restart_required.push(section.label().to_string());
998 }
999 }
1000 if !restart_required.is_empty() {
1001 warn!(
1002 config_path = %context.config_path.display(),
1003 sections = %restart_required.join(", "),
1004 "daemon config changed outside the modules section; restart the daemon to apply those changes"
1005 );
1006 }
1007
1008 for configured in &modules {
1009 if let Err(err) = validate_spec(&configured.module_spec()) {
1010 return Ok(vec![control_error_frame(
1011 &frame,
1012 "invalid_daemon_config",
1013 format!("supervisor rescan rejected daemon config: {err}"),
1014 )?]);
1015 }
1016 }
1017
1018 let configured_capabilities = modules
1019 .iter()
1020 .map(|module| (module.module_id.clone(), module.enabled))
1021 .collect::<Vec<_>>();
1022 let preview_capability_warnings = if preview {
1023 let (_, registrations) = self.runtime_capability_snapshot()?;
1024 let current_modules = self
1025 .supervisor
1026 .list()
1027 .into_iter()
1028 .map(|module| module.module_id().to_string())
1029 .collect::<BTreeSet<_>>();
1030 let resulting_modules = configured_capabilities.clone();
1031 let removed = current_modules
1032 .into_iter()
1033 .filter(|module_id| {
1034 !resulting_modules
1035 .iter()
1036 .any(|(configured_id, _)| configured_id == module_id)
1037 })
1038 .collect::<Vec<_>>();
1039 let disabled = match &mode {
1042 RescanMode::Candidate(_) => resulting_modules
1043 .iter()
1044 .filter(|(_, enabled)| !enabled)
1045 .map(|(module_id, _)| module_id.clone())
1046 .collect::<Vec<_>>(),
1047 _ => Vec::new(),
1048 };
1049 self.capability_evaluator.preview_warnings(
1050 resulting_modules,
1051 &removed,
1052 &disabled,
1053 ®istrations,
1054 )
1055 } else {
1056 Vec::new()
1057 };
1058 let reconciled = match (&mode, approved_preview.as_ref()) {
1059 (RescanMode::Preview, Some(approved)) => Ok((
1060 config_gate::preview_approved_daemon(approved, &modules),
1061 Vec::new(),
1062 )),
1063 (RescanMode::Candidate(candidate), _) => self
1064 .preview_candidate(&context, modules, candidate)
1065 .map(|result| (result, Vec::new())),
1066 _ => {
1067 self.reconcile_supervised_modules(
1068 &context.supervisor,
1069 modules,
1070 preview,
1071 requester.clone(),
1072 )
1073 .await
1074 }
1075 };
1076 let (result, changed) = match reconciled {
1077 Ok(result) => result,
1078 Err(message) => {
1079 return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
1080 }
1081 };
1082 if !preview {
1083 self.rescan_policy_root(config.agent_policy_root).await;
1084 if let Some(ledger) = &self.activity {
1085 ledger.module_rescanned(&result.added, &result.removed, requester.clone());
1086 ledger.config_changed(&result.added, &result.removed, &changed, requester);
1087 }
1088 if let Err(code) = self.configure_activity(activity_config).await {
1089 warn!(
1090 code,
1091 "activity retention could not be applied during rescan"
1092 );
1093 }
1094 self.capability_evaluator
1095 .configure(configured_capabilities, reserved_capabilities);
1096 self.capability_evaluator.wake_deadline_loop();
1097 self.refresh_capability_requirements();
1098 }
1099 let mut result = result;
1100 result.restart_required = restart_required;
1101 result.capability_warnings = preview_capability_warnings;
1102 let response = ClientControlResponse::SupervisorRescan { result };
1103 Ok(vec![control_response_body_frame(
1104 &frame,
1105 &response,
1106 "ClientControlResponse::SupervisorRescan",
1107 )?])
1108 }
1109}
1110
1111impl ControlHandler {
1112 fn plan_rescan(
1116 &self,
1117 configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
1118 ) -> Result<RescanPlan, String> {
1119 let mut current = BTreeMap::new();
1120 for module in self.supervisor.list() {
1121 let (spec, health) = module.configuration().map_err(|err| {
1122 format!(
1123 "failed to read configuration for module_id '{}': {err}",
1124 module.module_id()
1125 )
1126 })?;
1127 let enabled = module
1128 .status()
1129 .map_err(|err| {
1130 format!(
1131 "failed to read status for module_id '{}': {err}",
1132 module.module_id()
1133 )
1134 })?
1135 .enabled;
1136 current.insert(
1137 module.module_id().to_string(),
1138 (module, spec, health, enabled),
1139 );
1140 }
1141 let configured = configured_modules
1142 .into_iter()
1143 .map(|module| (module.module_id.clone(), module))
1144 .collect::<BTreeMap<_, _>>();
1145
1146 let added = configured
1147 .keys()
1148 .filter(|module_id| !current.contains_key(*module_id))
1149 .cloned()
1150 .collect::<Vec<_>>();
1151 let removed = current
1152 .keys()
1153 .filter(|module_id| !configured.contains_key(*module_id))
1154 .cloned()
1155 .collect::<Vec<_>>();
1156 let mut changed_pending_reload = Vec::new();
1157 let mut changed_pending = Vec::new();
1158 let mut configuration_changes = BTreeSet::new();
1159 let mut enabled_changes = BTreeSet::new();
1160 let mut unchanged = 0_u32;
1161 let publication = self
1162 .config_runtime
1163 .as_ref()
1164 .and_then(|owner| owner.polled_snapshot().ok());
1165
1166 for (module_id, configured_module) in &configured {
1167 let Some((module, current_spec, current_health, current_enabled)) =
1168 current.get(module_id)
1169 else {
1170 continue;
1171 };
1172 let launch_changed = *current_spec != configured_module.module_spec();
1176 let configuration_changed =
1177 launch_changed || *current_health != configured_module.health;
1178 let pending = self.pending_module_fields(
1179 module,
1180 Some(configured_module),
1181 configuration_changed,
1182 Self::registration_channel_in_force(
1183 publication
1184 .as_ref()
1185 .and_then(|view| view.registration_declaration(module_id))
1186 .as_deref(),
1187 publication
1188 .as_ref()
1189 .and_then(|view| match &view.approved_daemon {
1190 crate::config_gate::runtime::ApprovedDaemonView::Approved {
1191 config,
1192 ..
1193 } => config
1194 .modules
1195 .iter()
1196 .find(|entry| entry.module_id == *module_id)
1197 .map(|entry| entry.registration_channel),
1198 _ => None,
1199 }),
1200 ),
1201 publication.as_deref(),
1202 )?;
1203 let has_pending = !pending.is_empty();
1204 if has_pending {
1205 changed_pending.push(subc_control::SupervisorPendingModule {
1206 module_id: module_id.clone(),
1207 fields: pending
1208 .into_iter()
1209 .map(|mut field| {
1210 field.value = None;
1211 field
1212 })
1213 .collect(),
1214 });
1215 }
1216 let enabled_changed = *current_enabled != configured_module.enabled
1219 || self
1220 .capability_evaluator
1221 .configured_enabled(module_id)
1222 .is_some_and(|enabled| enabled != configured_module.enabled);
1223 if configuration_changed {
1224 configuration_changes.insert(module_id.clone());
1225 }
1226 if launch_changed {
1227 changed_pending_reload.push(module_id.clone());
1228 }
1229 if enabled_changed {
1230 enabled_changes.insert(module_id.clone());
1231 }
1232 if !configuration_changed && !enabled_changed && !has_pending {
1233 unchanged = unchanged.saturating_add(1);
1234 }
1235 }
1236 Ok(RescanPlan {
1237 current,
1238 configured,
1239 added,
1240 removed,
1241 changed_pending_reload,
1242 changed_pending,
1243 configuration_changes,
1244 enabled_changes,
1245 unchanged,
1246 })
1247 }
1248
1249 pub(super) async fn reconcile_supervised_modules(
1258 &self,
1259 supervisor: &Supervisor,
1260 configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
1261 preview: bool,
1262 requester: Principal,
1263 ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
1264 let plan = self.plan_rescan(configured_modules)?;
1265
1266 if preview {
1272 return Ok((plan.preview_result(), Vec::new()));
1273 }
1274 let changed = plan
1275 .configuration_changes
1276 .union(&plan.enabled_changes)
1277 .cloned()
1278 .collect::<Vec<_>>();
1279 let RescanPlan {
1280 current,
1281 configured,
1282 added,
1283 removed,
1284 changed_pending_reload,
1285 changed_pending,
1286 configuration_changes,
1287 enabled_changes,
1288 unchanged,
1289 } = plan;
1290 if !(added.is_empty()
1295 && removed.is_empty()
1296 && configuration_changes.is_empty()
1297 && changed_pending.is_empty()
1298 && enabled_changes.is_empty())
1299 {
1300 if let Some(context) = &self.rescan {
1301 context
1302 .generation
1303 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1304 }
1305 }
1306
1307 for module_id in &removed {
1308 let module = ¤t
1309 .get(module_id)
1310 .expect("removed module came from current supervisor state")
1311 .0;
1312 module
1313 .retire_requested(Some(requester.clone()))
1314 .await
1315 .map_err(|err| {
1316 format!("failed to retire module_id '{module_id}' during rescan: {err}")
1317 })?;
1318 self.supervisor.record_rescan_removal(module_id);
1352 self.supervisor.retire(module_id);
1353 self.route_outages.forget(module_id);
1354 }
1355
1356 for module_id in configured.keys() {
1357 let Some((module, _, _, current_enabled)) = current.get(module_id) else {
1358 continue;
1359 };
1360 let configured_module = configured
1361 .get(module_id)
1362 .expect("configured module id came from configured map");
1363 if configuration_changes.contains(module_id) {
1364 module
1365 .update_configuration(
1366 configured_module.module_spec(),
1367 configured_module.health.clone(),
1368 configured_module.drain_timeout_ms,
1369 )
1370 .await
1371 .map_err(|err| {
1372 format!(
1373 "failed to update module_id '{module_id}' configuration during rescan: {err}"
1374 )
1375 })?;
1376 }
1377 if *current_enabled != configured_module.enabled {
1380 self.route_outages.mark_operator_action(module_id);
1383 module
1384 .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
1385 .await
1386 .map_err(|err| {
1387 self.route_outages.operator_action_ended_unrefused(module_id);
1388 format!(
1389 "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
1390 configured_module.enabled
1391 )
1392 })?;
1393 }
1394 }
1395
1396 for module_id in &added {
1397 let configured_module = configured
1398 .get(module_id)
1399 .expect("added module id came from configured map");
1400 supervisor
1401 .supervise_configured_requested_async(
1402 configured_module.module_spec(),
1403 configured_module.enabled,
1404 configured_module.health.clone(),
1405 configured_module.drain_timeout_ms,
1406 configured_module.restart,
1407 configured_module.register_timeout,
1408 Some(requester.clone()),
1409 )
1410 .await
1411 .map_err(|err| {
1412 format!("failed to add module_id '{module_id}' during rescan: {err}")
1413 })?;
1414 }
1415
1416 if let Some(context) = &self.rescan {
1417 let mut entries = context
1418 .module_entries
1419 .lock()
1420 .unwrap_or_else(|e| e.into_inner());
1421 entries.record(&configured, &added, &removed);
1422 }
1423
1424 Ok((
1425 SupervisorRescanResult {
1426 added,
1427 removed,
1428 changed_pending_reload,
1429 changed_pending,
1430 enabled_changes: enabled_changes.iter().cloned().collect(),
1431 unchanged,
1432 preview: false,
1433 restart_required: Vec::new(),
1436 capability_warnings: Vec::new(),
1437 module_actions: Vec::new(),
1438 earlier_pending: Vec::new(),
1439 expect: None,
1440 },
1441 changed,
1442 ))
1443 }
1444}